nwc 0.45.0-alpha.7

Nostr Wallet Connect client
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
// Copyright (c) 2022-2023 Yuki Kishimoto
// Copyright (c) 2023-2025 Rust Nostr Developers
// Distributed under the MIT software license

//! NWC client and zapper backend for Nostr apps

#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![warn(clippy::large_futures)]
#![warn(rustdoc::bare_urls)]
#![allow(clippy::arc_with_non_send_sync)]

use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::Duration;

use futures_core::Stream;
use nostr::nips::nip47::{Notification, Request, Response};
use nostr_sdk::prelude::*;

mod api;
pub mod builder;
pub mod error;
mod future;
pub mod prelude;

pub use self::api::*;
use self::builder::NostrWalletConnectBuilder;
use self::error::Error;

const NOTIFICATIONS_ID: &str = "nwc-notifications";

#[allow(missing_docs)]
#[deprecated(since = "0.45.0", note = "Use NostrWalletConnect instead")]
pub type NWC = NostrWalletConnect;

#[derive(Debug)]
struct AtomicCipher(AtomicU32);

impl From<Option<Nip47Ciphers>> for AtomicCipher {
    fn from(value: Option<Nip47Ciphers>) -> Self {
        match value {
            Some(cipher) => Self::new(cipher),
            None => Self(AtomicU32::from(0)),
        }
    }
}

impl AtomicCipher {
    /// Create an atomic reference to the given cipher for lock-free shared access.
    #[inline]
    fn new(cipher: Nip47Ciphers) -> Self {
        Self(AtomicU32::from(cipher.as_u32()))
    }

    /// If any cipher is set, returns it; otherwise returns None.
    #[inline]
    fn load(&self) -> Option<Nip47Ciphers> {
        match self.0.load(Ordering::SeqCst) {
            0 => None,
            cipher => Nip47Ciphers::from_u32(cipher),
        }
    }
}

/// Nostr Wallet Connect client
#[derive(Debug, Clone)]
pub struct NostrWalletConnect {
    uri: NostrWalletConnectUri,
    client: Client,
    timeout: Duration,
    cipher: Arc<AtomicCipher>,
    relay_opts: RelayOptions,
    bootstrapped: Arc<AtomicBool>,
    notifications_subscribed: Arc<AtomicBool>,
}

impl NostrWalletConnect {
    /// Construct a new client.
    ///
    /// Use [`NostrWalletConnect::builder`] for customizing the client.
    #[inline]
    pub fn new(uri: NostrWalletConnectUri) -> Self {
        Self::builder(uri).build()
    }

    /// Construct a new Nostr Wallet Connect client builder.
    ///
    /// # Example
    ///
    /// ```
    /// # use std::time::Duration;
    /// use nwc::prelude::*;
    ///
    /// # let uri = NostrWalletConnectUri::parse("nostr+walletconnect://b889ff5b1513b641e2a139f661a661364979c5beee91842f8f0ef42ab558e9d4?secret=71a8c14c1407c113601079c4302dab36460f0ccd0ad506f1f2dc73b5100e4f3c&relay=wss%3A%2F%2Frelay.damus.io").unwrap();
    /// let nwc = NostrWalletConnect::builder(uri).timeout(Duration::from_secs(30)).build();
    /// # let _ = nwc;
    /// ```
    #[inline]
    pub fn builder(uri: NostrWalletConnectUri) -> NostrWalletConnectBuilder {
        NostrWalletConnectBuilder::new(uri)
    }

    fn from_builder(builder: NostrWalletConnectBuilder) -> Self {
        let client: Client = match builder.monitor {
            Some(monitor) => Client::builder().monitor(monitor).build(),
            None => Client::default(),
        };

        Self {
            uri: builder.uri,
            client,
            timeout: builder.timeout,
            relay_opts: builder.relay,
            cipher: Arc::new(AtomicCipher::from(builder.cipher)),
            bootstrapped: Arc::new(AtomicBool::new(false)),
            notifications_subscribed: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Get URI
    #[inline]
    pub fn uri(&self) -> &NostrWalletConnectUri {
        &self.uri
    }

    /// Get the inner nostr client
    #[inline]
    pub fn client(&self) -> &Client {
        &self.client
    }

    /// Get relays status
    #[deprecated(since = "0.45.0", note = "Use the client method instead")]
    pub async fn status(&self) -> HashMap<RelayUrl, RelayStatus> {
        let relays = self.client.relays().await;
        relays.into_iter().map(|(u, r)| (u, r.status())).collect()
    }

    /// Return the NIP-47 cipher to use, caching it if not already known
    ///
    /// Falls back to NIP-04 when the remote wallet does not advertise any
    /// cipher.
    async fn get_cipher(&self) -> Nip47Ciphers {
        let cipher = self.cipher.load();

        match cipher {
            Some(cipher) => cipher,
            None => {
                let cipher = self
                    .get_wallet_cipher()
                    .await
                    .unwrap_or(Nip47Ciphers::NIP04);
                _ = self.cipher.0.compare_exchange(
                    0,
                    cipher.as_u32(),
                    Ordering::SeqCst,
                    Ordering::SeqCst,
                );
                cipher
            }
        }
    }

    /// Connect and subscribe
    async fn bootstrap(&self) -> Result<(), Error> {
        // Check if already bootstrapped
        if self.bootstrapped.load(Ordering::SeqCst) {
            return Ok(());
        }

        // Add relays
        for url in self.uri.relays.iter() {
            self.client
                .add_relay(url)
                .opts(self.relay_opts.clone())
                .await?;
        }

        // Connect to relays
        self.client.connect().await;

        // Mark as bootstrapped
        self.bootstrapped.store(true, Ordering::SeqCst);

        Ok(())
    }

    /// Fetch the latest cipher advertised by the wallet, if any.
    async fn get_wallet_cipher(&self) -> Option<Nip47Ciphers> {
        let filter = Filter::new()
            .kind(Kind::WalletConnectInfo)
            .author(self.uri.public_key);

        let info_event = self.client.fetch_events(filter).await.ok()?.first_owned()?;

        info_event
            .tags
            .iter()
            .find_map(|t| match Nip47Tag::parse(t.as_slice()).ok()? {
                Nip47Tag::Encryption(et) => Some(et.latest()),
            })
    }

    async fn send_request(&self, req: Request, timeout: Duration) -> Result<Response, Error> {
        // Bootstrap
        self.bootstrap().await?;
        let cipher = self.get_cipher().await;

        tracing::debug!(
            "Sending request '{}' encrypted using '{cipher}'",
            req.as_json()
        );

        // Convert request to event
        let event: Event = req.to_event(&self.uri, cipher)?;

        // Construct the filter to wait for the response
        let filter = Filter::new()
            .author(self.uri.public_key)
            .kind(Kind::WalletConnectResponse)
            .event(event.id);

        // Subscribe to filter and create the stream
        let mut stream = self
            .client
            .stream_events(filter)
            .timeout(timeout)
            .policy(ReqExitPolicy::WaitForEvents(1))
            .await?;

        // Send the request
        self.client.send_event(&event).await?;

        // Wait for the response
        let (_, res) = stream.next().await.ok_or_else(Error::no_response)?;

        // Unwrap event
        let received_event: Event = res?;

        // Parse response
        let response: Response = Response::from_event(&self.uri, &received_event, cipher)?;

        // Return response
        Ok(response)
    }

    /// Pay invoice
    #[inline]
    pub fn pay_invoice(&self, request: PayInvoiceRequest) -> PayInvoice<'_> {
        PayInvoice::new(self, request)
    }

    /// Pay keysend
    #[inline]
    pub fn pay_keysend(&self, request: PayKeysendRequest) -> PayKeysend<'_> {
        PayKeysend::new(self, request)
    }

    /// Create invoice
    #[inline]
    pub fn make_invoice(&self, request: MakeInvoiceRequest) -> MakeInvoice<'_> {
        MakeInvoice::new(self, request)
    }

    /// Lookup invoice
    #[inline]
    pub fn lookup_invoice(&self, request: LookupInvoiceRequest) -> LookupInvoice<'_> {
        LookupInvoice::new(self, request)
    }

    /// List transactions
    #[inline]
    pub fn list_transactions(&self, params: ListTransactionsRequest) -> ListTransactions<'_> {
        ListTransactions::new(self, params)
    }

    /// Get balance (msat)
    #[inline]
    pub fn get_balance(&self) -> GetBalance<'_> {
        GetBalance::new(self)
    }

    /// Get info
    #[inline]
    pub fn get_info(&self) -> GetInfo<'_> {
        GetInfo::new(self)
    }

    /// Subscribe to wallet notifications
    pub async fn subscribe_to_notifications(&self) -> Result<(), Error> {
        if self.notifications_subscribed.load(Ordering::SeqCst) {
            tracing::debug!("Already subscribed to notifications");
            return Ok(());
        }

        tracing::info!("Subscribing to wallet notifications...");

        self.bootstrap().await?;

        let client_keys = Keys::new(self.uri.secret.clone());
        let client_pubkey = client_keys.public_key();

        tracing::debug!("Client pubkey: {}", client_pubkey);
        tracing::debug!("Wallet service pubkey: {}", self.uri.public_key);

        let notification_filter = Filter::new()
            .author(self.uri.public_key)
            .pubkey(client_pubkey)
            .kinds([
                Kind::WalletConnectNotification,
                Kind::WalletConnectNotificationNip44V2,
            ])
            .since(Timestamp::now());

        tracing::debug!("Notification filter: {:?}", notification_filter);

        self.client
            .subscribe(notification_filter)
            .with_id(SubscriptionId::new(NOTIFICATIONS_ID))
            .await?;

        self.notifications_subscribed.store(true, Ordering::SeqCst);

        tracing::info!("Successfully subscribed to notifications");
        Ok(())
    }

    /// Unsubscribe from notifications
    pub async fn unsubscribe_from_notifications(&self) -> Result<(), Error> {
        self.client
            .unsubscribe(&SubscriptionId::new(NOTIFICATIONS_ID))
            .await?;
        self.notifications_subscribed.store(false, Ordering::SeqCst);
        Ok(())
    }

    /// Get a new notification stream
    ///
    /// The stream terminates when the client shutdowns.
    pub fn notifications(
        &self,
    ) -> Pin<Box<dyn Stream<Item = Result<Notification, Error>> + Send + '_>> {
        let notifications = self.client.notifications();

        Box::pin(notifications.filter_map(move |notification| async move {
            tracing::trace!("Received a client notification: {:?}", notification);

            if let ClientNotification::Event {
                subscription_id,
                event,
                ..
            } = notification
            {
                tracing::debug!(
                    "Received event: kind={}, author={}, id={}",
                    event.kind,
                    event.pubkey,
                    event.id
                );

                if subscription_id.as_str() != NOTIFICATIONS_ID {
                    tracing::trace!("Ignoring event with subscription id: {}", subscription_id);
                    return None;
                }

                if event.kind != Kind::WalletConnectNotification
                    || event.kind != Kind::WalletConnectNotificationNip44V2
                {
                    tracing::trace!("Ignoring event with kind: {}", event.kind);
                    return None;
                }

                tracing::info!("Processing wallet notification event");

                match Notification::from_event(&self.uri, &event) {
                    Ok(nip47_notification) => {
                        tracing::info!(
                            "Successfully parsed notification: {:?}",
                            nip47_notification.notification_type
                        );
                        return Some(Ok(nip47_notification));
                    }
                    Err(e) => {
                        tracing::error!("Failed to parse notification: {}", e);
                        tracing::debug!("Event content: {}", event.content);
                        return Some(Err(Error::from(e)));
                    }
                }
            }

            None
        }))
    }

    /// Manually reconnect to a specific relay
    ///
    /// This function can be used to force a reconnection to a relay when the automatic reconnection
    /// is disabled via [`RelayOptions::reconnect`].
    ///
    /// If the client is not bootstrapped, it will do nothing.
    #[deprecated(since = "0.45.0", note = "Use the client method instead")]
    pub async fn reconnect_relay<'a, U>(&self, url: U) -> Result<(), Error>
    where
        U: Into<RelayUrlArg<'a>>,
    {
        if !self.bootstrapped.load(Ordering::SeqCst) {
            return Ok(());
        }

        Ok(self.client.connect_relay(url).await?)
    }

    /// Completely shutdown
    #[inline]
    pub async fn shutdown(&self) {
        self.client.shutdown().await
    }
}

#[cfg(test)]
mod tests {
    use nostr_sdk::local_relay::MockRelay;

    use super::*;

    const RESPONSE: Response = Response {
        result_type: Method::GetBalance,
        error: None,
        result: Some(nip47::ResponseResult::GetBalance(GetBalanceResponse {
            balance: 0xDEADBEEF,
        })),
    };

    fn create_keys(relay_url: RelayUrl) -> (Keys, Keys, NostrWalletConnectUri) {
        let wallet_keys = Keys::generate();
        let client_keys = Keys::generate();
        let uri = NostrWalletConnectUri::new(
            wallet_keys.public_key(),
            vec![relay_url],
            client_keys.secret_key().clone(),
            None,
        );
        (wallet_keys, client_keys, uri)
    }

    async fn run_wallet(
        wkeys: Keys,
        ckeys: Keys,
        relay_url: RelayUrl,
        advertise_ciphers: Option<Nip47Ciphers>,
        expected_cipher: Nip47Ciphers,
    ) {
        let client = Client::new();
        client.add_relay(relay_url).and_connect().await.unwrap();

        if let Some(ciphers) = advertise_ciphers {
            let event = EventBuilder::new(Kind::WalletConnectInfo, "")
                .tag(Nip47Tag::Encryption(ciphers).to_tag())
                .finalize(&wkeys)
                .unwrap();
            client.send_event(&event).await.unwrap();
        }

        let request = client
            .fetch_events(
                Filter::new()
                    .kind(Kind::WalletConnectRequest)
                    .author(ckeys.public_key())
                    .pubkey(wkeys.public_key()),
            )
            .policy(ReqExitPolicy::WaitForEvents(1))
            .await
            .unwrap()
            .first_owned()
            .unwrap();

        let cipher = request
            .tags
            .iter()
            .find_map(|tag| match Nip47Tag::parse(tag.as_slice()).ok()? {
                Nip47Tag::Encryption(ciphers) => Some(ciphers),
            })
            .unwrap_or(Nip47Ciphers::NIP04);

        assert_eq!(
            expected_cipher, cipher,
            "expected: {expected_cipher}. Found {cipher}"
        );

        let enc_response = cipher
            .encrypt(wkeys.secret_key(), &ckeys.public_key(), &RESPONSE.as_json())
            .unwrap();
        let response_event = EventBuilder::new(Kind::WalletConnectResponse, enc_response)
            .tag(Tag::public_key(ckeys.public_key()))
            .tag(Tag::event(request.id))
            .finalize(&wkeys)
            .unwrap();
        client.send_event(&response_event).await.unwrap();
    }

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

        let (wkeys, ckeys, uri) = create_keys(relay_url.clone());

        tokio::spawn(run_wallet(
            wkeys,
            ckeys,
            relay_url,
            None,
            Nip47Ciphers::NIP04,
        ));

        let client = NostrWalletConnectBuilder::new(uri).build();

        // `send_request` should use nip04 because there is no info event.
        let wallet_response = client
            .send_request(Request::get_balance(), Duration::from_secs(3))
            .await
            .unwrap();
        assert_eq!(RESPONSE, wallet_response);
    }

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

        let (wkeys, ckeys, uri) = create_keys(relay_url.clone());

        tokio::spawn(run_wallet(
            wkeys,
            ckeys,
            relay_url,
            Some(Nip47Ciphers::NIP44V2),
            Nip47Ciphers::NIP44V2,
        ));

        // Wait for the info event
        tokio::time::sleep(Duration::from_secs(1)).await;
        let client = NostrWalletConnectBuilder::new(uri).build();

        // `send_request` should use nip44_v2 because of the info event.
        let wallet_response = client
            .send_request(Request::get_balance(), Duration::from_secs(3))
            .await
            .unwrap();
        assert_eq!(RESPONSE, wallet_response);
    }

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

        let (wkeys, ckeys, uri) = create_keys(relay_url.clone());

        tokio::spawn(run_wallet(
            wkeys,
            ckeys,
            relay_url,
            Some(Nip47Ciphers::NIP04),
            Nip47Ciphers::NIP04,
        ));

        // Wait for the info event
        tokio::time::sleep(Duration::from_secs(1)).await;
        let client = NostrWalletConnectBuilder::new(uri).build();

        // `send_request` should use nip04 because of the info event.
        let wallet_response = client
            .send_request(Request::get_balance(), Duration::from_secs(3))
            .await
            .unwrap();
        assert_eq!(RESPONSE, wallet_response);
    }

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

        let (wkeys, ckeys, uri) = create_keys(relay_url.clone());

        tokio::spawn(run_wallet(
            wkeys,
            ckeys,
            relay_url,
            Some(Nip47Ciphers::NIP04.add(Nip47Ciphers::NIP44V2)),
            Nip47Ciphers::NIP44V2,
        ));

        // Wait for the info event
        tokio::time::sleep(Duration::from_secs(1)).await;
        let client = NostrWalletConnectBuilder::new(uri).build();

        // `send_request` should use nip44_v2 because of the info event.
        let wallet_response = client
            .send_request(Request::get_balance(), Duration::from_secs(3))
            .await
            .unwrap();
        assert_eq!(RESPONSE, wallet_response);
    }

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

        let (wkeys, ckeys, uri) = create_keys(relay_url.clone());

        tokio::spawn(run_wallet(
            wkeys,
            ckeys,
            relay_url,
            None,
            Nip47Ciphers::NIP04,
        ));

        // Wait for the info event
        tokio::time::sleep(Duration::from_secs(1)).await;
        let client = NostrWalletConnectBuilder::new(uri).force_nip04().build();

        // `send_request` should use nip04 because of the force.
        let wallet_response = client
            .send_request(Request::get_balance(), Duration::from_secs(3))
            .await
            .unwrap();
        assert_eq!(RESPONSE, wallet_response);
    }

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

        let (wkeys, ckeys, uri) = create_keys(relay_url.clone());

        tokio::spawn(run_wallet(
            wkeys,
            ckeys,
            relay_url,
            None,
            Nip47Ciphers::NIP44V2,
        ));

        // Wait for the info event
        tokio::time::sleep(Duration::from_secs(1)).await;
        let client = NostrWalletConnectBuilder::new(uri).force_nip44_v2().build();

        // `send_request` should use nip44_v2 because of the force.
        let wallet_response = client
            .send_request(Request::get_balance(), Duration::from_secs(3))
            .await
            .unwrap();
        assert_eq!(RESPONSE, wallet_response);
    }

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

        let (wkeys, ckeys, uri) = create_keys(relay_url.clone());

        tokio::spawn(run_wallet(
            wkeys,
            ckeys,
            relay_url,
            Some(Nip47Ciphers::NIP04.add(Nip47Ciphers::NIP44V2)),
            Nip47Ciphers::NIP04,
        ));

        // Wait for the info event
        tokio::time::sleep(Duration::from_secs(1)).await;
        let client = NostrWalletConnectBuilder::new(uri).force_nip04().build();

        // `send_request` should use nip04 because of the force.
        let wallet_response = client
            .send_request(Request::get_balance(), Duration::from_secs(3))
            .await
            .unwrap();
        assert_eq!(RESPONSE, wallet_response);
    }
}