iroh 0.98.0

p2p quic connections dialed by public key
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
//! An address lookup service which publishes and resolves endpoint information using a [pkarr] relay.
//!
//! Public-Key Addressable Resource Records, [pkarr], is a system which allows publishing
//! [DNS Resource Records] owned by a particular [`SecretKey`] under a name derived from its
//! corresponding [`PublicKey`], also known as the [`EndpointId`].  Additionally this pkarr
//! Resource Record is signed using the same [`SecretKey`], ensuring authenticity of the
//! record.
//!
//! Pkarr normally stores these records on the [Mainline DHT], but also provides two bridges
//! that do not require clients to directly interact with the DHT:
//!
//! - Resolvers are servers which expose the pkarr Resource Record under a domain name,
//!   e.g. `o3dks..6uyy.dns.iroh.link`.  This allows looking up the pkarr Resource Records
//!   using normal DNS clients.  These resolvers would normally perform lookups on the
//!   Mainline DHT augmented with a local cache to improve performance.
//!
//! - Relays are servers which allow both publishing and looking up of the pkarr Resource
//!   Records using HTTP PUT and GET requests.  They will usually perform the publishing to
//!   the Mainline DHT on behalf on the client as well as cache lookups performed on the DHT
//!   to improve performance.
//!
//! [`PkarrPublisher`] filters published addresses: only relay addresses are published by default.
//! To change this behavior, use [`PkarrPublisherBuilder::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.
//!
//! For address lookup in iroh the pkarr Resource Records contain the addressing information,
//! providing endpoints which retrieve the pkarr Resource Record with enough detail
//! to contact the iroh endpoint.
//!
//! There are several Address Lookup's built on top of pkarr, which can be composed
//! to the application's needs:
//!
//! - [`PkarrPublisher`], which publishes to a pkarr relay server using HTTP.
//!
//! - [`PkarrResolver`], which resolves from a pkarr relay server using HTTP.
//!
//! - [`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.
//!
//! [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
//! [`SecretKey`]: crate::SecretKey
//! [`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
//! [`AddrFilter::unfiltered`]: crate::address_lookup::AddrFilter::unfiltered
//! [`PkarrPublisherBuilder::addr_filter`]: PkarrPublisherBuilder::addr_filter

use std::sync::Arc;

use iroh_base::{EndpointId, RelayUrl, SecretKey};
use iroh_dns::pkarr::{SignedPacket, SignedPacketVerifyError};
use iroh_relay::endpoint_info::{AddrFilter, EncodingError, EndpointInfo};
use n0_error::{e, stack_error};
use n0_future::{
    boxed::BoxStream,
    task::{self, AbortOnDropHandle},
    time::{self, Duration, Instant},
};
use n0_watcher::{Disconnected, Watchable, Watcher as _};
use tracing::{Instrument, debug, error_span, trace, warn};
use url::Url;

#[cfg(not(wasm_browser))]
use crate::dns::DnsResolver;
use crate::{
    Endpoint,
    address_lookup::{
        AddressLookup, AddressLookupBuilder, AddressLookupBuilderError, EndpointData,
        Error as AddressLookupError, Item as AddressLookupItem,
    },
    endpoint::force_staging_infra,
    util::reqwest_client_builder,
};

#[cfg(feature = "address-lookup-pkarr-dht")]
pub mod dht;

#[allow(missing_docs)]
#[stack_error(derive, add_meta)]
#[non_exhaustive]
pub enum PkarrError {
    #[error("Invalid public key")]
    PublicKey {
        #[error(std_err)]
        source: iroh_base::KeyParsingError,
    },
    #[error("Packet failed to verify")]
    Verify {
        #[error(std_err)]
        source: SignedPacketVerifyError,
    },
    #[error("Invalid relay URL")]
    InvalidRelayUrl { url: RelayUrl },
    #[error("Error sending http request")]
    HttpSend {
        #[error(std_err)]
        source: reqwest::Error,
    },
    #[error("Error resolving http request")]
    HttpRequest { status: reqwest::StatusCode },
    #[error("Http payload error")]
    HttpPayload {
        #[error(std_err)]
        source: reqwest::Error,
    },
    #[error("EncodingError")]
    Encoding { source: EncodingError },
}

impl From<PkarrError> for AddressLookupError {
    fn from(err: PkarrError) -> Self {
        AddressLookupError::from_err_any("pkarr", err)
    }
}

/// The production pkarr relay run by [number 0].
///
/// This server is both a pkarr relay server as well as a DNS resolver, see the [module
/// documentation].  However it does not interact with the Mainline DHT, so is a more
/// central service.  It is a reliable service to use for address lookup.
///
/// [number 0]: https://n0.computer
/// [module documentation]: crate::address_lookup::pkarr
pub const N0_DNS_PKARR_RELAY_PROD: &str = "https://dns.iroh.link/pkarr";
/// The testing pkarr relay run by [number 0].
///
/// This server operates similarly to [`N0_DNS_PKARR_RELAY_PROD`] but is not as reliable.
/// It is meant for more experimental use and testing purposes.
///
/// [number 0]: https://n0.computer
pub const N0_DNS_PKARR_RELAY_STAGING: &str = "https://staging-dns.iroh.link/pkarr";

/// Default TTL for the records in the pkarr signed packet.
///
/// The Time To Live (TTL) tells DNS caches how long to store a record. It is ignored by the
/// `iroh-dns-server`, e.g. as running on [`N0_DNS_PKARR_RELAY_PROD`], as the home server
/// keeps the records for the domain. When using the pkarr relay no DNS is involved and the
/// setting is ignored.
// TODO(flub): huh?
pub const DEFAULT_PKARR_TTL: u32 = 30;

/// Interval in which to republish the endpoint info even if unchanged: 5 minutes.
pub const DEFAULT_REPUBLISH_INTERVAL: Duration = Duration::from_secs(60 * 5);

/// Builder for [`PkarrPublisher`].
///
/// See [`PkarrPublisher::builder`].
#[derive(Debug)]
pub struct PkarrPublisherBuilder {
    pkarr_relay: Url,
    ttl: u32,
    republish_interval: Duration,
    filter: AddrFilter,
    #[cfg(not(wasm_browser))]
    dns_resolver: Option<DnsResolver>,
}

impl PkarrPublisherBuilder {
    /// See [`PkarrPublisher::builder`].
    fn new(pkarr_relay: Url) -> Self {
        Self {
            pkarr_relay,
            ttl: DEFAULT_PKARR_TTL,
            republish_interval: DEFAULT_REPUBLISH_INTERVAL,
            filter: AddrFilter::relay_only(),
            #[cfg(not(wasm_browser))]
            dns_resolver: None,
        }
    }

    /// See [`PkarrPublisher::n0_dns`].
    fn n0_dns() -> Self {
        let pkarr_relay = match force_staging_infra() {
            true => N0_DNS_PKARR_RELAY_STAGING,
            false => N0_DNS_PKARR_RELAY_PROD,
        };

        let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid");
        Self::new(pkarr_relay)
    }

    /// Sets the TTL (time-to-live) for published packets.
    ///
    /// Default is [`DEFAULT_PKARR_TTL`].
    pub fn ttl(mut self, ttl: u32) -> Self {
        self.ttl = ttl;
        self
    }

    /// Sets the interval after which packets are republished even if our endpoint info did not change.
    ///
    /// Default is [`DEFAULT_REPUBLISH_INTERVAL`].
    pub fn republish_interval(mut self, republish_interval: Duration) -> Self {
        self.republish_interval = republish_interval;
        self
    }

    /// Sets the DNS resolver to use for resolving the pkarr relay URL.
    #[cfg(not(wasm_browser))]
    pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
        self.dns_resolver = Some(dns_resolver);
        self
    }

    /// Sets the address filter to control which addresses are published to the pkarr server.
    ///
    /// By default [`AddrFilter::relay_only`] is used. This avoids leaking IP addresses to the
    /// public pkarr server.
    ///
    /// However, enabling IP address publishing can be useful, e.g. when iroh runs on a machine
    /// connected to the internet via public IP addresses without a firewall.
    /// In such cases, publishing them can make dialing such endpoints via DNS or Pkarr lookup
    /// faster, potentially skipping a relay connection altogether.
    pub fn addr_filter(mut self, filter: AddrFilter) -> Self {
        self.filter = filter;
        self
    }

    /// Builds the [`PkarrPublisher`] with the passed secret key for signing packets.
    ///
    /// This publisher will be able to publish [pkarr](https://pkarr.org) records for [`SecretKey`].
    pub fn build(self, secret_key: SecretKey, tls_config: rustls::ClientConfig) -> PkarrPublisher {
        PkarrPublisher::new(
            secret_key,
            self.pkarr_relay,
            self.ttl,
            self.republish_interval,
            #[cfg(not(wasm_browser))]
            self.dns_resolver,
            tls_config,
            self.filter,
        )
    }
}

impl AddressLookupBuilder for PkarrPublisherBuilder {
    fn into_address_lookup(
        mut self,
        endpoint: &Endpoint,
    ) -> Result<impl AddressLookup, AddressLookupBuilderError> {
        #[cfg(not(wasm_browser))]
        if self.dns_resolver.is_none() {
            self.dns_resolver = Some(endpoint.dns_resolver()?.clone());
        }
        let tls_config = endpoint.tls_config().clone();
        Ok(self.build(endpoint.secret_key().clone(), tls_config))
    }
}

/// Publisher of address lookup information to a [pkarr] relay.
///
/// This publisher uses HTTP to publish address lookup information to a pkarr relay
/// server, see the [module docs] for details.
///
/// This implements the [`AddressLookup`] trait to be used as an address lookup service.  Note
/// that it only publishes address lookup information, for the corresponding resolver use
/// the [`PkarrResolver`] together with [`AddressLookupServices`].
///
/// This publisher will **only** publish the [`RelayUrl`] if it is set, otherwise the *direct addresses* are published instead.
///
/// [pkarr]: https://pkarr.org
/// [module docs]: crate::address_lookup::pkarr
/// [`RelayUrl`]: crate::RelayUrl
/// [`AddressLookupServices`]: super::AddressLookupServices
#[derive(derive_more::Debug, Clone)]
pub struct PkarrPublisher {
    endpoint_id: EndpointId,
    watchable: Watchable<Option<EndpointInfo>>,
    addr_filter: AddrFilter,
    _drop_guard: Arc<AbortOnDropHandle<()>>,
}

impl PkarrPublisher {
    /// Returns a [`PkarrPublisherBuilder`] that publishes endpoint info to a [pkarr] relay at `pkarr_relay`.
    ///
    /// If no further options are set, the pkarr publisher  will use [`DEFAULT_PKARR_TTL`] as the
    /// time-to-live value for the published packets, and it will republish Address Lookup information
    /// every [`DEFAULT_REPUBLISH_INTERVAL`], even if the information is unchanged.
    ///
    /// [`PkarrPublisherBuilder`] implements [`AddressLookupBuilder`], so it can be passed to [`address_lookup`].
    /// It will then use the endpoint's secret key to sign published packets.
    ///
    /// [`address_lookup`]:  crate::endpoint::Builder::address_lookup
    /// [pkarr]: https://pkarr.org
    pub fn builder(pkarr_relay: Url) -> PkarrPublisherBuilder {
        PkarrPublisherBuilder::new(pkarr_relay)
    }

    /// Creates a new [`PkarrPublisher`] with a custom TTL and republish intervals.
    ///
    /// This allows creating the publisher with custom time-to-live values of the
    /// [`SignedPacket`]s as well as a custom republish interval.
    fn new(
        secret_key: SecretKey,
        pkarr_relay: Url,
        ttl: u32,
        republish_interval: Duration,
        #[cfg(not(wasm_browser))] dns_resolver: Option<DnsResolver>,
        tls_config: rustls::ClientConfig,
        addr_filter: AddrFilter,
    ) -> Self {
        debug!("creating pkarr publisher that publishes to {pkarr_relay}");
        let endpoint_id = secret_key.public();

        #[cfg(wasm_browser)]
        let pkarr_client = PkarrRelayClient::new(pkarr_relay, tls_config);

        #[cfg(not(wasm_browser))]
        let pkarr_client = PkarrRelayClient::builder(pkarr_relay, tls_config)
            .set_dns_resolver(dns_resolver)
            .build();

        let watchable = Watchable::default();
        let service = PublisherService {
            ttl,
            watcher: watchable.watch(),
            secret_key,
            pkarr_client,
            republish_interval,
        };
        let join_handle = task::spawn(
            service
                .run()
                .instrument(error_span!("pkarr_publish", me=%endpoint_id.fmt_short())),
        );
        Self {
            watchable,
            endpoint_id,
            addr_filter,
            _drop_guard: Arc::new(AbortOnDropHandle::new(join_handle)),
        }
    }

    /// Creates a pkarr publisher which uses the [number 0] pkarr relay server.
    ///
    /// This uses the pkarr relay server operated by [number 0], at
    /// [`N0_DNS_PKARR_RELAY_PROD`].
    ///
    /// When running with the environment variable
    /// `IROH_FORCE_STAGING_RELAYS` set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]
    /// server is used instead.
    ///
    /// [number 0]: https://n0.computer
    pub fn n0_dns() -> PkarrPublisherBuilder {
        PkarrPublisherBuilder::n0_dns()
    }

    /// Publishes the addressing information about this endpoint to a pkarr relay.
    ///
    /// This is a nonblocking function, the actual update is performed in the background.
    pub fn update_endpoint_data(&self, data: &EndpointData) {
        let data = data.apply_filter(&self.addr_filter).into_owned();
        let info = EndpointInfo::from_parts(self.endpoint_id, data);
        self.watchable.set(Some(info)).ok();
    }
}

impl AddressLookup for PkarrPublisher {
    fn publish(&self, data: &EndpointData) {
        self.update_endpoint_data(data);
    }
}

/// Publish endpoint info to a pkarr relay.
#[derive(derive_more::Debug, Clone)]
struct PublisherService {
    #[debug("SecretKey")]
    secret_key: SecretKey,
    #[debug("PkarrClient")]
    pkarr_client: PkarrRelayClient,
    watcher: n0_watcher::Direct<Option<EndpointInfo>>,
    ttl: u32,
    republish_interval: Duration,
}

impl PublisherService {
    async fn run(mut self) {
        let mut failed_attempts = 0;
        let republish = time::sleep(Duration::MAX);
        tokio::pin!(republish);
        loop {
            if !self.watcher.is_connected() {
                break;
            }
            if let Some(info) = self.watcher.get() {
                match self.publish_current(info).await {
                    Err(err) => {
                        failed_attempts += 1;
                        // Retry after increasing timeout
                        let retry_after = Duration::from_secs(failed_attempts);
                        republish.as_mut().reset(Instant::now() + retry_after);
                        warn!(
                            err = %format!("{err:#}"),
                            url = %self.pkarr_client.pkarr_relay_url ,
                            ?retry_after,
                            %failed_attempts,
                            "Failed to publish to pkarr",
                        );
                    }
                    Ok(()) => {
                        failed_attempts = 0;
                        // Republish after fixed interval
                        republish
                            .as_mut()
                            .reset(Instant::now() + self.republish_interval);
                    }
                }
            }
            // Wait until either the retry/republish timeout is reached, or the endpoint info changed.
            tokio::select! {
                res = self.watcher.updated() => match res {
                    Ok(_) => debug!("Publish endpoint info to pkarr (info changed)"),
                    Err(Disconnected { .. }) => break,
                },
                _ = &mut republish => debug!("Publish endpoint info to pkarr (interval elapsed)"),
            }
        }
    }

    async fn publish_current(&self, info: EndpointInfo) -> Result<(), PkarrError> {
        debug!(
            data = ?info.data,
            pkarr_relay = %self.pkarr_client.pkarr_relay_url,
            "Publishing endpoint info to pkarr"
        );
        let signed_packet = info
            .to_pkarr_signed_packet(&self.secret_key, self.ttl)
            .map_err(|err| e!(PkarrError::Encoding, err))?;
        self.pkarr_client.publish(&signed_packet).await?;
        trace!(
            data = ?info.data,
            pkarr_relay = %self.pkarr_client.pkarr_relay_url,
            "Published endpoint info to pkarr"
        );
        Ok(())
    }
}

/// Builder for [`PkarrResolver`].
///
/// See [`PkarrResolver::builder`].
#[derive(Debug)]
pub struct PkarrResolverBuilder {
    pkarr_relay: Url,
    #[cfg(not(wasm_browser))]
    dns_resolver: Option<DnsResolver>,
}

impl PkarrResolverBuilder {
    /// Sets the DNS resolver to use for resolving the pkarr relay URL.
    #[cfg(not(wasm_browser))]
    pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
        self.dns_resolver = Some(dns_resolver);
        self
    }

    /// Creates a [`PkarrResolver`] from this builder.
    pub fn build(self, tls_config: rustls::ClientConfig) -> PkarrResolver {
        #[cfg(wasm_browser)]
        let pkarr_client = PkarrRelayClient::new(self.pkarr_relay, tls_config);

        #[cfg(not(wasm_browser))]
        let pkarr_client = PkarrRelayClient::builder(self.pkarr_relay, tls_config)
            .set_dns_resolver(self.dns_resolver)
            .build();

        PkarrResolver { pkarr_client }
    }
}

impl AddressLookupBuilder for PkarrResolverBuilder {
    fn into_address_lookup(
        mut self,
        endpoint: &Endpoint,
    ) -> Result<impl AddressLookup, AddressLookupBuilderError> {
        #[cfg(not(wasm_browser))]
        if self.dns_resolver.is_none() {
            self.dns_resolver = Some(endpoint.dns_resolver()?.clone());
        }
        let tls_config = endpoint.tls_config().clone();
        Ok(self.build(tls_config))
    }
}

/// Resolver of address lookup information from a [pkarr] relay.
///
/// The resolver uses HTTP to query address lookup information from a pkarr relay server,
/// see the [module docs] for details.
///
/// This implements the [`AddressLookup`] trait to be used as an address lookup service.  Note
/// that it only resolves address lookup information, for the corresponding publisher use
/// the [`PkarrPublisher`] together with [`AddressLookupServices`].
///
/// [pkarr]: https://pkarr.org
/// [module docs]: crate::address_lookup::pkarr
/// [`AddressLookupServices`]: super::AddressLookupServices
#[derive(derive_more::Debug, Clone)]
pub struct PkarrResolver {
    pkarr_client: PkarrRelayClient,
}

impl PkarrResolver {
    /// Creates a new resolver builder using the pkarr relay server at the URL.
    ///
    /// The builder implements [`AddressLookupBuilder`].
    pub fn builder(pkarr_relay: Url) -> PkarrResolverBuilder {
        PkarrResolverBuilder {
            pkarr_relay,
            #[cfg(not(wasm_browser))]
            dns_resolver: None,
        }
    }

    /// Creates a pkarr resolver builder which uses the [number 0] pkarr relay server.
    ///
    /// This uses the pkarr relay server operated by [number 0] at
    /// [`N0_DNS_PKARR_RELAY_PROD`].
    ///
    /// When running with the environment variable `IROH_FORCE_STAGING_RELAYS`
    /// set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]
    /// server is used instead.
    ///
    /// [number 0]: https://n0.computer
    pub fn n0_dns() -> PkarrResolverBuilder {
        let pkarr_relay = match force_staging_infra() {
            true => N0_DNS_PKARR_RELAY_STAGING,
            false => N0_DNS_PKARR_RELAY_PROD,
        };

        let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid");
        Self::builder(pkarr_relay)
    }
}

impl AddressLookup for PkarrResolver {
    fn resolve(
        &self,
        endpoint_id: EndpointId,
    ) -> Option<BoxStream<Result<AddressLookupItem, AddressLookupError>>> {
        let pkarr_client = self.pkarr_client.clone();
        let fut = async move {
            let signed_packet = pkarr_client.resolve(endpoint_id).await?;
            let info = EndpointInfo::from_pkarr_signed_packet(&signed_packet)
                .map_err(|err| AddressLookupError::from_err_any("pkarr", err))?;
            let item = AddressLookupItem::new(info, "pkarr", None);
            Ok(item)
        };
        let stream = n0_future::stream::once_future(fut);
        Some(Box::pin(stream))
    }
}

/// A [pkarr](https://pkarr.org) client to publish [`SignedPacket`]s to a pkarr relay.
///
/// [pkarr]: https://pkarr.org
#[derive(Debug, Clone)]
pub struct PkarrRelayClient {
    http_client: reqwest::Client,
    pkarr_relay_url: Url,
}

/// A builder for the [`PkarrRelayClient`]
#[derive(Debug, Clone)]
pub struct PkarrRelayClientBuilder {
    pkarr_relay_url: Url,
    #[cfg(not(wasm_browser))]
    dns_relay_resolver: Option<DnsResolver>,
    tls_config: rustls::ClientConfig,
}

impl PkarrRelayClientBuilder {
    fn new(pkarr_relay_url: Url, tls_config: rustls::ClientConfig) -> Self {
        Self {
            pkarr_relay_url,
            #[cfg(not(wasm_browser))]
            dns_relay_resolver: None,
            tls_config,
        }
    }

    /// Passes an optional DNS resolver for the client to use.
    #[cfg(not(wasm_browser))]
    pub fn set_dns_resolver(mut self, dns_resolver: Option<DnsResolver>) -> Self {
        self.dns_relay_resolver = dns_resolver;
        self
    }

    /// Build a [`PkarrRelayClient`].
    pub fn build(self) -> PkarrRelayClient {
        let mut http_client = reqwest_client_builder(Some(self.tls_config));

        #[cfg(not(wasm_browser))]
        if let Some(dns_resolver) = self.dns_relay_resolver {
            http_client = http_client.dns_resolver(Arc::new(dns_resolver));
        };

        let http_client = http_client
            .build()
            .expect("failed to create request client");
        PkarrRelayClient {
            http_client,
            pkarr_relay_url: self.pkarr_relay_url,
        }
    }
}

impl PkarrRelayClient {
    /// Create a new [`PkarrRelayClient`] with default settings.
    ///
    /// Use the [`PkarrRelayClient::builder`] to get a builder that allows for
    /// adding custom settings.
    pub fn new(pkarr_relay_url: Url, tls_config: rustls::ClientConfig) -> Self {
        Self {
            http_client: reqwest_client_builder(Some(tls_config))
                .build()
                .expect("failed to create request client"),
            pkarr_relay_url,
        }
    }

    /// Create a [`PkarrRelayClientBuilder`].
    pub fn builder(
        pkarr_relay_url: Url,
        tls_config: rustls::ClientConfig,
    ) -> PkarrRelayClientBuilder {
        PkarrRelayClientBuilder::new(pkarr_relay_url, tls_config)
    }

    /// Resolves a [`SignedPacket`] for the given [`EndpointId`].
    pub async fn resolve(
        &self,
        endpoint_id: EndpointId,
    ) -> Result<SignedPacket, AddressLookupError> {
        let mut url = self.pkarr_relay_url.clone();
        url.path_segments_mut()
            .map_err(|_| {
                e!(PkarrError::InvalidRelayUrl {
                    url: self.pkarr_relay_url.clone().into()
                })
            })?
            .push(&endpoint_id.to_z32());

        let response = self
            .http_client
            .get(url)
            .send()
            .await
            .map_err(|err| e!(PkarrError::HttpSend, err))?;

        if !response.status().is_success() {
            return Err(e!(PkarrError::HttpRequest {
                status: response.status()
            })
            .into());
        }

        let payload = response
            .bytes()
            .await
            .map_err(|source| e!(PkarrError::HttpPayload { source }))?;
        let packet = SignedPacket::from_relay_payload(&endpoint_id, &payload)
            .map_err(|err| e!(PkarrError::Verify, err))?;
        Ok(packet)
    }

    /// Publishes a [`SignedPacket`].
    pub async fn publish(&self, signed_packet: &SignedPacket) -> Result<(), PkarrError> {
        let mut url = self.pkarr_relay_url.clone();
        url.path_segments_mut()
            .map_err(|_| {
                e!(PkarrError::InvalidRelayUrl {
                    url: self.pkarr_relay_url.clone().into()
                })
            })?
            .push(&signed_packet.public_key().to_z32());

        let response = self
            .http_client
            .put(url)
            .body(signed_packet.to_relay_payload())
            .send()
            .await
            .map_err(|source| e!(PkarrError::HttpSend { source }))?;

        if !response.status().is_success() {
            return Err(e!(PkarrError::HttpRequest {
                status: response.status()
            }));
        }

        Ok(())
    }
}