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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
use crate::logging::MutinyLogger;
use crate::node::Node;
use crate::nodemanager::NodeManager;
use crate::nostr::nwc::{
    BudgetPeriod, BudgetedSpendingConditions, NostrWalletConnect, NwcProfile, NwcProfileTag,
    PendingNwcInvoice, Profile, SingleUseSpendingConditions, SpendingConditions,
    PENDING_NWC_EVENTS_KEY,
};
use crate::storage::MutinyStorage;
use crate::{error::MutinyError, utils::get_random_bip32_child_index};
use crate::{utils, HTLCStatus};
use bitcoin::hashes::hex::{FromHex, ToHex};
use bitcoin::hashes::{sha256, Hash};
use bitcoin::secp256k1::{PublicKey, Secp256k1, Signing};
use bitcoin::util::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey};
use futures::{pin_mut, select, FutureExt};
use futures_util::lock::Mutex;
use lightning::log_warn;
use lightning::util::logger::Logger;
use nostr::key::SecretKey;
use nostr::nips::nip47::*;
use nostr::prelude::{decrypt, encrypt};
use nostr::{Event, EventBuilder, EventId, Filter, Keys, Kind, Tag};
use nostr_sdk::{Client, RelayPoolNotification};
use std::str::FromStr;
use std::sync::atomic::Ordering;
use std::sync::{Arc, RwLock};
use std::time::Duration;

pub mod nwc;

const NWC_ACCOUNT_INDEX: u32 = 1;
const USER_NWC_PROFILE_START_INDEX: u32 = 1000;

const NWC_STORAGE_KEY: &str = "nwc_profiles";

/// Reserved profiles that are used internally.
/// Must not exceed `USER_NWC_PROFILE_START_INDEX`
pub enum ReservedProfile {
    MutinySubscription,
}

impl ReservedProfile {
    pub fn info(&self) -> (&'static str, u32) {
        let (n, i) = match self {
            ReservedProfile::MutinySubscription => ("Mutiny+ Subscription", 0),
        };
        if i >= USER_NWC_PROFILE_START_INDEX {
            panic!("Must not exceed 1000 reserved indexes")
        };
        (n, i)
    }
}

pub enum ProfileType {
    Reserved(ReservedProfile),
    Normal { name: String },
}

/// Manages Nostr keys and has different utilities for nostr specific things
#[derive(Clone)]
pub struct NostrManager<S: MutinyStorage> {
    /// Extended private key that is the root seed of the wallet
    xprivkey: ExtendedPrivKey,
    /// Primary key used for nostr, this will be used for signing events
    pub primary_key: Keys,
    /// Separate profiles for each nostr wallet connect string
    pub(crate) nwc: Arc<RwLock<Vec<NostrWalletConnect>>>,
    pub storage: S,
    /// Lock for pending nwc invoices
    pending_nwc_lock: Arc<Mutex<()>>,
    /// Logger
    pub logger: Arc<MutinyLogger>,
}

impl<S: MutinyStorage> NostrManager<S> {
    pub fn get_relays(&self) -> Vec<String> {
        let mut relays: Vec<String> = self
            .nwc
            .read()
            .unwrap()
            .iter()
            .filter(|x| x.profile.active())
            .map(|x| x.profile.relay.clone())
            .collect();

        // remove duplicates
        relays.sort();
        relays.dedup();

        relays
    }

    pub fn get_nwc_filters(&self) -> Vec<Filter> {
        self.nwc
            .read()
            .unwrap()
            .iter()
            .filter(|x| x.profile.active())
            .map(|nwc| nwc.create_nwc_filter())
            .collect()
    }

    pub fn get_nwc_uri(&self, index: u32) -> Result<String, MutinyError> {
        let opt = self
            .nwc
            .read()
            .unwrap()
            .iter()
            .find(|nwc| nwc.profile.index == index)
            .map(|nwc| nwc.get_nwc_uri());

        if let Some(uri) = opt {
            Ok(uri?)
        } else {
            Err(MutinyError::NotFound)
        }
    }

    pub fn profiles(&self) -> Vec<NwcProfile> {
        self.nwc
            .read()
            .unwrap()
            .iter()
            .filter(|x| x.profile.active())
            .map(|x| x.nwc_profile())
            .collect()
    }

    pub(crate) fn remove_inactive_profiles(&self) -> Result<(), MutinyError> {
        let mut profiles = self.nwc.write().unwrap();

        profiles.retain(|x| x.profile.active());

        // save to storage
        {
            let profiles = profiles
                .iter()
                .map(|x| x.profile.clone())
                .collect::<Vec<_>>();
            self.storage.set_data(NWC_STORAGE_KEY, profiles, None)?;
        }

        Ok(())
    }

    /// Goes through all single use profiles and removes the successfully paid ones
    pub(crate) fn clear_successful_single_use_profiles(
        &self,
        node: &Node<S>,
    ) -> Result<(), MutinyError> {
        let mut profiles = self.nwc.write().unwrap();

        profiles.retain(|x| {
            if let SpendingConditions::SingleUse(single_use) = &x.profile.spending_conditions {
                if let Some(payment_hash) = &single_use.payment_hash {
                    let hash: [u8; 32] = FromHex::from_hex(payment_hash).expect("invalid hash");
                    if let Some(payment) =
                        node.persister.read_payment_info(&hash, false, &self.logger)
                    {
                        if payment.status == HTLCStatus::Succeeded {
                            return false;
                        }
                    }
                }
            }
            true
        });

        // save to storage
        {
            let profiles = profiles
                .iter()
                .map(|x| x.profile.clone())
                .collect::<Vec<_>>();
            self.storage.set_data(NWC_STORAGE_KEY, profiles, None)?;
        }

        Ok(())
    }

    pub fn edit_profile(&self, profile: NwcProfile) -> Result<NwcProfile, MutinyError> {
        let mut profiles = self.nwc.write().unwrap();
        let index = profile.index;

        let nwc = profiles
            .iter_mut()
            .find(|nwc| nwc.profile.index == index)
            .ok_or(MutinyError::NotFound)?;

        nwc.profile = profile.profile();

        let nwc_profile = nwc.nwc_profile();

        // save to storage
        {
            let profiles = profiles
                .iter()
                .map(|x| x.profile.clone())
                .collect::<Vec<_>>();
            self.storage.set_data(NWC_STORAGE_KEY, profiles, None)?;
        }

        Ok(nwc_profile)
    }

    pub fn set_nwc_profile_budget(
        &self,
        profile_index: u32,
        budget_sats: u64,
        budget_period: BudgetPeriod,
        single_max_sats: Option<u64>,
    ) -> Result<NwcProfile, MutinyError> {
        let mut profiles = self.nwc.write().unwrap();

        let nwc = profiles
            .iter_mut()
            .find(|nwc| nwc.profile.index == profile_index)
            .ok_or(MutinyError::NotFound)?;

        let payments = if let SpendingConditions::Budget(budget) = &nwc.profile.spending_conditions
        {
            budget.payments.clone()
        } else {
            vec![]
        };

        nwc.profile.spending_conditions = SpendingConditions::Budget(BudgetedSpendingConditions {
            budget: budget_sats,
            single_max: single_max_sats,
            payments,
            period: budget_period,
        });

        let nwc_profile = nwc.nwc_profile();

        // save to storage
        {
            let profiles = profiles
                .iter()
                .map(|x| x.profile.clone())
                .collect::<Vec<_>>();
            self.storage.set_data(NWC_STORAGE_KEY, profiles, None)?;
        }

        Ok(nwc_profile)
    }

    pub fn get_profile(&self, index: u32) -> Result<NwcProfile, MutinyError> {
        let profiles = self.nwc.read().unwrap();

        let nwc = profiles
            .iter()
            .find(|nwc| nwc.profile.index == index)
            .ok_or(MutinyError::NotFound)?;

        Ok(nwc.nwc_profile())
    }

    /// Creates a new NWC profile and saves to storage
    pub(crate) fn create_new_profile(
        &self,
        profile_type: ProfileType,
        spending_conditions: SpendingConditions,
        tag: NwcProfileTag,
    ) -> Result<NwcProfile, MutinyError> {
        let mut profiles = self.nwc.write().unwrap();

        let (name, index, child_key_index) = match profile_type {
            ProfileType::Reserved(reserved_profile) => {
                let (name, index) = reserved_profile.info();
                (name.to_string(), index, None)
            }
            // Ensure normal profiles start from 1000
            ProfileType::Normal { name } => {
                let next_index = profiles
                    .iter()
                    .filter(|&nwc| nwc.profile.index >= USER_NWC_PROFILE_START_INDEX)
                    .max_by(|a, b| a.profile.index.cmp(&b.profile.index))
                    .map(|nwc| nwc.profile.index + 1)
                    .unwrap_or(USER_NWC_PROFILE_START_INDEX);

                debug_assert!(next_index >= USER_NWC_PROFILE_START_INDEX);

                (name, next_index, Some(get_random_bip32_child_index()))
            }
        };

        let profile = Profile {
            name,
            index,
            child_key_index,
            relay: "wss://nostr.mutinywallet.com".to_string(),
            enabled: None,
            archived: None,
            spending_conditions,
            tag,
        };
        let nwc = NostrWalletConnect::new(&Secp256k1::new(), self.xprivkey, profile)?;

        profiles.push(nwc.clone());
        profiles.sort_by_key(|nwc| nwc.profile.index);

        // save to storage
        {
            let profiles = profiles
                .iter()
                .map(|x| x.profile.clone())
                .collect::<Vec<_>>();
            self.storage.set_data(NWC_STORAGE_KEY, profiles, None)?;
        }

        Ok(nwc.nwc_profile())
    }

    /// Creates a new NWC profile and saves to storage
    /// This will also broadcast the info event to the relay
    pub async fn create_new_nwc_profile(
        &self,
        profile_type: ProfileType,
        spending_conditions: SpendingConditions,
        tag: NwcProfileTag,
    ) -> Result<NwcProfile, MutinyError> {
        let profile = self.create_new_profile(profile_type, spending_conditions, tag)?;

        let info_event = self.nwc.read().unwrap().iter().find_map(|nwc| {
            if nwc.profile.index == profile.index {
                nwc.create_nwc_info_event().ok()
            } else {
                None
            }
        });

        if let Some(info_event) = info_event {
            let client = Client::new(&self.primary_key);

            #[cfg(target_arch = "wasm32")]
            let add_relay_res = client.add_relay(profile.relay.as_str()).await;

            #[cfg(not(target_arch = "wasm32"))]
            let add_relay_res = client.add_relay(profile.relay.as_str(), None).await;

            add_relay_res.expect("Failed to add relays");
            client.connect().await;

            client.send_event(info_event).await.map_err(|e| {
                MutinyError::Other(anyhow::anyhow!("Failed to send info event: {e:?}"))
            })?;

            let _ = client.disconnect().await;
        }

        Ok(profile)
    }

    pub async fn create_single_use_nwc(
        &self,
        name: String,
        amount_sats: u64,
    ) -> Result<NwcProfile, MutinyError> {
        let profile = ProfileType::Normal { name };

        let spending_conditions = SpendingConditions::SingleUse(SingleUseSpendingConditions {
            amount_sats,
            payment_hash: None,
        });
        self.create_new_nwc_profile(profile, spending_conditions, NwcProfileTag::Gift)
            .await
    }

    /// Lists all pending NWC invoices
    pub fn get_pending_nwc_invoices(&self) -> Result<Vec<PendingNwcInvoice>, MutinyError> {
        Ok(self
            .storage
            .get_data(PENDING_NWC_EVENTS_KEY)?
            .unwrap_or_default())
    }

    fn find_nwc_data(
        &self,
        hash: sha256::Hash,
    ) -> Result<(NostrWalletConnect, PendingNwcInvoice), MutinyError> {
        let pending: Vec<PendingNwcInvoice> = self
            .storage
            .get_data(PENDING_NWC_EVENTS_KEY)?
            .unwrap_or_default();

        let inv = pending
            .iter()
            .find(|x| x.invoice.payment_hash() == &hash)
            .ok_or(MutinyError::NotFound)?;

        let nwc = {
            let profiles = self.nwc.read().unwrap();
            profiles
                .iter()
                .find(|x| x.profile.index == inv.index)
                .ok_or(MutinyError::NotFound)?
                .clone()
        };

        Ok((nwc, inv.to_owned()))
    }

    async fn broadcast_nwc_response(
        &self,
        resp: Response,
        nwc: NostrWalletConnect,
        inv: PendingNwcInvoice,
    ) -> Result<EventId, MutinyError> {
        let client = Client::new(&self.primary_key);

        #[cfg(target_arch = "wasm32")]
        let add_relay_res = client.add_relay(nwc.profile.relay.as_str()).await;

        #[cfg(not(target_arch = "wasm32"))]
        let add_relay_res = client.add_relay(nwc.profile.relay.as_str(), None).await;

        add_relay_res.expect("Failed to add relays");
        client.connect().await;

        let encrypted = encrypt(
            &nwc.server_key.secret_key().unwrap(),
            &nwc.client_pubkey(),
            resp.as_json(),
        )
        .unwrap();

        let p_tag = Tag::PubKey(inv.pubkey, None);
        let e_tag = Tag::Event(inv.event_id, None, None);
        let response = EventBuilder::new(Kind::WalletConnectResponse, encrypted, &[p_tag, e_tag])
            .to_event(&nwc.server_key)
            .map_err(|e| MutinyError::Other(anyhow::anyhow!("Failed to create event: {e:?}")))?;

        let event_id = client
            .send_event(response)
            .await
            .map_err(|e| MutinyError::Other(anyhow::anyhow!("Failed to send info event: {e:?}")))?;

        let _ = client.disconnect().await;

        Ok(event_id)
    }

    /// Approves an invoice and sends the payment
    pub async fn approve_invoice(
        &self,
        hash: sha256::Hash,
        node_manager: &NodeManager<S>,
        from_node: &PublicKey,
    ) -> Result<EventId, MutinyError> {
        let (nwc, inv) = self.find_nwc_data(hash)?;

        let resp = nwc
            .pay_nwc_invoice(node_manager, from_node, &inv.invoice)
            .await?;

        let event_id = self.broadcast_nwc_response(resp, nwc, inv).await?;

        // get lock for writing
        self.pending_nwc_lock.lock().await;

        // get from storage again, in case it was updated
        let mut pending: Vec<PendingNwcInvoice> = self
            .storage
            .get_data(PENDING_NWC_EVENTS_KEY)?
            .unwrap_or_default();

        // remove from storage
        pending.retain(|x| x.invoice.payment_hash() != &hash);
        self.storage
            .set_data(PENDING_NWC_EVENTS_KEY, pending, None)?;

        Ok(event_id)
    }

    /// Removes an invoice from the pending list, will also remove expired invoices
    pub async fn deny_invoice(&self, hash: sha256::Hash) -> Result<(), MutinyError> {
        // need to tell relay to remove the invoice
        // doesn't work in test environment
        #[cfg(not(test))]
        {
            let resp = Response {
                result_type: Method::PayInvoice,
                error: Some(NIP47Error {
                    code: ErrorCode::Other,
                    message: "Rejected".to_string(),
                }),
                result: None,
            };
            let (nwc, inv) = self.find_nwc_data(hash)?;
            self.broadcast_nwc_response(resp, nwc, inv).await?;
        }

        // wait for lock
        self.pending_nwc_lock.lock().await;

        let mut invoices: Vec<PendingNwcInvoice> = self
            .storage
            .get_data(PENDING_NWC_EVENTS_KEY)?
            .unwrap_or_default();

        // remove expired invoices
        invoices.retain(|x| !x.is_expired());

        // remove the invoice
        invoices.retain(|x| x.invoice.payment_hash() != &hash);

        self.storage
            .set_data(PENDING_NWC_EVENTS_KEY, invoices, None)?;

        Ok(())
    }

    /// Goes through all pending NWC invoices and removes the expired ones
    pub async fn clear_expired_nwc_invoices(&self) -> Result<(), MutinyError> {
        self.pending_nwc_lock.lock().await;
        let mut invoices: Vec<PendingNwcInvoice> = self
            .storage
            .get_data(PENDING_NWC_EVENTS_KEY)?
            .unwrap_or_default();

        // remove expired invoices
        invoices.retain(|x| !x.is_expired());

        // sort and dedup
        invoices.sort();
        invoices.dedup();

        self.storage
            .set_data(PENDING_NWC_EVENTS_KEY, invoices, None)?;

        Ok(())
    }

    pub async fn handle_nwc_request(
        &self,
        event: Event,
        node_manager: &NodeManager<S>,
        from_node: &PublicKey,
    ) -> anyhow::Result<Option<Event>> {
        let nwc = {
            let vec = self.nwc.read().unwrap();
            vec.iter()
                .find(|nwc| nwc.client_pubkey() == event.pubkey)
                .cloned()
        };

        if let Some(mut nwc) = nwc {
            let event = nwc
                .handle_nwc_request(event, node_manager, from_node, self)
                .await?;
            Ok(event)
        } else {
            Ok(None)
        }
    }

    pub(crate) fn save_nwc_profile(&self, nwc: NostrWalletConnect) -> Result<(), MutinyError> {
        let mut vec = self.nwc.write().unwrap();

        // update the profile
        for item in vec.iter_mut() {
            if item.profile.index == nwc.profile.index {
                item.profile = nwc.profile;
                break;
            }
        }

        let profiles = vec.iter().map(|x| x.profile.clone()).collect::<Vec<_>>();

        self.storage.set_data(NWC_STORAGE_KEY, profiles, None)?;

        Ok(())
    }

    pub fn delete_nwc_profile(&self, index: u32) -> Result<(), MutinyError> {
        let mut vec = self.nwc.write().unwrap();

        // update the profile
        vec.retain(|x| x.profile.index != index);

        let profiles = vec.iter().map(|x| x.profile.clone()).collect::<Vec<_>>();

        self.storage.set_data(NWC_STORAGE_KEY, profiles, None)?;

        Ok(())
    }

    pub async fn claim_single_use_nwc(
        &self,
        amount_sats: u64,
        nwc_uri: &str,
        node_manager: &NodeManager<S>,
    ) -> Result<Option<NIP47Error>, MutinyError> {
        let nwc = NostrWalletConnectURI::from_str(nwc_uri)
            .map_err(|_| MutinyError::InvalidArgumentsError)?;
        let secret = Keys::new(nwc.secret);
        let client = Client::new(&secret);

        #[cfg(target_arch = "wasm32")]
        let add_relay_res = client.add_relay(nwc.relay_url.as_str()).await;

        #[cfg(not(target_arch = "wasm32"))]
        let add_relay_res = client.add_relay(nwc.relay_url.as_str(), None).await;

        add_relay_res.expect("Failed to add relays");
        client.connect().await;

        let invoice = node_manager
            .create_invoice(Some(amount_sats), vec!["Gift".to_string()])
            .await?;
        // unwrap is safe, we just created it
        let bolt11 = invoice.bolt11.unwrap();

        let req = Request {
            method: Method::PayInvoice,
            params: RequestParams::PayInvoice(PayInvoiceRequestParams {
                invoice: bolt11.to_string(),
            }),
        };
        let encrypted = encrypt(&nwc.secret, &nwc.public_key, req.as_json())?;
        let p_tag = Tag::PubKey(nwc.public_key, None);
        let request_event =
            EventBuilder::new(Kind::WalletConnectRequest, encrypted, &[p_tag]).to_event(&secret)?;

        let filter = Filter::new()
            .kind(Kind::WalletConnectResponse)
            .author(nwc.public_key.to_hex())
            .pubkey(secret.public_key())
            .event(request_event.id);

        client.subscribe(vec![filter]).await;

        client
            .send_event(request_event.clone())
            .await
            .map_err(|e| {
                MutinyError::Other(anyhow::anyhow!("Failed to send request event: {e:?}"))
            })?;

        let mut notifications = client.notifications();

        let start_time = utils::now();

        // every second, check for response event, invoice paid, or timeout
        loop {
            let now = utils::now();
            if now - start_time > Duration::from_secs(30) {
                client.disconnect().await?;
                return Err(MutinyError::PaymentTimeout);
            }

            // check if the invoice has been paid, if so, return, otherwise continue
            // checking for response event
            if let Ok(invoice) = node_manager.get_invoice(&bolt11).await {
                if invoice.paid() {
                    break;
                }
            }

            let read_fut = notifications.recv().fuse();
            let delay_fut = Box::pin(utils::sleep(1_000)).fuse();

            pin_mut!(read_fut, delay_fut);
            select! {
                notification = read_fut => {
                    match notification {
                        Ok(RelayPoolNotification::Event(_url, event)) => {
                            let has_e_tag = event.tags.iter().any(|x| {
                                if let Tag::Event(id, _, _) = x {
                                    *id == request_event.id
                                } else {
                                        false
                                }
                            });
                            if has_e_tag && event.kind == Kind::WalletConnectResponse && event.verify().is_ok() {
                                let decrypted = decrypt(&nwc.secret, &nwc.public_key, &event.content)?;
                                let resp: Response = serde_json::from_str(&decrypted)?;

                                if resp.result_type == Method::PayInvoice {
                                    client.disconnect().await?;

                                    match resp.result {
                                        Some(ResponseResult::PayInvoice(params)) => {
                                            let preimage: Vec<u8> = FromHex::from_hex(&params.preimage)?;
                                            if sha256::Hash::hash(&preimage) != invoice.payment_hash {
                                                log_warn!(self.logger, "Received payment preimage that does not represent the invoice hash");
                                            }
                                            return Ok(None);
                                        },
                                        Some(_) => unreachable!("Should not receive any other response type"),
                                        None => return Ok(resp.error),
                                    }
                                }
                            }
                        },
                        Ok(RelayPoolNotification::Message(_, _)) => {}, // ignore messages
                        Ok(RelayPoolNotification::Stop) => {}, // ignore stops
                        Ok(RelayPoolNotification::Shutdown) =>
                            return Err(MutinyError::ConnectionFailed),
                        Err(_) => return Err(MutinyError::ConnectionFailed),
                    }
                }
                _ = delay_fut => {
                    if node_manager.stop.load(Ordering::Relaxed) {
                        client.disconnect().await?;
                        return Err(MutinyError::NotRunning);
                    }
                }
            }
        }

        client.disconnect().await?;

        Ok(None)
    }

    /// Derives the client and server keys for Nostr Wallet Connect given a profile index
    /// The left key is the client key and the right key is the server key
    pub(crate) fn derive_nwc_keys<C: Signing>(
        context: &Secp256k1<C>,
        xprivkey: ExtendedPrivKey,
        profile_index: u32,
    ) -> Result<(Keys, Keys), MutinyError> {
        let client_key = Self::derive_nostr_key(
            context,
            xprivkey,
            NWC_ACCOUNT_INDEX,
            Some(profile_index),
            Some(0),
        )?;
        let server_key = Self::derive_nostr_key(
            context,
            xprivkey,
            NWC_ACCOUNT_INDEX,
            Some(profile_index),
            Some(1),
        )?;

        Ok((client_key, server_key))
    }

    fn derive_nostr_key<C: Signing>(
        context: &Secp256k1<C>,
        xprivkey: ExtendedPrivKey,
        account: u32,
        chain: Option<u32>,
        index: Option<u32>,
    ) -> Result<Keys, MutinyError> {
        let chain = match chain {
            Some(chain) => ChildNumber::from_hardened_idx(chain)?,
            None => ChildNumber::from_normal_idx(0)?,
        };

        let index = match index {
            Some(index) => ChildNumber::from_hardened_idx(index)?,
            None => ChildNumber::from_normal_idx(0)?,
        };

        let path = DerivationPath::from_str(&format!("m/44'/1237'/{account}'/{chain}/{index}"))?;
        let key = xprivkey.derive_priv(context, &path)?;

        // just converting to nostr secret key, unwrap is safe
        let secret_key = SecretKey::from_slice(&key.private_key.secret_bytes()).unwrap();
        Ok(Keys::new(secret_key))
    }

    /// Creates a new NostrManager
    pub fn from_mnemonic(
        xprivkey: ExtendedPrivKey,
        storage: S,
        logger: Arc<MutinyLogger>,
    ) -> Result<Self, MutinyError> {
        let context = Secp256k1::new();

        // generate the default primary key
        let primary_key = Self::derive_nostr_key(&context, xprivkey, 0, None, None)?;

        // get from storage
        let profiles: Vec<Profile> = storage.get_data(NWC_STORAGE_KEY)?.unwrap_or_default();

        // generate the wallet connect keys
        let nwc = profiles
            .into_iter()
            .map(|profile| NostrWalletConnect::new(&context, xprivkey, profile).unwrap())
            .collect();

        Ok(Self {
            xprivkey,
            primary_key,
            nwc: Arc::new(RwLock::new(nwc)),
            storage,
            pending_nwc_lock: Arc::new(Mutex::new(())),
            logger,
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::storage::MemoryStorage;
    use bip39::Mnemonic;
    use bitcoin::util::bip32::ExtendedPrivKey;
    use bitcoin::Network;
    use futures::executor::block_on;
    use lightning_invoice::Bolt11Invoice;
    use nostr::key::XOnlyPublicKey;
    use std::str::FromStr;

    fn create_nostr_manager() -> NostrManager<MemoryStorage> {
        let mnemonic = Mnemonic::from_str("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about").expect("could not generate");

        let xprivkey =
            ExtendedPrivKey::new_master(Network::Bitcoin, &mnemonic.to_seed("")).unwrap();

        let storage = MemoryStorage::new(None, None, None);

        let logger = Arc::new(MutinyLogger::default());

        NostrManager::from_mnemonic(xprivkey, storage, logger).unwrap()
    }

    #[test]
    fn test_create_profile() {
        let nostr_manager = create_nostr_manager();

        let name = "test".to_string();

        let profile = nostr_manager
            .create_new_profile(
                ProfileType::Normal { name: name.clone() },
                SpendingConditions::default(),
                Default::default(),
            )
            .unwrap();

        assert_eq!(profile.name, name);
        assert_eq!(profile.index, 1000);

        let profiles = nostr_manager.profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].name, name);
        assert_eq!(profiles[0].index, 1000);

        let profiles: Vec<Profile> = nostr_manager
            .storage
            .get_data(NWC_STORAGE_KEY)
            .unwrap()
            .unwrap_or_default();

        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].name, name);
        assert_eq!(profiles[0].index, 1000);
    }

    #[test]
    fn test_create_reserve_profile() {
        let nostr_manager = create_nostr_manager();

        let name = "Mutiny+ Subscription".to_string();

        let profile = nostr_manager
            .create_new_profile(
                ProfileType::Reserved(ReservedProfile::MutinySubscription),
                SpendingConditions::default(),
                Default::default(),
            )
            .unwrap();

        assert_eq!(profile.name, name);
        assert_eq!(profile.index, 0);

        let profiles = nostr_manager.profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].name, name);
        assert_eq!(profiles[0].index, 0);

        let profiles: Vec<Profile> = nostr_manager
            .storage
            .get_data(NWC_STORAGE_KEY)
            .unwrap()
            .unwrap_or_default();

        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].name, name);
        assert_eq!(profiles[0].index, 0);

        // now create normal profile
        let name = "test".to_string();

        let profile = nostr_manager
            .create_new_profile(
                ProfileType::Normal { name: name.clone() },
                SpendingConditions::default(),
                Default::default(),
            )
            .unwrap();

        assert_eq!(profile.name, name);
        assert_eq!(profile.index, 1000);
        assert!(profile.child_key_index.is_some());

        // create a non child_key_index profile
        let non_child_key_index_profile = Profile {
            name,
            index: 1001,
            relay: "wss://nostr.mutinywallet.com".to_string(),
            enabled: None,
            archived: None,
            child_key_index: None,
            spending_conditions: Default::default(),
            tag: Default::default(),
        };
        let mut profiles = nostr_manager.nwc.write().unwrap();
        let nwc = NostrWalletConnect::new(
            &Secp256k1::new(),
            nostr_manager.xprivkey,
            non_child_key_index_profile,
        )
        .unwrap();
        let original_nwc_uri = nwc.get_nwc_uri().unwrap();
        profiles.push(nwc);
        profiles.sort_by_key(|nwc| nwc.profile.index);
        {
            let profiles = profiles
                .iter()
                .map(|x| x.profile.clone())
                .collect::<Vec<_>>();
            nostr_manager
                .storage
                .set_data(NWC_STORAGE_KEY, profiles, None)
                .unwrap();
        }
        // now read it and make sure the NWC URI is still correct
        let profiles: Vec<Profile> = nostr_manager
            .storage
            .get_data(NWC_STORAGE_KEY)
            .unwrap()
            .unwrap_or_default();
        let mut new_profile = profiles[2].clone();
        let new_nwc = NostrWalletConnect::new(
            &Secp256k1::new(),
            nostr_manager.xprivkey,
            new_profile.clone(),
        )
        .unwrap();

        assert_eq!(new_profile.clone().index, 1001);
        assert!(new_profile.child_key_index.is_none());
        assert_eq!(original_nwc_uri, new_nwc.get_nwc_uri().unwrap());

        // if we change the index then it should change the private key/nwc
        new_profile.index = 1002;
        let changed_nwc = NostrWalletConnect::new(
            &Secp256k1::new(),
            nostr_manager.xprivkey,
            new_profile.clone(),
        )
        .unwrap();
        assert_ne!(original_nwc_uri, changed_nwc.get_nwc_uri().unwrap());
    }

    #[test]
    fn test_edit_profile() {
        let nostr_manager = create_nostr_manager();

        let name = "test".to_string();

        let mut profile = nostr_manager
            .create_new_profile(
                ProfileType::Normal { name: name.clone() },
                SpendingConditions::default(),
                Default::default(),
            )
            .unwrap();

        assert_eq!(profile.name, name);
        assert_eq!(profile.index, 1000);
        assert_eq!(profile.relay.as_str(), "wss://nostr.mutinywallet.com");

        profile.relay = "wss://relay.damus.io".to_string();

        nostr_manager.edit_profile(profile).unwrap();

        let profiles = nostr_manager.profiles();
        assert_eq!(profiles.len(), 1);
        // check this stuff is the same
        assert_eq!(profiles[0].name, name);
        assert_eq!(profiles[0].index, 1000);
        // check this is different
        assert_eq!(profiles[0].relay.as_str(), "wss://relay.damus.io");

        let profiles: Vec<Profile> = nostr_manager
            .storage
            .get_data(NWC_STORAGE_KEY)
            .unwrap()
            .unwrap_or_default();

        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].name, name);
        assert_eq!(profiles[0].index, 1000);
    }

    #[test]
    fn test_delete_profile() {
        let nostr_manager = create_nostr_manager();

        let name = "test".to_string();

        let profile = nostr_manager
            .create_new_profile(
                ProfileType::Normal { name: name.clone() },
                SpendingConditions::default(),
                Default::default(),
            )
            .unwrap();

        assert_eq!(profile.name, name);
        assert_eq!(profile.index, 1000);
        assert_eq!(profile.relay.as_str(), "wss://nostr.mutinywallet.com");

        nostr_manager.delete_nwc_profile(profile.index).unwrap();

        let profiles = nostr_manager.profiles();
        assert_eq!(profiles.len(), 0);

        let profiles: Vec<Profile> = nostr_manager
            .storage
            .get_data(NWC_STORAGE_KEY)
            .unwrap()
            .unwrap_or_default();

        assert_eq!(profiles.len(), 0);
    }

    #[test]
    fn test_deny_invoice() {
        let nostr_manager = create_nostr_manager();

        let name = "test".to_string();

        let profile = nostr_manager
            .create_new_profile(
                ProfileType::Normal { name },
                SpendingConditions::default(),
                Default::default(),
            )
            .unwrap();

        let inv = PendingNwcInvoice {
            index: profile.index,
            invoice: Bolt11Invoice::from_str("lnbc923720n1pj9nrefpp5pczykgk37af5388n8dzynljpkzs7sje4melqgazlwv9y3apay8jqhp5rd8saxz3juve3eejq7z5fjttxmpaq88d7l92xv34n4h3mq6kwq2qcqzzsxqzfvsp5z0jwpehkuz9f2kv96h62p8x30nku76aj8yddpcust7g8ad0tr52q9qyyssqfy622q25helv8cj8hyxqltws4rdwz0xx2hw0uh575mn7a76cp3q4jcptmtjkjs4a34dqqxn8uy70d0qlxqleezv4zp84uk30pp5q3nqq4c9gkz").unwrap(),
            event_id: EventId::from_slice(&[0; 32]).unwrap(),
            pubkey: XOnlyPublicKey::from_str("552a9d06810f306bfc085cb1e1c26102554138a51fa3a7fdf98f5b03a945143a").unwrap(),
        };

        // add dummy to storage
        nostr_manager
            .storage
            .set_data(PENDING_NWC_EVENTS_KEY, vec![inv.clone()], None)
            .unwrap();

        let pending = nostr_manager.get_pending_nwc_invoices().unwrap();
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].invoice, inv.invoice);

        block_on(nostr_manager.deny_invoice(inv.invoice.payment_hash().to_owned())).unwrap();

        let pending = nostr_manager.get_pending_nwc_invoices().unwrap();
        assert_eq!(pending.len(), 0);
    }
}