nostr-sdk 0.45.0

A full-featured SDK for building high-performance and reliable nostr applications.
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
use std::collections::{BTreeSet, HashSet};
use std::future::IntoFuture;
use std::iter;
use std::time::Duration;

use nostr::event::{Event, EventId, Kind};
use nostr::key::PublicKey;
use nostr::types::RelayUrl;
use nostr_gossip::{BestRelaySelection, GossipListKind};

use crate::client::gossip::Gossip;
use crate::client::url::RelayUrlArg;
use crate::client::{Client, Output};
use crate::error::Error;
use crate::future::BoxedFuture;
use crate::relay::{EventSendStatus, RelayCapabilities};

/// Output returned when sending an event.
pub type SendEventOutput = Output<EventId, EventSendStatus, String>;

enum OverwritePolicy<'url> {
    // All WRITE relays
    Broadcast,
    // To specific relays
    To(Vec<RelayUrlArg<'url>>),
    // To NIP-17 relays
    ToNip17,
    // To NIP-65 relays
    ToNip65,
}

// /// Error returned when building an invalid [`AckPolicy`].
// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
// pub enum AckPolicyError {
//     /// `AtLeast` ratio must satisfy `0.0 < ratio <= 1.0`.
//     InvalidAtLeastRatio,
// }
//
// impl std::error::Error for AckPolicyError {}
//
// impl fmt::Display for AckPolicyError {
//     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//         match self {
//             Self::InvalidAtLeastRatio => {
//                 f.write_str("invalid ack policy ratio: expected 0.0 < ratio <= 1.0")
//             }
//         }
//     }
// }

#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum InnerAckPolicy {
    All,
    None,
    // FirstSuccess,
    // // 0.0 < p <= 1.0
    // AtLeast(f64),
}

/// Policy for relay `OK` acknowledgements when sending events.
///
/// This policy controls whether each relay send waits for an `OK` response
/// after dispatching the `EVENT` message.
#[derive(Debug, Clone)]
pub struct AckPolicy(InnerAckPolicy);

impl Default for AckPolicy {
    /// Wait for relay `OK` acknowledgements ([`AckPolicy::all`]).
    #[inline]
    fn default() -> Self {
        Self::all()
    }
}

impl AckPolicy {
    /// Wait for relay `OK` acknowledgement from each selected relay (default).
    #[inline]
    pub const fn all() -> Self {
        Self(InnerAckPolicy::All)
    }

    /// Do not wait for relay `OK` acknowledgements.
    ///
    /// The operation still sends to all selected relays, but each relay result
    /// is reported immediately after dispatch.
    #[inline]
    pub const fn none() -> Self {
        Self(InnerAckPolicy::None)
    }

    // /// Return as soon as the first relay succeeds.
    // #[inline]
    // pub const fn first_success() -> Self {
    //     Self(InnerAckPolicy::FirstSuccess)
    // }
    //
    // /// Return once at least `ratio` of selected relays succeeds.
    // ///
    // /// The ratio is expressed in `(0.0, 1.0]` space (e.g. `0.6` = 60%).
    // ///
    // /// Returns [`AckPolicyError::InvalidAtLeastRatio`] when `ratio` is not
    // /// finite or outside `0.0 < ratio <= 1.0`.
    // #[inline]
    // pub fn at_least(ratio: f64) -> Result<Self, AckPolicyError> {
    //     if !ratio.is_finite() || ratio <= 0.0 || ratio > 1.0 {
    //         return Err(AckPolicyError::InvalidAtLeastRatio);
    //     }
    //
    //     Ok(Self(InnerAckPolicy::AtLeast(ratio)))
    // }

    #[inline]
    pub(crate) fn into_inner(self) -> InnerAckPolicy {
        self.0
    }
}

/// Send event
#[must_use = "Does nothing unless you await!"]
pub struct SendEvent<'client, 'event, 'url> {
    // --------------------------------------------------
    // WHEN ADDING NEW OPTIONS HERE,
    // REMEMBER TO UPDATE THE "Configuration" SECTION in
    // Client::send_event DOC.
    // --------------------------------------------------
    client: &'client Client,
    event: &'event Event,
    policy: Option<OverwritePolicy<'url>>,
    ack_policy: AckPolicy,
    save_into_database: bool,
    wait_for_ok_timeout: Duration,
    wait_for_authentication_timeout: Duration,
}

impl<'client, 'event, 'url> SendEvent<'client, 'event, 'url> {
    pub(crate) fn new(client: &'client Client, event: &'event Event) -> Self {
        Self {
            client,
            event,
            policy: None,
            ack_policy: AckPolicy::default(),
            save_into_database: true,
            wait_for_ok_timeout: Duration::from_secs(10),
            wait_for_authentication_timeout: Duration::from_secs(10),
        }
    }

    /// Send event to all relays with [`RelayCapabilities::WRITE`] capability.
    ///
    /// This overwrites the following methods:
    /// - [`SendEvent::to`]
    /// - [`SendEvent::to_nip17`]
    /// - [`SendEvent::to_nip65`]
    #[inline]
    pub fn broadcast(mut self) -> Self {
        self.policy = Some(OverwritePolicy::Broadcast);
        self
    }

    /// Send event to specific relays
    ///
    /// This overwrites the following methods:
    /// - [`SendEvent::broadcast`]
    /// - [`SendEvent::to_nip17`]
    /// - [`SendEvent::to_nip65`]
    pub fn to<I, T>(mut self, urls: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<RelayUrlArg<'url>>,
    {
        self.policy = Some(OverwritePolicy::To(
            urls.into_iter().map(Into::into).collect(),
        ));
        self
    }

    /// Send event to NIP-17 relays
    ///
    /// This overwrites the following methods:
    /// - [`SendEvent::to`]
    /// - [`SendEvent::broadcast`]
    /// - [`SendEvent::to_nip65`]
    ///
    /// Returns an error if gossip is not configured.
    #[inline]
    pub fn to_nip17(mut self) -> Self {
        self.policy = Some(OverwritePolicy::ToNip17);
        self
    }

    /// Send event to NIP-65 relays
    ///
    /// This overwrites the following methods:
    /// - [`SendEvent::to`]
    /// - [`SendEvent::broadcast`]
    /// - [`SendEvent::to_nip17`]
    ///
    /// Returns an error if gossip is not configured.
    #[inline]
    pub fn to_nip65(mut self) -> Self {
        self.policy = Some(OverwritePolicy::ToNip65);
        self
    }

    /// Save the event into the database (default: true)
    ///
    /// If `true`, the event is immediately saved into the database.
    #[inline]
    pub fn save_into_database(mut self, enabled: bool) -> Self {
        self.save_into_database = enabled;
        self
    }

    /// Set how relay `OK` acknowledgements are handled.
    ///
    /// Default is [`AckPolicy::all`].
    #[inline]
    pub fn ack_policy(mut self, policy: AckPolicy) -> Self {
        self.ack_policy = policy;
        self
    }

    /// Timeout for waiting for relay `OK` (default: 10 sec).
    ///
    /// Used only when waiting for relay `OK` is enabled.
    #[inline]
    pub fn ok_timeout(mut self, timeout: Duration) -> Self {
        self.wait_for_ok_timeout = timeout;
        self
    }

    /// Timeout for waiting for relay authentication (default: 10 sec).
    ///
    /// Used only when waiting for relay `OK` is enabled.
    #[inline]
    pub fn authentication_timeout(mut self, timeout: Duration) -> Self {
        self.wait_for_authentication_timeout = timeout;
        self
    }
}

async fn gossip_prepare_urls(
    client: &Client,
    gossip: &Gossip,
    event: &Event,
    is_nip17: bool,
) -> Result<HashSet<RelayUrl>, Error> {
    let is_contact_list: bool = event.kind == Kind::ContactList;
    let is_gift_wrap: bool = event.kind == Kind::GiftWrap;

    // Get involved public keys and check what are up to date in the gossip graph and which ones require an update.
    let (public_keys, gossip_kinds): (BTreeSet<PublicKey>, &[GossipListKind]) = if is_gift_wrap {
        let kind: GossipListKind = if is_nip17 {
            GossipListKind::Nip17
        } else {
            GossipListKind::Nip65
        };

        // Get only p tags since the author of a gift wrap is randomized
        let public_keys: BTreeSet<PublicKey> = event.tags.public_keys().collect();

        (public_keys, &[kind])
    } else if is_contact_list {
        // Contact list, update only author
        (BTreeSet::from([event.pubkey]), &[GossipListKind::Nip65])
    } else {
        // Get all public keys involved in the event: author + p tags
        let public_keys: BTreeSet<PublicKey> = event
            .tags
            .public_keys()
            .chain(iter::once(event.pubkey))
            .collect();
        (public_keys, &[GossipListKind::Nip65])
    };

    // Ensure public keys are up to date
    client
        .ensure_gossip_public_keys_fresh(gossip, public_keys, gossip_kinds)
        .await?;

    // Check if NIP17 or NIP65
    if is_nip17 && is_gift_wrap {
        // Get NIP17 relays
        // Get only for relays for p tags since gift wraps are signed with random key (random author)
        let relays = gossip
            .resolver()
            .get_relays(
                event.tags.public_keys(),
                BestRelaySelection::PrivateMessage {
                    limit: client.config().gossip_config.limits.nip17_relays,
                },
                client.config().gossip_config.allowed,
            )
            .await?;

        // Clients SHOULD publish kind 14 events to the 10050-listed relays.
        // If that is not found, that indicates the user is not ready to receive messages under this NIP and clients shouldn't try.
        //
        // <https://github.com/nostr-protocol/nips/blob/6e7a618e7f873bb91e743caacc3b09edab7796a0/17.md>
        if relays.is_empty() {
            return Err(Error::not_found(
                "Private message relays not found. The user is not ready to receive private messages.",
            ));
        }

        // Add outbox and inbox relays
        for url in relays.iter().cloned() {
            client
                .add_relay(url)
                .capabilities(RelayCapabilities::GOSSIP)
                .and_connect()
                .await?;
        }

        Ok(relays)
    } else {
        // Get OUTBOX, HINTS and MOST_RECEIVED relays for the author
        let mut relays: HashSet<RelayUrl> = gossip
            .store()
            .get_best_relays(
                &event.pubkey,
                BestRelaySelection::All {
                    read: 0, // No read relays
                    write: client.config().gossip_config.limits.write_relays_per_user,
                    hints: client.config().gossip_config.limits.hint_relays_per_user,
                    most_received: client
                        .config()
                        .gossip_config
                        .limits
                        .most_used_relays_per_user,
                },
                client.config().gossip_config.allowed,
            )
            .await?;

        // Extend with INBOX, HINTS and MOST_RECEIVED relays for the tags
        if !is_contact_list {
            let inbox_hints_most_recv: HashSet<RelayUrl> = gossip
                .resolver()
                .get_relays(
                    event.tags.public_keys(),
                    BestRelaySelection::All {
                        read: client.config().gossip_config.limits.read_relays_per_user,
                        write: 0, // No write relays
                        hints: client.config().gossip_config.limits.hint_relays_per_user,
                        most_received: client
                            .config()
                            .gossip_config
                            .limits
                            .most_used_relays_per_user,
                    },
                    client.config().gossip_config.allowed,
                )
                .await?;

            relays.extend(inbox_hints_most_recv);
        }

        // Add OUTBOX and INBOX relays
        for url in relays.iter().cloned() {
            client
                .add_relay(url)
                .capabilities(RelayCapabilities::GOSSIP)
                .and_connect()
                .await?;
        }

        // Get WRITE relays
        let write_relays: HashSet<RelayUrl> = client.pool().write_relay_urls().await;

        // Extend relays with WRITE ones
        relays.extend(write_relays);

        // Return all relays
        Ok(relays)
    }
}

impl<'client, 'event, 'url> IntoFuture for SendEvent<'client, 'event, 'url>
where
    'event: 'client,
    'url: 'client,
{
    type Output = Result<SendEventOutput, Error>;
    type IntoFuture = BoxedFuture<'client, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            // Caller-supplied events may be externally signed; validate before local side effects.
            self.event.verify()?;

            // Save event into database
            if self.save_into_database {
                self.client.database().save_event(self.event).await?;
            }

            // Process event for gossip, independently of the policy
            if let Some(gossip) = self.client.gossip() {
                gossip.store().process(self.event, None).await?;
            }

            let urls: HashSet<RelayUrl> = match (self.policy, self.client.gossip()) {
                // No overwrite policy or send to NIP-65 and gossip available: send to NIP-65 relays
                (None | Some(OverwritePolicy::ToNip65), Some(gossip)) => {
                    gossip_prepare_urls(self.client, gossip, self.event, false).await?
                }
                // Send to NIP-17 and gossip available: send to NIP-17 relays
                (Some(OverwritePolicy::ToNip17), Some(gossip)) => {
                    gossip_prepare_urls(self.client, gossip, self.event, true).await?
                }
                // Send to gossip, but gossip is not available: error
                (Some(OverwritePolicy::ToNip17 | OverwritePolicy::ToNip65), None) => {
                    return Err(Error::gossip_not_configured());
                }
                // Send to specific relays
                (Some(OverwritePolicy::To(list)), _) => {
                    let mut urls: HashSet<RelayUrl> = HashSet::with_capacity(list.len());

                    for url in list {
                        urls.insert(url.try_into_relay_url()?.into_owned());
                    }

                    urls
                }
                // - Broadcast policy,
                // - Or, no overwrite policy and no gossip available
                // -> Send to all WRITE relays
                (Some(OverwritePolicy::Broadcast), _) | (None, None) => {
                    self.client.pool().write_relay_urls().await
                }
            };

            self.client
                .pool()
                .send_event(
                    urls,
                    self.event,
                    self.ack_policy.into_inner(),
                    self.wait_for_ok_timeout,
                    self.wait_for_authentication_timeout,
                )
                .await
        })
    }
}

#[cfg(test)]
mod tests {
    use nostr::nips::nip17::InboxRelayList;
    use nostr::nips::nip65::RelayList;
    use nostr::prelude::*;
    use nostr_database::DatabaseEventStatus;
    use nostr_gossip::GossipAllowedRelays;
    use nostr_gossip_memory::store::NostrGossipMemory;

    use super::*;
    use crate::client::{GossipConfig, GossipRelayLimits};
    use crate::error::ErrorKind;
    use crate::local_relay::*;

    #[tokio::test]
    async fn unverified_event_is_rejected_before_sending() {
        let client = Client::default();
        let keys = Keys::generate();
        let mut event = EventBuilder::new(Kind::TextNote, "original")
            .finalize(&keys)
            .unwrap();
        event.content = String::from("forged");

        let err = client.send_event(&event).await.unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Protocol);
        assert_eq!(
            client.database().check_id(&event.id).await.unwrap(),
            DatabaseEventStatus::NotExistent
        );
    }

    #[tokio::test]
    async fn test_send_event() {
        let mock1 = MockRelay::run().await.unwrap();
        let url1 = mock1.url().await;
        let mock2 = MockRelay::run().await.unwrap();
        let url2 = mock2.url().await;
        let mock3 = MockRelay::run().await.unwrap();
        let url3 = mock3.url().await;

        let client: Client = Client::default();

        // Add 2 READ and WRITE relays
        client.add_relay(&url1).await.unwrap();
        client.add_relay(&url2).await.unwrap();

        // Add a READ-only relay
        client
            .add_relay(&url3)
            .capabilities(RelayCapabilities::READ)
            .await
            .unwrap();

        client.connect().await;

        let keys = Keys::generate();
        let event = EventBuilder::new(Kind::TextNote, "Broadcast test")
            .finalize(&keys)
            .unwrap();

        // Send event (broadcast to all WRITE relays by default)
        let output = client.send_event(&event).await.unwrap();

        assert_eq!(output.success.len(), 2);
        assert!(output.success.contains_key(&url1));
        assert!(output.success.contains_key(&url2));
        assert!(!output.success.contains_key(&url3));
        assert!(output.failed.is_empty());
        assert_eq!(output.value, event.id);
    }

    #[tokio::test]
    async fn test_send_event_to() {
        let mock1 = MockRelay::run().await.unwrap();
        let url1 = mock1.url().await;
        let mock2 = MockRelay::run().await.unwrap();
        let url2 = mock2.url().await;

        let client = Client::default();
        client.add_relay(&url1).await.unwrap();
        client.add_relay(&url2).await.unwrap();
        client.connect().await;

        let keys = Keys::generate();
        let event = EventBuilder::new(Kind::TextNote, "Targeted test")
            .finalize(&keys)
            .unwrap();

        // Send only to relay 1
        let output = client.send_event(&event).to([&url1]).await.unwrap();

        assert_eq!(output.success.len(), 1);
        assert!(output.success.contains_key(&url1));
        assert!(!output.success.contains_key(&url2));
        assert!(output.failed.is_empty());
        assert_eq!(output.value, event.id);
    }

    #[tokio::test]
    async fn test_send_event_broadcast() {
        let mock1 = MockRelay::run().await.unwrap();
        let url1 = mock1.url().await;
        let mock2 = MockRelay::run().await.unwrap();
        let url2 = mock2.url().await;
        let mock3 = MockRelay::run().await.unwrap();
        let url3 = mock3.url().await;

        // Configure client with gossip
        let gossip: NostrGossipMemory = NostrGossipMemory::unbounded();
        let client: Client = Client::builder().gossip(gossip).build();

        // Add 2 READ and WRITE relays
        client.add_relay(&url1).await.unwrap();
        client.add_relay(&url2).await.unwrap();

        // Add a READ-only relay
        client
            .add_relay(&url3)
            .capabilities(RelayCapabilities::READ)
            .await
            .unwrap();

        client.connect().await;

        let keys = Keys::generate();
        let event = EventBuilder::new(Kind::TextNote, "Force to all test")
            .finalize(&keys)
            .unwrap();

        // Force send to all WRITE instead of using gossip
        let output = client.send_event(&event).broadcast().await.unwrap();

        assert_eq!(output.success.len(), 2);
        assert!(output.success.contains_key(&url1));
        assert!(output.success.contains_key(&url2));
        assert!(!output.success.contains_key(&url3));
        assert!(output.failed.is_empty());
        assert_eq!(output.value, event.id);
    }

    #[tokio::test]
    async fn test_send_event_with_auto_gossip() {
        // Setup Outbox Relay (where the user wants to receive/send events)
        let outbox_mock = MockRelay::run().await.unwrap();
        let outbox_url = outbox_mock.url().await;

        // Setup Discovery Relay (where NIP-65 lists are stored)
        let discovery_mock = MockRelay::run().await.unwrap();
        let discovery_url = discovery_mock.url().await;

        // Setup a generic "Public" Relay
        let public_mock = MockRelay::run().await.unwrap();
        let public_url = public_mock.url().await;

        // Setup User A keys and their Relay List (NIP-65) pointing to the Outbox Relay
        let keys_a = Keys::generate();
        let relay_list = RelayList::new([(outbox_url.clone(), None)])
            .finalize(&keys_a)
            .unwrap();
        let res = discovery_mock.add_event(relay_list).await.unwrap();
        assert!(res.is_success());

        // Configure Client with Gossip
        let gossip = NostrGossipMemory::unbounded();
        let config = GossipConfig::default()
            .limits(GossipRelayLimits {
                read_relays_per_user: 2,
                write_relays_per_user: 2,
                hint_relays_per_user: 1,
                most_used_relays_per_user: 0, // Disable the most used, as it would be the discovery one
                nip17_relays: 3,
            })
            .allowed(GossipAllowedRelays {
                onion: true,
                local: true,
                without_tls: true,
            });
        let client = Client::builder()
            .gossip(gossip)
            .gossip_config(config)
            .build();

        // The client only knows about the Discovery and Public relays initially
        client
            .add_relay(&discovery_url)
            .capabilities(RelayCapabilities::DISCOVERY)
            .await
            .unwrap();
        client.add_relay(&public_url).await.unwrap();
        client.connect().await;

        // Verify that the client doesn't have the outbox relay
        assert!(client.relay(&outbox_url).await.unwrap().is_none());

        // Verify capabilities
        let relay = client.relay(&discovery_url).await.unwrap().unwrap();
        assert_eq!(relay.capabilities().load(), RelayCapabilities::DISCOVERY);

        // Now, send a Text Note from User A.
        // The gossip engine should:
        // - See the author is User A
        // - Fetch User A's relay list from Discovery/Public relays (or local cache)
        // - Identify 'outbox_url' as the target
        // - Automatically connect to 'outbox_url'
        // - Send the event to the outbox and public relay
        let event = EventBuilder::new(Kind::TextNote, "Gossip test")
            .finalize(&keys_a)
            .unwrap();

        // Send event using default config (must be sent to gossip)
        let output = client.send_event(&event).await.unwrap();

        // Verify output
        assert_eq!(output.success.len(), 2);
        assert!(output.success.contains_key(&outbox_url));
        assert!(output.success.contains_key(&public_url));
        assert!(!output.success.contains_key(&discovery_url));
        assert!(output.failed.is_empty());
        assert_eq!(output.value, event.id);

        // Verify the client now has the outbox relay in its pool with GOSSIP capability
        let outbox_relay = client.relay(&outbox_url).await.unwrap().unwrap();
        assert_eq!(
            outbox_relay.capabilities().load(),
            RelayCapabilities::GOSSIP
        );
    }

    #[tokio::test]
    async fn test_send_event_to_nip65_without_gossip() {
        let mock = MockRelay::run().await.unwrap();
        let url = mock.url().await;

        let client: Client = Client::default();
        client.add_relay(&url).await.unwrap();
        client.connect().await;

        let keys = Keys::generate();
        let event = EventBuilder::new(Kind::TextNote, "Broadcast test")
            .finalize(&keys)
            .unwrap();

        // Send event
        let err = client.send_event(&event).to_nip65().await.unwrap_err();
        assert_eq!(err.kind(), ErrorKind::State);
        assert_eq!(err.to_string(), "gossip not configured");
    }

    #[tokio::test]
    async fn test_send_event_to_nip17() {
        let inbox_mock = MockRelay::run().await.unwrap();
        let inbox_url = inbox_mock.url().await;

        // Setup Discovery Relay (where NIP-17 lists are stored)
        let discovery_mock = MockRelay::run().await.unwrap();
        let discovery_url = discovery_mock.url().await;

        // Setup a generic "Public" Relay
        let public_mock = MockRelay::run().await.unwrap();
        let public_url = public_mock.url().await;

        // Setup Bob keys and NIP-17 list pointing to the Inbox Relay
        let bob_keys = Keys::generate();
        let relay_list = InboxRelayList::new([inbox_url.clone()])
            .finalize(&bob_keys)
            .unwrap();
        let res = discovery_mock.add_event(relay_list).await.unwrap();
        assert!(res.is_success());

        // Configure Client with Gossip
        let gossip = NostrGossipMemory::unbounded();
        let config = GossipConfig::default().allowed(GossipAllowedRelays {
            onion: true,
            local: true,
            without_tls: true,
        });
        let client = Client::builder()
            .gossip(gossip)
            .gossip_config(config)
            .build();

        // The client only knows about the Discovery and Public relays initially
        client
            .add_relay(&discovery_url)
            .capabilities(RelayCapabilities::DISCOVERY)
            .await
            .unwrap();
        client.add_relay(&public_url).await.unwrap();
        client.connect().await;

        // Verify that the client doesn't have the inbox relay
        assert!(client.relay(&inbox_url).await.unwrap().is_none());

        // Sends an event to the inbox relay
        // NOTE: this is not a NIP-17 event, as the nip59 feature is required, so we are sending a fake gift wrap tagging the recipient
        let event = EventBuilder::new(Kind::GiftWrap, "payload")
            .tag(Tag::public_key(bob_keys.public_key()))
            .finalize(&Keys::generate())
            .unwrap();
        let output = client.send_event(&event).to_nip17().await.unwrap();

        // Should be sent ONLY to Bob's discovered inbox
        assert_eq!(output.success.len(), 1);
        assert!(output.success.contains_key(&inbox_url));
        assert!(!output.success.contains_key(&public_url));
        assert!(!output.success.contains_key(&discovery_url));
        assert!(output.failed.is_empty());
        assert_eq!(output.value, event.id);

        // Verify the client now has the outbox relay in its pool with GOSSIP capability
        let inbox_relay = client.relay(&inbox_url).await.unwrap().unwrap();
        assert_eq!(inbox_relay.capabilities().load(), RelayCapabilities::GOSSIP);
    }

    #[tokio::test]
    async fn test_send_event_to_nip17_without_gossip() {
        let mock = MockRelay::run().await.unwrap();
        let url = mock.url().await;

        let client: Client = Client::default();
        client.add_relay(&url).await.unwrap();
        client.connect().await;

        // NOTE: this is not a NIP-17 event, as the nip59 feature is required, so we are sending a fake gift wrap tagging the recipient
        let bob_keys = Keys::generate();
        let event = EventBuilder::new(Kind::GiftWrap, "payload")
            .tag(Tag::public_key(bob_keys.public_key()))
            .finalize(&Keys::generate())
            .unwrap();

        // Send event
        let err = client.send_event(&event).to_nip17().await.unwrap_err();
        assert_eq!(err.kind(), ErrorKind::State);
        assert_eq!(err.to_string(), "gossip not configured");
    }
}