iroh_relay/
endpoint_info.rs

1//! Support for handling DNS resource records for dialing by [`EndpointId`].
2//!
3//! Dialing by [`EndpointId`] is supported by iroh endpoints publishing [Pkarr] records to DNS
4//! servers or the Mainline DHT.  This module supports creating and parsing these records.
5//!
6//! DNS records are published under the following names:
7//!
8//! `_iroh.<z32-endpoint-id>.<origin-domain> TXT`
9//!
10//! - `_iroh` is the record name as defined by [`IROH_TXT_NAME`].
11//!
12//! - `<z32-endpoint-id>` is the [z-base-32] encoding of the [`EndpointId`].
13//!
14//! - `<origin-domain>` is the domain name of the publishing DNS server,
15//!   [`N0_DNS_ENDPOINT_ORIGIN_PROD`] is the server operated by number0 for production.
16//!   [`N0_DNS_ENDPOINT_ORIGIN_STAGING`] is the server operated by number0 for testing.
17//!
18//! - `TXT` is the DNS record type.
19//!
20//! The returned TXT records must contain a string value of the form `key=value` as defined
21//! in [RFC1464].  The following attributes are defined:
22//!
23//! - `relay=<url>`: The home [`RelayUrl`] of this endpoint.
24//!
25//! - `addr=<addr> <addr>`: A space-separated list of sockets addresses for this iroh endpoint.
26//!   Each address is an IPv4 or IPv6 address with a port.
27//!
28//! [Pkarr]: https://app.pkarr.org
29//! [z-base-32]: https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
30//! [RFC1464]: https://www.rfc-editor.org/rfc/rfc1464
31//! [`RelayUrl`]: iroh_base::RelayUrl
32//! [`N0_DNS_ENDPOINT_ORIGIN_PROD`]: crate::dns::N0_DNS_ENDPOINT_ORIGIN_PROD
33//! [`N0_DNS_ENDPOINT_ORIGIN_STAGING`]: crate::dns::N0_DNS_ENDPOINT_ORIGIN_STAGING
34
35use std::{
36    collections::{BTreeMap, BTreeSet},
37    fmt::{self, Display},
38    hash::Hash,
39    net::SocketAddr,
40    str::{FromStr, Utf8Error},
41    sync::Arc,
42};
43
44use iroh_base::{EndpointAddr, EndpointId, KeyParsingError, RelayUrl, SecretKey, TransportAddr};
45use n0_error::{e, ensure, stack_error};
46use url::Url;
47
48/// The DNS name for the iroh TXT record.
49pub const IROH_TXT_NAME: &str = "_iroh";
50
51#[allow(missing_docs)]
52#[stack_error(derive, add_meta)]
53#[non_exhaustive]
54pub enum EncodingError {
55    #[error(transparent)]
56    FailedBuildingPacket {
57        #[error(std_err)]
58        source: pkarr::errors::SignedPacketBuildError,
59    },
60    #[error("invalid TXT entry")]
61    InvalidTxtEntry {
62        #[error(std_err)]
63        source: pkarr::dns::SimpleDnsError,
64    },
65}
66
67#[allow(missing_docs)]
68#[stack_error(derive, add_meta)]
69#[non_exhaustive]
70pub enum DecodingError {
71    #[error("endpoint id was not encoded in valid z32")]
72    InvalidEncodingZ32 {
73        #[error(std_err)]
74        source: z32::Z32Error,
75    },
76    #[error("length must be 32 bytes, but got {len} byte(s)")]
77    InvalidLength { len: usize },
78    #[error("endpoint id is not a valid public key")]
79    InvalidKey { source: KeyParsingError },
80}
81
82/// Extension methods for [`EndpointId`] to encode to and decode from [`z32`],
83/// which is the encoding used in [`pkarr`] domain names.
84pub trait EndpointIdExt {
85    /// Encodes a [`EndpointId`] in [`z-base-32`] encoding.
86    ///
87    /// [`z-base-32`]: https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
88    fn to_z32(&self) -> String;
89
90    /// Parses a [`EndpointId`] from [`z-base-32`] encoding.
91    ///
92    /// [`z-base-32`]: https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
93    fn from_z32(s: &str) -> Result<EndpointId, DecodingError>;
94}
95
96impl EndpointIdExt for EndpointId {
97    fn to_z32(&self) -> String {
98        z32::encode(self.as_bytes())
99    }
100
101    fn from_z32(s: &str) -> Result<EndpointId, DecodingError> {
102        let bytes =
103            z32::decode(s.as_bytes()).map_err(|err| e!(DecodingError::InvalidEncodingZ32, err))?;
104        let bytes: &[u8; 32] = &bytes
105            .try_into()
106            .map_err(|_| e!(DecodingError::InvalidLength { len: s.len() }))?;
107        let endpoint_id =
108            EndpointId::from_bytes(bytes).map_err(|err| e!(DecodingError::InvalidKey, err))?;
109        Ok(endpoint_id)
110    }
111}
112
113/// Data about an endpoint that may be published to and resolved from discovery services.
114///
115/// This includes an optional [`RelayUrl`], a set of direct addresses, and the optional
116/// [`UserData`], a string that can be set by applications and is not parsed or used by iroh
117/// itself.
118///
119/// This struct does not include the endpoint's [`EndpointId`], only the data *about* a certain
120/// endpoint. See [`EndpointInfo`] for a struct that contains a [`EndpointId`] with associated [`EndpointData`].
121#[derive(Debug, Clone, Default, Eq, PartialEq)]
122pub struct EndpointData {
123    /// addresses where this endpoint can be reached.
124    addrs: BTreeSet<TransportAddr>,
125    /// Optional user-defined [`UserData`] for this endpoint.
126    user_data: Option<UserData>,
127}
128
129impl EndpointData {
130    /// Creates a new [`EndpointData`] with a relay URL and a set of direct addresses.
131    pub fn new(addrs: impl IntoIterator<Item = TransportAddr>) -> Self {
132        Self {
133            addrs: addrs.into_iter().collect(),
134            user_data: None,
135        }
136    }
137
138    /// Sets the relay URL and returns the updated endpoint data.
139    pub fn with_relay_url(mut self, relay_url: Option<RelayUrl>) -> Self {
140        if let Some(url) = relay_url {
141            self.addrs.insert(TransportAddr::Relay(url));
142        }
143        self
144    }
145
146    /// Sets the direct addresses and returns the updated endpoint data.
147    pub fn with_ip_addrs(mut self, addresses: BTreeSet<SocketAddr>) -> Self {
148        for addr in addresses.into_iter() {
149            self.addrs.insert(TransportAddr::Ip(addr));
150        }
151        self
152    }
153
154    /// Sets the user-defined data and returns the updated endpoint data.
155    pub fn with_user_data(mut self, user_data: Option<UserData>) -> Self {
156        self.user_data = user_data;
157        self
158    }
159
160    /// Returns the relay URL of the endpoint.
161    pub fn relay_urls(&self) -> impl Iterator<Item = &RelayUrl> {
162        self.addrs.iter().filter_map(|addr| match addr {
163            TransportAddr::Relay(url) => Some(url),
164            _ => None,
165        })
166    }
167
168    /// Returns the optional user-defined data of the endpoint.
169    pub fn user_data(&self) -> Option<&UserData> {
170        self.user_data.as_ref()
171    }
172
173    /// Returns the direct addresses of the endpoint.
174    pub fn ip_addrs(&self) -> impl Iterator<Item = &SocketAddr> {
175        self.addrs.iter().filter_map(|addr| match addr {
176            TransportAddr::Ip(addr) => Some(addr),
177            _ => None,
178        })
179    }
180
181    /// Removes all direct addresses from the endpoint data.
182    pub fn clear_ip_addrs(&mut self) {
183        self.addrs
184            .retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
185    }
186
187    /// Removes all direct addresses from the endpoint data.
188    pub fn clear_relay_urls(&mut self) {
189        self.addrs
190            .retain(|addr| !matches!(addr, TransportAddr::Relay(_)));
191    }
192
193    /// Add addresses to the endpoint data.
194    pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>) {
195        for addr in addrs.into_iter() {
196            self.addrs.insert(addr);
197        }
198    }
199
200    /// Sets the user-defined data of the endpoint data.
201    pub fn set_user_data(&mut self, user_data: Option<UserData>) {
202        self.user_data = user_data;
203    }
204
205    /// Returns the full list of all known addresses
206    pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr> {
207        self.addrs.iter()
208    }
209
210    /// Does this have any addresses?
211    pub fn has_addrs(&self) -> bool {
212        !self.addrs.is_empty()
213    }
214
215    /// Apply the given filter to the current addresses.
216    ///
217    /// Returns a vec to allow re-ordering of addresses.
218    pub fn filtered_addrs(&self, filter: &AddrFilter) -> Vec<TransportAddr> {
219        filter.apply(&self.addrs)
220    }
221}
222
223/// The function type inside [`AddrFilter`].
224type AddrFilterFn = dyn Fn(&BTreeSet<TransportAddr>) -> Vec<TransportAddr> + Send + Sync + 'static;
225
226/// A filter and/or reordering function applied to transport addresses,
227/// typically used by AddressLookup services in iroh before publishing.
228///
229/// Takes the full set of transport addresses and returns them as an ordered `Vec`,
230/// allowing both filtering (by omitting addresses) and reordering (by controlling
231/// the output order). A `BTreeSet` cannot preserve a custom order, so the return
232/// type is `Vec` to make reordering possible.
233///
234/// See the documentation for each address lookup implementation for details on
235/// what additional filtering the implementation may perform on top.
236#[derive(Clone, Default)]
237pub struct AddrFilter(Option<Arc<AddrFilterFn>>);
238
239impl std::fmt::Debug for AddrFilter {
240    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241        if self.0.is_some() {
242            f.debug_struct("AddrFilter").finish_non_exhaustive()
243        } else {
244            write!(f, "identity")
245        }
246    }
247}
248
249impl AddrFilter {
250    /// Create a new [`AddrFilter`]
251    pub fn new(
252        f: impl Fn(&BTreeSet<TransportAddr>) -> Vec<TransportAddr> + Send + Sync + 'static,
253    ) -> Self {
254        Self(Some(Arc::new(f)))
255    }
256
257    /// Only keep relay addresses.
258    pub fn relay_only() -> Self {
259        Self::new(|addrs| addrs.iter().filter(|a| a.is_relay()).cloned().collect())
260    }
261
262    /// Only keep direct IP addresses.
263    pub fn ip_only() -> Self {
264        Self::new(|addrs| addrs.iter().filter(|a| !a.is_relay()).cloned().collect())
265    }
266
267    /// Apply the address filter function to a set of addresses.
268    pub fn apply(&self, addrs: &BTreeSet<TransportAddr>) -> Vec<TransportAddr> {
269        match &self.0 {
270            Some(f) => f(addrs),
271            None => addrs.iter().cloned().collect(),
272        }
273    }
274}
275
276impl From<EndpointAddr> for EndpointData {
277    fn from(endpoint_addr: EndpointAddr) -> Self {
278        Self {
279            addrs: endpoint_addr.addrs,
280            user_data: None,
281        }
282    }
283}
284
285// User-defined data that can be published and resolved through endpoint discovery.
286///
287/// Under the hood this is a UTF-8 String is no longer than [`UserData::MAX_LENGTH`] bytes.
288///
289/// Iroh does not keep track of or examine the user-defined data.
290///
291/// `UserData` implements [`FromStr`] and [`TryFrom<String>`], so you can
292/// convert `&str` and `String` into `UserData` easily.
293#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
294pub struct UserData(String);
295
296impl UserData {
297    /// The max byte length allowed for user-defined data.
298    ///
299    /// In DNS discovery services, the user-defined data is stored in a TXT record character string,
300    /// which has a max length of 255 bytes. We need to subtract the `user-data=` prefix,
301    /// which leaves 245 bytes for the actual user-defined data.
302    pub const MAX_LENGTH: usize = 245;
303}
304
305/// Error returned when an input value is too long for [`UserData`].
306#[allow(missing_docs)]
307#[stack_error(derive, add_meta)]
308#[error("max length exceeded")]
309pub struct MaxLengthExceededError {}
310
311impl TryFrom<String> for UserData {
312    type Error = MaxLengthExceededError;
313
314    fn try_from(value: String) -> Result<Self, Self::Error> {
315        ensure!(value.len() <= Self::MAX_LENGTH, MaxLengthExceededError);
316        Ok(Self(value))
317    }
318}
319
320impl FromStr for UserData {
321    type Err = MaxLengthExceededError;
322
323    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
324        ensure!(s.len() <= Self::MAX_LENGTH, MaxLengthExceededError);
325        Ok(Self(s.to_string()))
326    }
327}
328
329impl fmt::Display for UserData {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        write!(f, "{}", self.0)
332    }
333}
334
335impl AsRef<str> for UserData {
336    fn as_ref(&self) -> &str {
337        &self.0
338    }
339}
340
341/// Information about an endpoint that may be published to and resolved from discovery services.
342///
343/// This struct couples a [`EndpointId`] with its associated [`EndpointData`].
344#[derive(derive_more::Debug, Clone, Eq, PartialEq)]
345pub struct EndpointInfo {
346    /// The [`EndpointId`] of the endpoint this is about.
347    pub endpoint_id: EndpointId,
348    /// The information published about the endpoint.
349    pub data: EndpointData,
350}
351
352impl From<TxtAttrs<IrohAttr>> for EndpointInfo {
353    fn from(attrs: TxtAttrs<IrohAttr>) -> Self {
354        (&attrs).into()
355    }
356}
357
358impl From<&TxtAttrs<IrohAttr>> for EndpointInfo {
359    fn from(attrs: &TxtAttrs<IrohAttr>) -> Self {
360        use iroh_base::CustomAddr;
361
362        let endpoint_id = attrs.endpoint_id();
363        let attrs = attrs.attrs();
364        let relay_urls = attrs
365            .get(&IrohAttr::Relay)
366            .into_iter()
367            .flatten()
368            .filter_map(|s| Url::parse(s).ok())
369            .map(|url| TransportAddr::Relay(url.into()));
370        // Parse addresses: try IP first, then CustomAddr
371        let addrs = attrs
372            .get(&IrohAttr::Addr)
373            .into_iter()
374            .flatten()
375            .filter_map(|s| {
376                if let Ok(addr) = SocketAddr::from_str(s) {
377                    Some(TransportAddr::Ip(addr))
378                } else if let Ok(addr) = CustomAddr::from_str(s) {
379                    Some(TransportAddr::Custom(addr))
380                } else {
381                    None
382                }
383            });
384
385        let user_data = attrs
386            .get(&IrohAttr::UserData)
387            .into_iter()
388            .flatten()
389            .next()
390            .and_then(|s| UserData::from_str(s).ok());
391        let mut data = EndpointData::default();
392        data.set_user_data(user_data);
393        data.add_addrs(relay_urls.chain(addrs));
394
395        Self { endpoint_id, data }
396    }
397}
398
399impl From<EndpointInfo> for EndpointAddr {
400    fn from(value: EndpointInfo) -> Self {
401        value.into_endpoint_addr()
402    }
403}
404
405impl From<EndpointAddr> for EndpointInfo {
406    fn from(addr: EndpointAddr) -> Self {
407        let mut info = Self::new(addr.id);
408        info.add_addrs(addr.addrs);
409        info
410    }
411}
412
413impl EndpointInfo {
414    /// Creates a new [`EndpointInfo`] with an empty [`EndpointData`].
415    pub fn new(endpoint_id: EndpointId) -> Self {
416        Self::from_parts(endpoint_id, Default::default())
417    }
418
419    /// Creates a new [`EndpointInfo`] from its parts.
420    pub fn from_parts(endpoint_id: EndpointId, data: EndpointData) -> Self {
421        Self { endpoint_id, data }
422    }
423
424    /// Sets the relay URL and returns the updated endpoint info.
425    pub fn with_relay_url(mut self, relay_url: Option<RelayUrl>) -> Self {
426        self.data = self.data.with_relay_url(relay_url);
427        self
428    }
429
430    /// Sets the IP based addresses and returns the updated endpoint info.
431    pub fn with_ip_addrs(mut self, addrs: BTreeSet<SocketAddr>) -> Self {
432        self.data = self.data.with_ip_addrs(addrs);
433        self
434    }
435
436    /// Sets the user-defined data and returns the updated endpoint info.
437    pub fn with_user_data(mut self, user_data: Option<UserData>) -> Self {
438        self.data = self.data.with_user_data(user_data);
439        self
440    }
441
442    /// Converts into a [`EndpointAddr`] by cloning the needed fields.
443    pub fn to_endpoint_addr(&self) -> EndpointAddr {
444        EndpointAddr {
445            id: self.endpoint_id,
446            addrs: self.addrs.clone(),
447        }
448    }
449
450    /// Converts into a [`EndpointAddr`] without cloning.
451    pub fn into_endpoint_addr(self) -> EndpointAddr {
452        let Self { endpoint_id, data } = self;
453        EndpointAddr {
454            id: endpoint_id,
455            addrs: data.addrs,
456        }
457    }
458
459    fn to_attrs(&self) -> TxtAttrs<IrohAttr> {
460        self.into()
461    }
462
463    #[cfg(not(wasm_browser))]
464    /// Parses a [`EndpointInfo`] from DNS TXT lookup.
465    pub fn from_txt_lookup(
466        domain_name: String,
467        lookup: impl Iterator<Item = crate::dns::TxtRecordData>,
468    ) -> Result<Self, ParseError> {
469        let attrs = TxtAttrs::from_txt_lookup(domain_name, lookup)?;
470        Ok(Self::from(attrs))
471    }
472
473    /// Parses a [`EndpointInfo`] from a [`pkarr::SignedPacket`].
474    pub fn from_pkarr_signed_packet(packet: &pkarr::SignedPacket) -> Result<Self, ParseError> {
475        let attrs = TxtAttrs::from_pkarr_signed_packet(packet)?;
476        Ok(attrs.into())
477    }
478
479    /// Creates a [`pkarr::SignedPacket`].
480    ///
481    /// This constructs a DNS packet and signs it with a [`SecretKey`].
482    pub fn to_pkarr_signed_packet(
483        &self,
484        secret_key: &SecretKey,
485        ttl: u32,
486    ) -> Result<pkarr::SignedPacket, EncodingError> {
487        self.to_attrs().to_pkarr_signed_packet(secret_key, ttl)
488    }
489
490    /// Converts into a list of `{key}={value}` strings.
491    pub fn to_txt_strings(&self) -> Vec<String> {
492        self.to_attrs().to_txt_strings().collect()
493    }
494}
495
496#[allow(missing_docs)]
497#[stack_error(derive, add_meta, from_sources)]
498#[non_exhaustive]
499pub enum ParseError {
500    #[error("Expected format `key=value`, received `{s}`")]
501    UnexpectedFormat { s: String },
502    #[error("Could not convert key to Attr")]
503    AttrFromString { key: String },
504    #[error("Expected 2 labels, received {num_labels}")]
505    NumLabels { num_labels: usize },
506    #[error("Could not parse labels")]
507    Utf8 {
508        #[error(std_err)]
509        source: Utf8Error,
510    },
511    #[error("Record is not an `iroh` record, expected `_iroh`, got `{label}`")]
512    NotAnIrohRecord { label: String },
513    #[error(transparent)]
514    DecodingError { source: DecodingError },
515}
516
517impl std::ops::Deref for EndpointInfo {
518    type Target = EndpointData;
519    fn deref(&self) -> &Self::Target {
520        &self.data
521    }
522}
523
524impl std::ops::DerefMut for EndpointInfo {
525    fn deref_mut(&mut self) -> &mut Self::Target {
526        &mut self.data
527    }
528}
529
530/// Parses a [`EndpointId`] from iroh DNS name.
531///
532/// Takes a [`hickory_resolver::proto::rr::Name`] DNS name and expects the first label to be
533/// [`IROH_TXT_NAME`] and the second label to be a z32 encoded [`EndpointId`]. Ignores
534/// subsequent labels.
535#[cfg(not(wasm_browser))]
536fn endpoint_id_from_txt_name(name: &str) -> Result<EndpointId, ParseError> {
537    let num_labels = name.split(".").count();
538    if num_labels < 2 {
539        return Err(e!(ParseError::NumLabels { num_labels }));
540    }
541    let mut labels = name.split(".");
542    let label = labels.next().expect("checked above");
543    if label != IROH_TXT_NAME {
544        return Err(e!(ParseError::NotAnIrohRecord {
545            label: label.to_string()
546        }));
547    }
548    let label = labels.next().expect("checked above");
549    let endpoint_id = EndpointId::from_z32(label)?;
550    Ok(endpoint_id)
551}
552
553/// The attributes supported by iroh for [`IROH_TXT_NAME`] DNS resource records.
554///
555/// The resource record uses the lower-case names.
556#[derive(
557    Debug, strum::Display, strum::AsRefStr, strum::EnumString, Hash, Eq, PartialEq, Ord, PartialOrd,
558)]
559#[strum(serialize_all = "kebab-case")]
560pub(crate) enum IrohAttr {
561    /// URL of home relay.
562    Relay,
563    /// Address (IP or custom transport).
564    Addr,
565    /// User-defined data
566    UserData,
567}
568
569/// Attributes parsed from [`IROH_TXT_NAME`] TXT records.
570///
571/// This struct is generic over the key type. When using with [`String`], this will parse
572/// all attributes. Can also be used with an enum, if it implements [`FromStr`] and
573/// [`Display`].
574#[derive(Debug)]
575pub(crate) struct TxtAttrs<T> {
576    endpoint_id: EndpointId,
577    attrs: BTreeMap<T, Vec<String>>,
578}
579
580impl From<&EndpointInfo> for TxtAttrs<IrohAttr> {
581    fn from(info: &EndpointInfo) -> Self {
582        let mut attrs = vec![];
583        for addr in &info.data.addrs {
584            match addr {
585                TransportAddr::Relay(url) => attrs.push((IrohAttr::Relay, url.to_string())),
586                TransportAddr::Ip(addr) => attrs.push((IrohAttr::Addr, addr.to_string())),
587                TransportAddr::Custom(addr) => attrs.push((IrohAttr::Addr, addr.to_string())),
588                _ => {}
589            }
590        }
591
592        if let Some(user_data) = &info.data.user_data {
593            attrs.push((IrohAttr::UserData, user_data.to_string()));
594        }
595        Self::from_parts(info.endpoint_id, attrs.into_iter())
596    }
597}
598
599impl<T: FromStr + Display + Hash + Ord> TxtAttrs<T> {
600    /// Creates [`TxtAttrs`] from an endpoint id and an iterator of key-value pairs.
601    pub(crate) fn from_parts(
602        endpoint_id: EndpointId,
603        pairs: impl Iterator<Item = (T, String)>,
604    ) -> Self {
605        let mut attrs: BTreeMap<T, Vec<String>> = BTreeMap::new();
606        for (k, v) in pairs {
607            attrs.entry(k).or_default().push(v);
608        }
609        Self { attrs, endpoint_id }
610    }
611
612    /// Creates [`TxtAttrs`] from an endpoint id and an iterator of "{key}={value}" strings.
613    pub(crate) fn from_strings(
614        endpoint_id: EndpointId,
615        strings: impl Iterator<Item = String>,
616    ) -> Result<Self, ParseError> {
617        let mut attrs: BTreeMap<T, Vec<String>> = BTreeMap::new();
618        for s in strings {
619            let mut parts = s.split('=');
620            let (Some(key), Some(value)) = (parts.next(), parts.next()) else {
621                return Err(e!(ParseError::UnexpectedFormat { s }));
622            };
623            let attr = T::from_str(key).map_err(|_| {
624                e!(ParseError::AttrFromString {
625                    key: key.to_string()
626                })
627            })?;
628            attrs.entry(attr).or_default().push(value.to_string());
629        }
630        Ok(Self { attrs, endpoint_id })
631    }
632
633    /// Returns the parsed attributes.
634    pub(crate) fn attrs(&self) -> &BTreeMap<T, Vec<String>> {
635        &self.attrs
636    }
637
638    /// Returns the endpoint id.
639    pub(crate) fn endpoint_id(&self) -> EndpointId {
640        self.endpoint_id
641    }
642
643    /// Parses a [`pkarr::SignedPacket`].
644    pub(crate) fn from_pkarr_signed_packet(
645        packet: &pkarr::SignedPacket,
646    ) -> Result<Self, ParseError> {
647        use pkarr::dns::{
648            rdata::RData,
649            {self},
650        };
651        let pubkey = packet.public_key();
652        let pubkey_z32 = pubkey.to_z32();
653        let endpoint_id =
654            EndpointId::from_bytes(&pubkey.verifying_key().to_bytes()).expect("valid key");
655        let zone = dns::Name::new(&pubkey_z32).expect("z32 encoding is valid");
656        let txt_data = packet
657            .all_resource_records()
658            .filter_map(|rr| match &rr.rdata {
659                RData::TXT(txt) => match rr.name.without(&zone) {
660                    Some(name) if name.to_string() == IROH_TXT_NAME => Some(txt),
661                    Some(_) | None => None,
662                },
663                _ => None,
664            });
665
666        let txt_strs = txt_data.filter_map(|s| String::try_from(s.clone()).ok());
667        Self::from_strings(endpoint_id, txt_strs)
668    }
669
670    /// Parses a TXT records lookup.
671    #[cfg(not(wasm_browser))]
672    pub(crate) fn from_txt_lookup(
673        name: String,
674        lookup: impl Iterator<Item = crate::dns::TxtRecordData>,
675    ) -> Result<Self, ParseError> {
676        let queried_endpoint_id = endpoint_id_from_txt_name(&name)?;
677
678        let strings = lookup.map(|record| record.to_string());
679        Self::from_strings(queried_endpoint_id, strings)
680    }
681
682    fn to_txt_strings(&self) -> impl Iterator<Item = String> + '_ {
683        self.attrs
684            .iter()
685            .flat_map(move |(k, vs)| vs.iter().map(move |v| format!("{k}={v}")))
686    }
687
688    /// Creates a [`pkarr::SignedPacket`]
689    ///
690    /// This constructs a DNS packet and signs it with a [`SecretKey`].
691    pub(crate) fn to_pkarr_signed_packet(
692        &self,
693        secret_key: &SecretKey,
694        ttl: u32,
695    ) -> Result<pkarr::SignedPacket, EncodingError> {
696        use pkarr::dns::{self, rdata};
697        let keypair = pkarr::Keypair::from_secret_key(&secret_key.to_bytes());
698        let name = dns::Name::new(IROH_TXT_NAME).expect("constant");
699
700        let mut builder = pkarr::SignedPacket::builder();
701        for s in self.to_txt_strings() {
702            let mut txt = rdata::TXT::new();
703            txt.add_string(&s)
704                .map_err(|err| e!(EncodingError::InvalidTxtEntry, err))?;
705            builder = builder.txt(name.clone(), txt.into_owned(), ttl);
706        }
707        let signed_packet = builder
708            .build(&keypair)
709            .map_err(|err| e!(EncodingError::FailedBuildingPacket, err))?;
710        Ok(signed_packet)
711    }
712}
713
714#[cfg(not(wasm_browser))]
715pub(crate) fn ensure_iroh_txt_label(name: String) -> String {
716    let mut parts = name.split(".");
717    if parts.next() == Some(IROH_TXT_NAME) {
718        name
719    } else {
720        format!("{IROH_TXT_NAME}.{name}")
721    }
722}
723
724#[cfg(not(wasm_browser))]
725pub(crate) fn endpoint_domain(endpoint_id: &EndpointId, origin: &str) -> String {
726    format!("{}.{}", EndpointId::to_z32(endpoint_id), origin)
727}
728
729#[cfg(test)]
730mod tests {
731    use std::{collections::BTreeSet, str::FromStr, sync::Arc};
732
733    use hickory_resolver::{
734        Name,
735        lookup::Lookup,
736        proto::{
737            op::Query,
738            rr::{
739                RData, Record, RecordType,
740                rdata::{A, TXT},
741            },
742        },
743    };
744    use iroh_base::{EndpointId, SecretKey, TransportAddr};
745    use n0_error::{Result, StdResultExt};
746
747    use super::{EndpointData, EndpointIdExt, EndpointInfo};
748    use crate::dns::TxtRecordData;
749
750    #[test]
751    fn txt_attr_roundtrip() {
752        let endpoint_data = EndpointData::new([
753            TransportAddr::Relay("https://example.com".parse().unwrap()),
754            TransportAddr::Ip("127.0.0.1:1234".parse().unwrap()),
755        ])
756        .with_user_data(Some("foobar".parse().unwrap()));
757        let endpoint_id = "vpnk377obfvzlipnsfbqba7ywkkenc4xlpmovt5tsfujoa75zqia"
758            .parse()
759            .unwrap();
760        let expected = EndpointInfo::from_parts(endpoint_id, endpoint_data);
761        let attrs = expected.to_attrs();
762        let actual = EndpointInfo::from(&attrs);
763        assert_eq!(expected, actual);
764    }
765
766    #[test]
767    fn signed_packet_roundtrip() {
768        let secret_key =
769            SecretKey::from_str("vpnk377obfvzlipnsfbqba7ywkkenc4xlpmovt5tsfujoa75zqia").unwrap();
770        let endpoint_data = EndpointData::new([
771            TransportAddr::Relay("https://example.com".parse().unwrap()),
772            TransportAddr::Ip("127.0.0.1:1234".parse().unwrap()),
773        ])
774        .with_user_data(Some("foobar".parse().unwrap()));
775        let expected = EndpointInfo::from_parts(secret_key.public(), endpoint_data);
776        let packet = expected.to_pkarr_signed_packet(&secret_key, 30).unwrap();
777        let actual = EndpointInfo::from_pkarr_signed_packet(&packet).unwrap();
778        assert_eq!(expected, actual);
779    }
780
781    #[test]
782    fn txt_attr_roundtrip_with_custom_addr() {
783        use iroh_base::CustomAddr;
784
785        // Bluetooth-like address (small id, 6 byte MAC)
786        let bt_addr = CustomAddr::from_parts(1, &[0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6]);
787        // Tor-like address (larger id, 32 byte pubkey)
788        let tor_addr = CustomAddr::from_parts(42, &[0xab; 32]);
789
790        let endpoint_data = EndpointData::new([
791            TransportAddr::Relay("https://example.com".parse().unwrap()),
792            TransportAddr::Ip("127.0.0.1:1234".parse().unwrap()),
793            TransportAddr::Custom(bt_addr),
794            TransportAddr::Custom(tor_addr),
795        ]);
796        let endpoint_id = "vpnk377obfvzlipnsfbqba7ywkkenc4xlpmovt5tsfujoa75zqia"
797            .parse()
798            .unwrap();
799        let expected = EndpointInfo::from_parts(endpoint_id, endpoint_data);
800        let attrs = expected.to_attrs();
801        let actual = EndpointInfo::from(&attrs);
802        assert_eq!(expected, actual);
803    }
804
805    #[test]
806    fn signed_packet_roundtrip_with_custom_addr() {
807        use iroh_base::CustomAddr;
808
809        let secret_key =
810            SecretKey::from_str("vpnk377obfvzlipnsfbqba7ywkkenc4xlpmovt5tsfujoa75zqia").unwrap();
811
812        // Bluetooth-like address (small id, 6 byte MAC)
813        let bt_addr = CustomAddr::from_parts(1, &[0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6]);
814        // Tor-like address (larger id, 32 byte pubkey)
815        let tor_addr = CustomAddr::from_parts(42, &[0xab; 32]);
816
817        let endpoint_data = EndpointData::new([
818            TransportAddr::Relay("https://example.com".parse().unwrap()),
819            TransportAddr::Ip("127.0.0.1:1234".parse().unwrap()),
820            TransportAddr::Custom(bt_addr),
821            TransportAddr::Custom(tor_addr),
822        ])
823        .with_user_data(Some("foobar".parse().unwrap()));
824
825        let expected = EndpointInfo::from_parts(secret_key.public(), endpoint_data);
826        let packet = expected.to_pkarr_signed_packet(&secret_key, 30).unwrap();
827        let actual = EndpointInfo::from_pkarr_signed_packet(&packet).unwrap();
828        assert_eq!(expected, actual);
829    }
830
831    /// There used to be a bug where uploading an EndpointAddr with more than only exactly
832    /// one relay URL or one publicly reachable IP addr would prevent connection
833    /// establishment.
834    ///
835    /// The reason was that only the first address was parsed (e.g. 192.168.96.145 in
836    /// this example), which could be a local, unreachable address.
837    #[test]
838    fn test_from_hickory_lookup() -> Result {
839        let name = Name::from_utf8(
840            "_iroh.dgjpkxyn3zyrk3zfads5duwdgbqpkwbjxfj4yt7rezidr3fijccy.dns.iroh.link.",
841        )
842        .std_context("dns name")?;
843        let query = Query::query(name.clone(), RecordType::TXT);
844        let records = [
845            Record::from_rdata(
846                name.clone(),
847                30,
848                RData::TXT(TXT::new(vec!["addr=192.168.96.145:60165".to_string()])),
849            ),
850            Record::from_rdata(
851                name.clone(),
852                30,
853                RData::TXT(TXT::new(vec!["addr=213.208.157.87:60165".to_string()])),
854            ),
855            // Test a record with mismatching record type (A instead of TXT). It should be filtered out.
856            Record::from_rdata(name.clone(), 30, RData::A(A::new(127, 0, 0, 1))),
857            // Test a record with a mismatching name
858            Record::from_rdata(
859                Name::from_utf8(format!(
860                    "_iroh.{}.dns.iroh.link.",
861                    EndpointId::from_str(
862                        // Another EndpointId
863                        "a55f26132e5e43de834d534332f66a20d480c3e50a13a312a071adea6569981e"
864                    )?
865                    .to_z32()
866                ))
867                .std_context("name")?,
868                30,
869                RData::TXT(TXT::new(vec![
870                    "relay=https://euw1-1.relay.iroh.network./".to_string(),
871                ])),
872            ),
873            // Test a record with a completely different name
874            Record::from_rdata(
875                Name::from_utf8("dns.iroh.link.").std_context("name")?,
876                30,
877                RData::TXT(TXT::new(vec![
878                    "relay=https://euw1-1.relay.iroh.network./".to_string(),
879                ])),
880            ),
881            Record::from_rdata(
882                name.clone(),
883                30,
884                RData::TXT(TXT::new(vec![
885                    "relay=https://euw1-1.relay.iroh.network./".to_string(),
886                ])),
887            ),
888        ];
889        let lookup = Lookup::new_with_max_ttl(query, Arc::new(records));
890        let lookup = hickory_resolver::lookup::TxtLookup::from(lookup);
891        let lookup = lookup
892            .into_iter()
893            .map(|txt| TxtRecordData::from_iter(txt.iter().cloned()));
894
895        let endpoint_info = EndpointInfo::from_txt_lookup(name.to_string(), lookup)?;
896
897        let expected_endpoint_info = EndpointInfo::new(EndpointId::from_str(
898            "1992d53c02cdc04566e5c0edb1ce83305cd550297953a047a445ea3264b54b18",
899        )?)
900        .with_relay_url(Some("https://euw1-1.relay.iroh.network./".parse()?))
901        .with_ip_addrs(BTreeSet::from([
902            "192.168.96.145:60165".parse().unwrap(),
903            "213.208.157.87:60165".parse().unwrap(),
904        ]));
905
906        assert_eq!(endpoint_info, expected_endpoint_info);
907
908        Ok(())
909    }
910}