cdk 0.18.0-rc.3

Core Cashu Development Kit library implementing the Cashu protocol
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
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
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
//! NpubCash integration for CDK Wallet
//!
//! This module provides integration between the CDK wallet and the NpubCash service,
//! allowing wallets to sync quotes, subscribe to updates, and manage NpubCash settings.

use std::collections::HashSet;
use std::sync::Arc;

use bitcoin::bip32::{ChildNumber, DerivationPath, Xpriv};
use bitcoin::Network;
use cdk_common::{database, SECP256K1};
use cdk_nostr::npubcash::{JwtAuthProvider, NpubCashClient, Quote};
use tracing::instrument;

use crate::error::Error;
use crate::nuts::SecretKey;
use crate::wallet::types::{MintQuote, TransactionDirection, TransactionStatus};
use crate::wallet::{MintQuoteState, Wallet};
use crate::Amount;

/// KV store namespace for npubcash-related data
pub const NPUBCASH_KV_NAMESPACE: &str = "npubcash";
/// KV store secondary namespace marking quotes that came from NpubCash
const QUOTES_KV_SECONDARY_NAMESPACE: &str = "quotes";
/// Quote marker for the current NIP-06 NpubCash signing key
const QUOTE_KEY_NIP06: &[u8] = b"nip06";
/// Quote marker for quotes imported from the legacy seed-prefix NpubCash identity
const QUOTE_KEY_LEGACY_SEED_PREFIX: &[u8] = b"legacy-seed-prefix";
/// KV store key for the last fetch timestamp (stored as u64 Unix timestamp)
const LAST_FETCH_TIMESTAMP_KEY: &str = "last_fetch_timestamp";
/// KV store key for whether the provenance-safe legacy quote migration completed
const LEGACY_QUOTES_MIGRATED_V2_KEY: &str = "legacy_quotes_migrated_v2";
/// KV store key for the active mint URL
pub const ACTIVE_MINT_KEY: &str = "active_mint";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NpubCashQuoteKey {
    Nip06,
    LegacySeedPrefix,
}

impl NpubCashQuoteKey {
    fn as_bytes(self) -> &'static [u8] {
        match self {
            Self::Nip06 => QUOTE_KEY_NIP06,
            Self::LegacySeedPrefix => QUOTE_KEY_LEGACY_SEED_PREFIX,
        }
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        match bytes {
            QUOTE_KEY_LEGACY_SEED_PREFIX => Self::LegacySeedPrefix,
            // Empty values were written by the first non-persisting-key
            // implementation and used the current NIP-06 key.
            _ => Self::Nip06,
        }
    }
}

fn merge_npubcash_quote(mut incoming: MintQuote, existing: MintQuote) -> MintQuote {
    incoming.state = match (incoming.state, existing.state) {
        (MintQuoteState::Issued, _) | (_, MintQuoteState::Issued) => MintQuoteState::Issued,
        (MintQuoteState::Paid, _) | (_, MintQuoteState::Paid) => MintQuoteState::Paid,
        (MintQuoteState::Unpaid, MintQuoteState::Unpaid) => MintQuoteState::Unpaid,
    };
    incoming.amount_paid = incoming.amount_paid.max(existing.amount_paid);
    incoming.amount_issued = incoming.amount_issued.max(existing.amount_issued);
    incoming.updated_at = incoming.updated_at.max(existing.updated_at);
    incoming.secret_key = existing.secret_key;
    incoming.estimated_blocks = existing.estimated_blocks;
    incoming.used_by_operation = existing.used_by_operation;
    incoming.version = existing.version;
    incoming
}

/// Derive the current NpubCash secret key from a wallet seed
///
/// Uses NIP-06 BIP-32 derivation (`m/44'/1237'/0'/0/0`) so the key never
/// equals raw seed material and cannot be used to recover the seed.
///
/// # Errors
///
/// Returns an error if the key derivation fails
pub fn derive_npubcash_secret_key_from_seed(seed: &[u8; 64]) -> Result<SecretKey, Error> {
    let path = DerivationPath::from(vec![
        ChildNumber::from_hardened_idx(44)?,
        ChildNumber::from_hardened_idx(1237)?,
        ChildNumber::from_hardened_idx(0)?,
        ChildNumber::from_normal_idx(0)?,
        ChildNumber::from_normal_idx(0)?,
    ]);

    let xpriv = Xpriv::new_master(Network::Bitcoin, seed)?;

    Ok(SecretKey::from(
        xpriv.derive_priv(&SECP256K1, &path)?.private_key,
    ))
}

impl Wallet {
    /// Enable NpubCash integration for this wallet
    ///
    /// Registers the wallet's mint URL on the server and enables NUT-20 quote
    /// locking, so that quotes created after enabling can only be minted by
    /// this wallet. The client is only exposed to the rest of the wallet
    /// after locking has been enabled and confirmed; already-existing
    /// unlocked quotes remain claimable.
    ///
    /// # Arguments
    ///
    /// * `npubcash_url` - Base URL of the NpubCash service (e.g., "<https://npubx.cash>")
    ///
    /// # Errors
    ///
    /// Returns an error if the NpubCash client cannot be initialized, or if
    /// quote locking cannot be enabled and confirmed — for example when the
    /// configured mint does not support NUT-20.
    #[instrument(skip(self))]
    pub async fn enable_npubcash(&self, npubcash_url: String) -> Result<(), Error> {
        let keys = self.derive_npubcash_keys()?;
        let auth_provider = Arc::new(JwtAuthProvider::new(npubcash_url.clone(), keys));
        let client = Arc::new(NpubCashClient::new(npubcash_url.clone(), auth_provider));

        // Automatically set the mint URL on the NpubCash server
        let mint_url = self.mint_url.to_string();
        match client.set_mint_url(&mint_url).await {
            Ok(_) => {
                tracing::info!(
                    "Mint URL '{}' set on NpubCash server at '{}'",
                    mint_url,
                    npubcash_url
                );
            }
            Err(e) => {
                tracing::warn!(
                    "Failed to set mint URL on NpubCash server: {}. Quotes may use server default.",
                    e
                );
            }
        }

        // New quotes must be locked to this wallet's NpubCash npub so only
        // this wallet can mint them. Locking is an invariant of the
        // integration: do not expose the client when the server rejects it
        // (e.g. the configured mint lacks NUT-20 support) or does not
        // confirm it.
        let response = client.set_quote_locking(true).await.map_err(|e| {
            Error::Custom(format!("Failed to enable NpubCash quote locking: {}", e))
        })?;
        if !response.data.user().lock_quote {
            return Err(Error::Custom(
                "NpubCash server did not confirm quote locking".to_string(),
            ));
        }
        tracing::info!("NpubCash quote locking enabled at '{}'", npubcash_url);

        if let Err(e) = self.import_legacy_npubcash_quotes_once(&npubcash_url).await {
            tracing::warn!("Failed to import legacy NpubCash quotes: {}", e);
        }

        let mut npubcash = self.npubcash_client.write().await;
        *npubcash = Some(client);
        drop(npubcash);

        tracing::info!("NpubCash integration enabled");

        Ok(())
    }

    /// Derive the NpubCash secret key from the wallet seed
    ///
    /// Uses NIP-06 BIP-32 derivation (`m/44'/1237'/0'/0/0`) so the key never
    /// equals raw seed material and cannot be used to recover the seed.
    ///
    /// # Errors
    ///
    /// Returns an error if the key derivation fails
    pub(crate) fn derive_npubcash_secret_key(&self) -> Result<SecretKey, Error> {
        derive_npubcash_secret_key_from_seed(&self.seed)
    }

    fn derive_legacy_npubcash_secret_key(&self) -> Result<SecretKey, Error> {
        Ok(SecretKey::from_slice(&self.seed[..32])?)
    }

    /// Derive Nostr keys from wallet seed for NpubCash authentication
    ///
    /// Uses NIP-06 derivation (`m/44'/1237'/0'/0/0`) from the wallet seed.
    ///
    /// # Errors
    ///
    /// Returns an error if the key derivation fails
    fn derive_npubcash_keys(&self) -> Result<nostr_sdk::Keys, Error> {
        let secret_key = self.derive_npubcash_secret_key()?;

        let nostr_secret = nostr_sdk::SecretKey::from_slice(&secret_key.to_secret_bytes())
            .map_err(|e| Error::Custom(format!("Failed to derive Nostr keys: {}", e)))?;

        Ok(nostr_sdk::Keys::new(nostr_secret))
    }

    fn derive_legacy_npubcash_keys(&self) -> Result<nostr_sdk::Keys, Error> {
        let secret_key = self.derive_legacy_npubcash_secret_key()?;
        let nostr_secret = nostr_sdk::SecretKey::from_slice(&secret_key.to_secret_bytes())
            .map_err(|e| Error::Custom(format!("Failed to derive legacy Nostr keys: {}", e)))?;

        Ok(nostr_sdk::Keys::new(nostr_secret))
    }

    /// Get the Nostr keys used for NpubCash authentication
    ///
    /// Returns the derived Nostr keys from the wallet seed.
    /// These keys are used for authenticating with the NpubCash service.
    ///
    /// # Errors
    ///
    /// Returns an error if the key derivation fails
    pub fn get_npubcash_keys(&self) -> Result<nostr_sdk::Keys, Error> {
        self.derive_npubcash_keys()
    }

    /// Helper to get NpubCash client reference
    ///
    /// # Errors
    ///
    /// Returns an error if NpubCash is not enabled
    async fn get_npubcash_client(&self) -> Result<Arc<NpubCashClient>, Error> {
        self.npubcash_client
            .read()
            .await
            .clone()
            .ok_or_else(|| Error::Custom("NpubCash not enabled".to_string()))
    }

    /// Helper to process npubcash quotes and add them to the wallet
    ///
    /// # Errors
    ///
    /// Returns an error if adding quotes fails
    async fn process_npubcash_quotes(&self, quotes: Vec<Quote>) -> Result<Vec<MintQuote>, Error> {
        self.process_npubcash_quotes_with_key(quotes, NpubCashQuoteKey::Nip06)
            .await
    }

    async fn process_npubcash_quotes_with_key(
        &self,
        quotes: Vec<Quote>,
        key: NpubCashQuoteKey,
    ) -> Result<Vec<MintQuote>, Error> {
        let mut mint_quotes = Vec::with_capacity(quotes.len());
        for quote in quotes {
            if let Some(mint_quote) = self.add_npubcash_mint_quote_with_key(quote, key).await? {
                mint_quotes.push(mint_quote);
            }
        }
        Ok(mint_quotes)
    }

    /// Sync quotes from NpubCash and add them to the wallet
    ///
    /// This method fetches quotes from the last stored fetch timestamp and updates
    /// the timestamp after successful fetch. If no timestamp is stored, it fetches
    /// all quotes.
    ///
    /// # Errors
    ///
    /// Returns an error if NpubCash is not enabled or the sync fails
    #[instrument(skip(self))]
    pub async fn sync_npubcash_quotes(&self) -> Result<Vec<MintQuote>, Error> {
        let client = self.get_npubcash_client().await?;

        // Get the last fetch timestamp from KV store
        let since = self.get_last_npubcash_fetch_timestamp().await?;

        let quotes = client
            .get_quotes(since)
            .await
            .map_err(|e| Error::Custom(format!("Failed to sync quotes: {}", e)))?;

        // Update the last fetch timestamp to the max created_at from fetched quotes
        if let Some(max_ts) = quotes.iter().map(|q| q.created_at).max() {
            self.set_last_npubcash_fetch_timestamp(max_ts).await?;
        }

        self.process_npubcash_quotes(quotes).await
    }

    /// Sync quotes from NpubCash since a specific timestamp and add them to the wallet
    ///
    /// # Arguments
    ///
    /// * `since` - Unix timestamp to fetch quotes from
    ///
    /// # Errors
    ///
    /// Returns an error if NpubCash is not enabled or the sync fails
    #[instrument(skip(self))]
    pub async fn sync_npubcash_quotes_since(&self, since: u64) -> Result<Vec<MintQuote>, Error> {
        let client = self.get_npubcash_client().await?;
        let quotes = client
            .get_quotes(Some(since))
            .await
            .map_err(|e| Error::Custom(format!("Failed to sync quotes: {}", e)))?;
        self.process_npubcash_quotes(quotes).await
    }

    /// Reconcile the wallet with NpubCash by resolving quotes missing locally
    ///
    /// Fetches all quote IDs from NpubCash, determines which ones are not in
    /// the local quote store, and resolves their full data via the server's
    /// missing-quotes endpoint. If the server does not support that endpoint
    /// yet, the data from the full quote list is used instead.
    ///
    /// Quotes known locally are re-processed too, so their NpubCash lock
    /// provenance (and therefore whether they get a NUT-20 quote signature)
    /// tracks the server's current state — e.g. quotes that were synced while
    /// unlocked must lose their marker so mints that reject signatures on
    /// unlocked quotes can be claimed.
    ///
    /// Unlike [`Self::sync_npubcash_quotes`], this does not rely on the last
    /// fetch timestamp and therefore recovers quotes that incremental syncs
    /// may have missed.
    ///
    /// # Errors
    ///
    /// Returns an error if NpubCash is not enabled or the sync fails
    #[instrument(skip(self))]
    pub async fn sync_missing_npubcash_quotes(&self) -> Result<Vec<MintQuote>, Error> {
        self.sync_missing_npubcash_quotes_with_ids()
            .await
            .map(|(quotes, _)| quotes)
    }

    /// Like [`Self::sync_missing_npubcash_quotes`], additionally returning the
    /// IDs of all quotes currently listed server-side on the NpubCash account.
    async fn sync_missing_npubcash_quotes_with_ids(
        &self,
    ) -> Result<(Vec<MintQuote>, HashSet<String>), Error> {
        let client = self.get_npubcash_client().await?;

        let remote_quotes = client
            .get_quotes(None)
            .await
            .map_err(|e| Error::Custom(format!("Failed to fetch NpubCash quote list: {}", e)))?;

        let remote_ids: HashSet<String> =
            remote_quotes.iter().map(|quote| quote.id.clone()).collect();

        let known_ids: HashSet<String> = self
            .localstore
            .get_mint_quotes()
            .await?
            .into_iter()
            .map(|quote| quote.id)
            .collect();

        let missing_ids: Vec<String> = remote_quotes
            .iter()
            .filter(|quote| !known_ids.contains(&quote.id))
            .map(|quote| quote.id.clone())
            .collect();

        if missing_ids.is_empty() {
            // Nothing new to resolve, but refresh lock provenance for the
            // quotes we already know about.
            self.process_npubcash_quotes(remote_quotes).await?;
            return Ok((Vec::new(), remote_ids));
        }

        tracing::info!("Resolving {} missing NpubCash quotes", missing_ids.len());

        let missing_quotes = match client.get_missing_quotes(&missing_ids).await {
            Ok(quotes) => quotes,
            Err(err) => {
                // Older servers may not expose the missing-quotes endpoint;
                // fall back to the data already present in the quote list.
                tracing::warn!(
                    "Failed to resolve missing NpubCash quotes ({}); falling back to quote list data",
                    err
                );
                remote_quotes
                    .clone()
                    .into_iter()
                    .filter(|quote| missing_ids.contains(&quote.id))
                    .collect()
            }
        };

        // Refresh provenance for known quotes from the full list before
        // resolving the missing ones.
        self.process_npubcash_quotes(
            remote_quotes
                .into_iter()
                .filter(|quote| !missing_ids.contains(&quote.id))
                .collect(),
        )
        .await?;

        self.process_npubcash_quotes(missing_quotes)
            .await
            .map(|quotes| (quotes, remote_ids))
    }

    /// Claim all pending NpubCash quotes
    ///
    /// Performs an incremental quote sync and a missing-quote reconciliation,
    /// then mints every paid NpubCash quote that has not been issued yet.
    /// Only quotes attributable to the wallet's NpubCash accounts (the
    /// server-side quote list plus quotes carrying an NpubCash provenance
    /// marker, which covers locked quotes imported from the legacy identity)
    /// are claimed; unrelated mint quotes created through normal wallet flows
    /// are left untouched. Mints that advertise NUT-29 are claimed with batch
    /// minting automatically; other mints fall back to individual minting.
    ///
    /// Returns the total amount minted across all claimed quotes.
    ///
    /// # Errors
    ///
    /// Returns an error if NpubCash is not enabled or the sync fails
    #[instrument(skip(self))]
    pub async fn claim_npubcash_quotes(&self) -> Result<Amount, Error> {
        let npubcash_quote_ids = self.collect_npubcash_quote_ids().await?;
        let unissued_quotes = self.get_unissued_mint_quotes().await?;
        let npubcash_quotes = unissued_quotes
            .into_iter()
            .filter(|quote| npubcash_quote_ids.contains(&quote.id))
            .collect();
        self.mint_given_unissued_quotes(npubcash_quotes).await
    }

    /// Collect the IDs of the quotes attributable to the wallet's NpubCash
    /// accounts.
    ///
    /// Performs an incremental quote sync and a missing-quote reconciliation,
    /// returning the union of:
    /// - the IDs of all quotes currently listed server-side, and
    /// - the IDs of locally stored quotes carrying an NpubCash provenance
    ///   marker, which covers locked quotes previously imported from the
    ///   legacy seed-prefix identity (they are not listed under the current
    ///   identity) as well as quotes pruned from the server-side list.
    async fn collect_npubcash_quote_ids(&self) -> Result<HashSet<String>, Error> {
        let synced_quotes = self.sync_npubcash_quotes().await?;
        let (_, remote_ids) = self.sync_missing_npubcash_quotes_with_ids().await?;

        let mut npubcash_quote_ids: HashSet<String> =
            synced_quotes.into_iter().map(|quote| quote.id).collect();
        npubcash_quote_ids.extend(remote_ids);

        for quote in self.localstore.get_mint_quotes().await? {
            if self.npubcash_quote_key(&quote.id).await?.is_some() {
                npubcash_quote_ids.insert(quote.id);
            }
        }

        Ok(npubcash_quote_ids)
    }

    /// Create a stream that continuously polls NpubCash and yields proofs as payments arrive
    ///
    /// # Arguments
    ///
    /// * `split_target` - How to split the minted proofs
    /// * `spending_conditions` - Optional spending conditions for the minted proofs
    /// * `poll_interval` - How often to check for new quotes
    pub fn npubcash_proof_stream(
        &self,
        split_target: cdk_common::amount::SplitTarget,
        spending_conditions: Option<crate::nuts::SpendingConditions>,
        poll_interval: std::time::Duration,
    ) -> crate::wallet::streams::npubcash::WalletNpubCashProofStream {
        crate::wallet::streams::npubcash::WalletNpubCashProofStream::new(
            self.clone(),
            poll_interval,
            split_target,
            spending_conditions,
        )
    }

    /// Set the mint URL in NpubCash settings
    ///
    /// # Arguments
    ///
    /// * `mint_url` - The mint URL to set
    ///
    /// # Errors
    ///
    /// Returns an error if NpubCash is not enabled or the update fails
    #[instrument(skip(self, mint_url))]
    pub async fn set_npubcash_mint_url(
        &self,
        mint_url: impl Into<String>,
    ) -> Result<cdk_nostr::npubcash::UserResponse, Error> {
        let client = self.get_npubcash_client().await?;
        client
            .set_mint_url(mint_url)
            .await
            .map_err(|e| Error::Custom(e.to_string()))
    }

    /// Fetch the wallet's NpubCash account settings
    ///
    /// Returns the configured mint URL and whether quote locking is enabled.
    ///
    /// # Errors
    ///
    /// Returns an error if NpubCash is not enabled or the request fails
    #[instrument(skip(self))]
    pub async fn get_npubcash_user_info(&self) -> Result<cdk_nostr::npubcash::UserResponse, Error> {
        let client = self.get_npubcash_client().await?;
        client
            .get_user_info()
            .await
            .map_err(|e| Error::Custom(e.to_string()))
    }

    /// Add an NpubCash quote to the wallet's mint quote database
    ///
    /// Converts an NpubCash quote to a wallet MintQuote and stores it. The
    /// NUT-20 signing key is not persisted; the quote is marked in the KV
    /// store so the NpubCash key can be re-derived from the seed at claim
    /// time.
    ///
    /// # Arguments
    ///
    /// * `npubcash_quote` - The NpubCash quote to add
    ///
    /// # Errors
    ///
    /// Returns an error if the conversion fails or the database operation fails
    #[instrument(skip(self))]
    pub async fn add_npubcash_mint_quote(
        &self,
        npubcash_quote: cdk_nostr::npubcash::Quote,
    ) -> Result<Option<MintQuote>, Error> {
        self.add_npubcash_mint_quote_with_key(npubcash_quote, NpubCashQuoteKey::Nip06)
            .await
    }

    async fn add_npubcash_mint_quote_with_key(
        &self,
        npubcash_quote: cdk_nostr::npubcash::Quote,
        key: NpubCashQuoteKey,
    ) -> Result<Option<MintQuote>, Error> {
        // The NpubCash API reports whether this quote is NUT-20-locked.
        // Signing an unlocked quote is rejected by mints with
        // "Signature missing or invalid", so only persisted quotes that
        // are actually locked carry a provenance marker — and only those
        // get a quote signature on mint.
        let quote_locked = npubcash_quote.locked.unwrap_or(true);
        let mint_quote: MintQuote = npubcash_quote.into();

        let stored_quote = if quote_locked {
            // This marker is authoritative because the quote came from the
            // NpubCash account associated with `key`.
            self.localstore
                .kv_write(
                    NPUBCASH_KV_NAMESPACE,
                    QUOTES_KV_SECONDARY_NAMESPACE,
                    &mint_quote.id,
                    key.as_bytes(),
                )
                .await?;

            match key {
                NpubCashQuoteKey::Nip06 => self.localstore.get_mint_quote(&mint_quote.id).await?,
                NpubCashQuoteKey::LegacySeedPrefix => {
                    self.scrub_proven_legacy_npubcash_quote(&mint_quote.id)
                        .await?
                }
            }
        } else {
            // Unlocked npub.cash quote: drop any provenance marker and any
            // previously persisted secret key so mint_quote_signing_key
            // resolves no key and the mint request goes unsigned.
            self.localstore
                .kv_remove(
                    NPUBCASH_KV_NAMESPACE,
                    QUOTES_KV_SECONDARY_NAMESPACE,
                    &mint_quote.id,
                )
                .await?;
            self.scrub_proven_legacy_npubcash_quote(&mint_quote.id)
                .await?
        };

        let exists = self
            .list_transactions(Some(TransactionDirection::Incoming))
            .await?
            .iter()
            .any(|tx| {
                tx.quote_id.as_ref() == Some(&mint_quote.id)
                    && tx.status != TransactionStatus::Failed
            });

        if exists {
            return Ok(None);
        }

        if let Some(stored_quote) = stored_quote {
            let updated_quote = merge_npubcash_quote(mint_quote, stored_quote);
            let quote_id = updated_quote.id.clone();
            self.localstore.add_mint_quote(updated_quote).await?;

            let persisted = self
                .localstore
                .get_mint_quote(&quote_id)
                .await?
                .ok_or(Error::UnknownQuote)?;
            tracing::info!("Updated NpubCash quote {} in wallet database", quote_id);
            return Ok(Some(persisted));
        }

        self.localstore.add_mint_quote(mint_quote.clone()).await?;

        tracing::info!("Added NpubCash quote {} to wallet database", mint_quote.id);
        Ok(Some(mint_quote))
    }

    pub(crate) async fn npubcash_quote_key(
        &self,
        quote_id: &str,
    ) -> Result<Option<NpubCashQuoteKey>, Error> {
        Ok(self
            .localstore
            .kv_read(
                NPUBCASH_KV_NAMESPACE,
                QUOTES_KV_SECONDARY_NAMESPACE,
                quote_id,
            )
            .await?
            .map(|value| NpubCashQuoteKey::from_bytes(&value)))
    }

    fn is_legacy_npubcash_secret_key(&self, secret_key: &SecretKey) -> bool {
        secret_key.as_secret_bytes() == &self.seed[..32]
    }

    pub(crate) fn npubcash_quote_secret_key(
        &self,
        key: NpubCashQuoteKey,
    ) -> Result<SecretKey, Error> {
        match key {
            NpubCashQuoteKey::Nip06 => self.derive_npubcash_secret_key(),
            NpubCashQuoteKey::LegacySeedPrefix => self.derive_legacy_npubcash_secret_key(),
        }
    }

    async fn scrub_proven_legacy_npubcash_quote(
        &self,
        quote_id: &str,
    ) -> Result<Option<MintQuote>, Error> {
        let mut retry_concurrent_update = true;

        loop {
            let Some(mut quote) = self.localstore.get_mint_quote(quote_id).await? else {
                return Ok(None);
            };

            let Some(secret_key) = &quote.secret_key else {
                return Ok(Some(quote));
            };

            if !self.is_legacy_npubcash_secret_key(secret_key) {
                return Ok(Some(quote));
            }

            quote.secret_key = None;
            match self.localstore.add_mint_quote(quote).await {
                Ok(()) => return Ok(self.localstore.get_mint_quote(quote_id).await?),
                Err(database::Error::ConcurrentUpdate) if retry_concurrent_update => {
                    retry_concurrent_update = false;
                }
                Err(error) => return Err(error.into()),
            }
        }
    }

    async fn import_legacy_npubcash_quotes_once(&self, npubcash_url: &str) -> Result<(), Error> {
        if self
            .localstore
            .kv_read(NPUBCASH_KV_NAMESPACE, "", LEGACY_QUOTES_MIGRATED_V2_KEY)
            .await?
            .is_some()
        {
            return Ok(());
        }

        let keys = self.derive_legacy_npubcash_keys()?;
        let auth_provider = Arc::new(JwtAuthProvider::new(npubcash_url.to_string(), keys));
        let client = NpubCashClient::new(npubcash_url.to_string(), auth_provider);
        let quotes = client
            .get_quotes(None)
            .await
            .map_err(|e| Error::Custom(format!("Failed to sync legacy NpubCash quotes: {}", e)))?;

        self.process_npubcash_quotes_with_key(quotes, NpubCashQuoteKey::LegacySeedPrefix)
            .await?;

        self.localstore
            .kv_write(
                NPUBCASH_KV_NAMESPACE,
                "",
                LEGACY_QUOTES_MIGRATED_V2_KEY,
                &[1],
            )
            .await?;

        Ok(())
    }

    /// Get reference to the NpubCash client if enabled
    pub async fn npubcash_client(&self) -> Option<Arc<NpubCashClient>> {
        self.npubcash_client.read().await.clone()
    }

    /// Check if NpubCash is enabled for this wallet
    pub async fn is_npubcash_enabled(&self) -> bool {
        self.npubcash_client.read().await.is_some()
    }

    /// Get the last fetch timestamp from KV store
    ///
    /// Returns the Unix timestamp of the last successful npubcash fetch,
    /// or `None` if no fetch has been recorded yet.
    async fn get_last_npubcash_fetch_timestamp(&self) -> Result<Option<u64>, Error> {
        let value = self
            .localstore
            .kv_read(NPUBCASH_KV_NAMESPACE, "", LAST_FETCH_TIMESTAMP_KEY)
            .await?;

        match value {
            Some(bytes) => {
                let timestamp =
                    u64::from_be_bytes(bytes.try_into().map_err(|_| {
                        Error::Custom("Invalid timestamp format in KV store".into())
                    })?);
                Ok(Some(timestamp))
            }
            None => Ok(None),
        }
    }

    /// Store the last fetch timestamp in KV store
    ///
    /// # Arguments
    ///
    /// * `timestamp` - Unix timestamp of the fetch
    async fn set_last_npubcash_fetch_timestamp(&self, timestamp: u64) -> Result<(), Error> {
        self.localstore
            .kv_write(
                NPUBCASH_KV_NAMESPACE,
                "",
                LAST_FETCH_TIMESTAMP_KEY,
                &timestamp.to_be_bytes(),
            )
            .await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;
    use std::sync::Arc;

    use cdk_common::database::{self, WalletDatabase};

    use super::*;
    use crate::mint_url::MintUrl;
    use crate::nuts::CurrencyUnit;
    use crate::wallet::WalletBuilder;

    async fn build_test_wallet(seed: [u8; 64]) -> Wallet {
        let localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync> = Arc::new(
            cdk_sqlite::wallet::memory::empty()
                .await
                .expect("memory db"),
        );

        WalletBuilder::new()
            .mint_url(MintUrl::from_str("https://mint.example.com").expect("valid mint url"))
            .unit(CurrencyUnit::Sat)
            .localstore(localstore)
            .seed(seed)
            .build()
            .expect("wallet builds")
    }

    fn test_quote() -> Quote {
        Quote {
            id: "npubcash-quote-1".to_string(),
            amount: 1000,
            unit: "sat".to_string(),
            created_at: 0,
            paid_at: None,
            expires_at: None,
            mint_url: Some("https://mint.example.com".to_string()),
            request: Some("lnbc100n1pjz".to_string()),
            state: Some("PAID".to_string()),
            locked: None,
        }
    }

    #[tokio::test]
    async fn npubcash_key_is_nip06_derived_not_raw_seed() {
        let seed = [0x42u8; 64];
        let wallet = build_test_wallet(seed).await;

        let secret_key = wallet.derive_npubcash_secret_key().expect("key derives");

        assert_ne!(
            &secret_key.to_secret_bytes()[..],
            &seed[..32],
            "npubcash key must not equal raw wallet seed bytes"
        );

        let xpriv = Xpriv::new_master(Network::Bitcoin, &seed).expect("master key");
        let path = DerivationPath::from_str("m/44'/1237'/0'/0/0").expect("valid path");
        let expected = xpriv
            .derive_priv(&SECP256K1, &path)
            .expect("derivation")
            .private_key;

        assert_eq!(secret_key.to_secret_bytes(), expected.secret_bytes());
    }

    #[tokio::test]
    async fn add_npubcash_mint_quote_does_not_persist_secret_key() {
        let seed = [0x42u8; 64];
        let wallet = build_test_wallet(seed).await;

        let stored = wallet
            .add_npubcash_mint_quote(test_quote())
            .await
            .expect("add_npubcash_mint_quote succeeds")
            .expect("quote was inserted");

        assert!(
            stored.secret_key.is_none(),
            "npubcash quotes must not carry a persisted secret key"
        );

        let persisted = wallet
            .localstore
            .get_mint_quote(&stored.id)
            .await
            .expect("quote lookup")
            .expect("quote in store");
        assert!(
            persisted.secret_key.is_none(),
            "no secret key may be written to the localstore"
        );

        assert_eq!(
            wallet
                .npubcash_quote_key(&stored.id)
                .await
                .expect("kv lookup"),
            Some(NpubCashQuoteKey::Nip06)
        );

        let signing_key = wallet
            .mint_quote_signing_key(&persisted)
            .await
            .expect("signing key lookup")
            .expect("npubcash quote signing key is re-derivable");

        assert_eq!(
            signing_key.to_secret_bytes(),
            wallet
                .derive_npubcash_secret_key()
                .expect("key derives")
                .to_secret_bytes()
        );
        assert_ne!(&signing_key.to_secret_bytes()[..], &seed[..32]);
    }

    #[tokio::test]
    async fn legacy_npubcash_quote_uses_legacy_key_without_persisting_it() {
        let seed = [0x42u8; 64];
        let wallet = build_test_wallet(seed).await;

        let stored = wallet
            .add_npubcash_mint_quote_with_key(test_quote(), NpubCashQuoteKey::LegacySeedPrefix)
            .await
            .expect("legacy quote is added")
            .expect("quote was inserted");

        assert!(stored.secret_key.is_none());
        assert_eq!(
            wallet
                .npubcash_quote_key(&stored.id)
                .await
                .expect("kv lookup"),
            Some(NpubCashQuoteKey::LegacySeedPrefix)
        );

        let signing_key = wallet
            .mint_quote_signing_key(&stored)
            .await
            .expect("signing key lookup")
            .expect("legacy npubcash signing key is re-derivable");

        assert_eq!(&signing_key.to_secret_bytes()[..], &seed[..32]);
    }

    #[tokio::test]
    async fn external_seed_prefix_key_is_not_claimed_by_npubcash() {
        let seed = [0x42u8; 64];
        let wallet = build_test_wallet(seed).await;
        let mut external_quote: MintQuote = test_quote().into();
        external_quote.secret_key = Some(
            wallet
                .derive_legacy_npubcash_secret_key()
                .expect("legacy key derives"),
        );

        wallet
            .localstore
            .add_mint_quote(external_quote.clone())
            .await
            .expect("external quote is stored");
        let before = wallet
            .localstore
            .get_mint_quote(&external_quote.id)
            .await
            .expect("quote lookup")
            .expect("quote remains stored");

        let signing_key = wallet
            .mint_quote_signing_key(&before)
            .await
            .expect("signing key lookup")
            .expect("external signing key is returned");

        assert_eq!(&signing_key.to_secret_bytes()[..], &seed[..32]);

        let after = wallet
            .localstore
            .get_mint_quote(&external_quote.id)
            .await
            .expect("quote lookup")
            .expect("quote remains stored");
        assert_eq!(after.version, before.version);
        assert!(
            after.secret_key.is_some(),
            "an unmarked external quote must keep its signing key"
        );
        assert_eq!(
            wallet
                .npubcash_quote_key(&external_quote.id)
                .await
                .expect("kv lookup"),
            None
        );
    }

    #[tokio::test]
    async fn proven_legacy_persisted_npubcash_key_is_scrubbed_during_import() {
        let seed = [0x42u8; 64];
        let wallet = build_test_wallet(seed).await;
        let mut legacy_quote: MintQuote = test_quote().into();
        legacy_quote.secret_key = Some(
            wallet
                .derive_legacy_npubcash_secret_key()
                .expect("legacy key derives"),
        );

        wallet
            .localstore
            .add_mint_quote(legacy_quote.clone())
            .await
            .expect("legacy quote is stored");

        let scrubbed = wallet
            .add_npubcash_mint_quote_with_key(test_quote(), NpubCashQuoteKey::LegacySeedPrefix)
            .await
            .expect("legacy quote import succeeds")
            .expect("legacy quote is returned");

        assert!(
            scrubbed.secret_key.is_none(),
            "proven legacy raw seed key should be removed from storage"
        );
        assert!(scrubbed.version > legacy_quote.version);
        assert_eq!(
            wallet
                .npubcash_quote_key(&legacy_quote.id)
                .await
                .expect("kv lookup"),
            Some(NpubCashQuoteKey::LegacySeedPrefix)
        );

        let version_before_lookup = scrubbed.version;
        let signing_key = wallet
            .mint_quote_signing_key(&scrubbed)
            .await
            .expect("signing key lookup")
            .expect("legacy signing key is returned");
        assert_eq!(&signing_key.to_secret_bytes()[..], &seed[..32]);

        let after_lookup = wallet
            .localstore
            .get_mint_quote(&legacy_quote.id)
            .await
            .expect("quote lookup")
            .expect("quote remains stored");
        assert_eq!(after_lookup.version, version_before_lookup);
    }

    #[tokio::test]
    async fn sync_missing_npubcash_quotes_requires_enabled_client() {
        let wallet = build_test_wallet([0x42u8; 64]).await;

        let err = wallet
            .sync_missing_npubcash_quotes()
            .await
            .expect_err("sync must fail when NpubCash is not enabled");

        assert!(matches!(err, Error::Custom(_)));
    }

    #[tokio::test]
    async fn unlocked_npubcash_quote_never_carries_provenance() {
        let seed = [0x42u8; 64];
        let wallet = build_test_wallet(seed).await;

        let mut unlocked_quote = test_quote();
        unlocked_quote.locked = Some(false);

        let stored = wallet
            .add_npubcash_mint_quote(unlocked_quote)
            .await
            .expect("unlocked npubcash quote is added")
            .expect("quote was inserted");

        assert!(
            stored.secret_key.is_none(),
            "unlocked quote must not persist a secret key"
        );
        assert_eq!(
            wallet
                .npubcash_quote_key(&stored.id)
                .await
                .expect("kv lookup"),
            None,
            "unlocked quote must not carry a provenance marker"
        );
        assert!(
            wallet
                .mint_quote_signing_key(&stored)
                .await
                .expect("signing key lookup")
                .is_none(),
            "unlocked quote must resolve no signing key"
        );
    }

    #[tokio::test]
    async fn unlocked_update_scrubs_prior_provenance_and_key() {
        let seed = [0x42u8; 64];
        let wallet = build_test_wallet(seed).await;

        let mut locked_quote = test_quote();
        locked_quote.locked = Some(true);
        let stored = wallet
            .add_npubcash_mint_quote(locked_quote)
            .await
            .expect("locked npubcash quote is added")
            .expect("quote was inserted");
        assert_eq!(
            wallet
                .npubcash_quote_key(&stored.id)
                .await
                .expect("kv lookup"),
            Some(NpubCashQuoteKey::Nip06)
        );

        let mut unlocked_quote = test_quote();
        unlocked_quote.locked = Some(false);
        let stored = wallet
            .add_npubcash_mint_quote(unlocked_quote)
            .await
            .expect("unlocked npubcash quote update is applied")
            .expect("quote was updated");
        assert_eq!(
            wallet
                .npubcash_quote_key(&stored.id)
                .await
                .expect("kv lookup"),
            None
        );
        assert!(wallet
            .mint_quote_signing_key(&stored)
            .await
            .expect("signing key lookup")
            .is_none());
    }

    #[tokio::test]
    async fn claim_npubcash_quotes_requires_enabled_client() {
        let wallet = build_test_wallet([0x42u8; 64]).await;

        let err = wallet
            .claim_npubcash_quotes()
            .await
            .expect_err("claim must fail when NpubCash is not enabled");

        assert!(matches!(err, Error::Custom(_)));
    }

    /// How the mock server answers the quote-locking request.
    enum LockResponse {
        /// 400 — the server rejects locking (e.g. mint without NUT-20)
        Rejected,
        /// 200 with `lockQuote: true`
        Confirmed,
        /// 200 but `lockQuote: false` — locking not actually enabled
        NotConfirmed,
    }

    fn user_body(lock_quote: bool) -> String {
        format!(
            r#"{{"error":false,"data":{{"user":{{"pubkey":"test","mintUrl":"https://mint.example.com","lockQuote":{lock_quote}}}}}}}"#
        )
    }

    /// Minimal NpubCash server: answers the mint/lock settings endpoints and
    /// rejects everything else, so the best-effort legacy import stops at the
    /// JWT request. Accepts connections until none arrive for 500ms.
    async fn start_lock_gate_server(mode: LockResponse) -> (String, tokio::task::JoinHandle<()>) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("test server binds");
        let addr = listener.local_addr().expect("test server has local addr");
        let base_url = format!("http://{}", addr);

        let server = tokio::spawn(async move {
            loop {
                let accept =
                    tokio::time::timeout(std::time::Duration::from_millis(500), listener.accept())
                        .await;
                let Ok(Ok((mut stream, _))) = accept else {
                    break;
                };

                let mut buffer = Vec::new();
                let mut chunk = [0u8; 4096];
                loop {
                    let read = stream.read(&mut chunk).await.expect("request is readable");
                    if read == 0 {
                        break;
                    }
                    buffer.extend_from_slice(&chunk[..read]);
                    if buffer.windows(4).any(|w| w == b"\r\n\r\n") {
                        // The small JSON bodies fit in the first read
                        break;
                    }
                }
                let request = String::from_utf8_lossy(&buffer).to_string();

                let (status, body) = if request.starts_with("PATCH /api/v2/user/lock ") {
                    match &mode {
                        LockResponse::Rejected => {
                            ("HTTP/1.1 400 Bad Request", r#"{"error":true}"#.to_string())
                        }
                        LockResponse::Confirmed => ("HTTP/1.1 200 OK", user_body(true)),
                        LockResponse::NotConfirmed => ("HTTP/1.1 200 OK", user_body(false)),
                    }
                } else if request.starts_with("PATCH /api/v2/user/mint ") {
                    ("HTTP/1.1 200 OK", user_body(true))
                } else {
                    ("HTTP/1.1 400 Bad Request", r#"{"error":true}"#.to_string())
                };

                let response = format!(
                    "{status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                stream
                    .write_all(response.as_bytes())
                    .await
                    .expect("response is written");
            }
        });

        (base_url, server)
    }

    #[tokio::test]
    async fn enable_npubcash_fails_when_quote_locking_is_rejected() {
        let wallet = build_test_wallet([0x42u8; 64]).await;
        let (url, server) = start_lock_gate_server(LockResponse::Rejected).await;

        let err = wallet
            .enable_npubcash(url)
            .await
            .expect_err("enable must fail when the server rejects quote locking");

        assert!(matches!(err, Error::Custom(_)));
        assert!(
            !wallet.is_npubcash_enabled().await,
            "client must not be exposed when locking cannot be established"
        );
        server.await.expect("server completes");
    }

    #[tokio::test]
    async fn enable_npubcash_fails_when_locking_is_not_confirmed() {
        let wallet = build_test_wallet([0x42u8; 64]).await;
        let (url, server) = start_lock_gate_server(LockResponse::NotConfirmed).await;

        let err = wallet
            .enable_npubcash(url)
            .await
            .expect_err("enable must fail when the server does not confirm locking");

        assert!(matches!(err, Error::Custom(_)));
        assert!(!wallet.is_npubcash_enabled().await);
        server.await.expect("server completes");
    }

    #[tokio::test]
    async fn enable_npubcash_publishes_client_once_locking_is_confirmed() {
        let wallet = build_test_wallet([0x42u8; 64]).await;
        let (url, server) = start_lock_gate_server(LockResponse::Confirmed).await;

        wallet
            .enable_npubcash(url)
            .await
            .expect("enable succeeds when locking is confirmed");

        assert!(wallet.is_npubcash_enabled().await);
        server.await.expect("server completes");
    }

    /// Build a paid NpubCash server quote for the wallet's mint.
    fn paid_server_quote(id: &str, amount: u64, locked: Option<bool>, mint_url: &str) -> Quote {
        Quote {
            id: id.to_string(),
            amount,
            unit: "sat".to_string(),
            created_at: 0,
            paid_at: Some(10),
            expires_at: None,
            mint_url: Some(mint_url.to_string()),
            request: Some(format!("lnbc{amount}n1pjz")),
            state: Some("PAID".to_string()),
            locked,
        }
    }

    #[tokio::test]
    async fn upgrade_claims_legacy_locked_and_unlocked_quotes_after_reopen() {
        use bitcoin::secp256k1::schnorr::Signature;

        use crate::wallet::test_utils::{
            create_test_db, create_test_wallet_with_mock_seed, test_mint_info, test_mint_url,
            MockMintConnector,
        };

        let seed = [0x42u8; 64];
        let mint_url = test_mint_url().to_string();

        // --- Pre-migration state, as written by the previous wallet
        // version: the quote carries its persisted raw seed-prefix secret
        // key and no provenance marker.
        let db = create_test_db().await;
        let legacy_server_quote = paid_server_quote("legacy-locked-quote", 1_000, None, &mint_url);
        let mut pre_migration_quote: MintQuote = legacy_server_quote.clone().into();
        pre_migration_quote.secret_key =
            Some(SecretKey::from_slice(&seed[..32]).expect("legacy key is valid"));
        db.add_mint_quote(pre_migration_quote)
            .await
            .expect("pre-migration quote is stored");

        // --- Reopen the wallet on the same database and seed, backed by a
        // signing mock mint that advertises NUT-29 batching.
        let mock_client = Arc::new(MockMintConnector::new());
        mock_client.enable_mint_signing();
        let mut mint_info = test_mint_info();
        mint_info.nuts.nut29 = cdk_common::nut29::Settings::new(Some(100), None);
        mock_client.set_mint_info_response(Ok(mint_info));
        let wallet = create_test_wallet_with_mock_seed(db.clone(), mock_client.clone(), seed).await;

        let stored = db
            .get_mint_quote("legacy-locked-quote")
            .await
            .expect("quote lookup")
            .expect("quote exists");
        assert!(
            stored.secret_key.is_some(),
            "pre-migration quote still carries its persisted key"
        );

        // --- Import phase, as performed on the first enable after the
        // upgrade: re-import the legacy quote with legacy provenance, plus a
        // newly locked quote and an existing unlocked legacy quote.
        wallet
            .add_npubcash_mint_quote_with_key(
                legacy_server_quote,
                NpubCashQuoteKey::LegacySeedPrefix,
            )
            .await
            .expect("legacy import succeeds");
        wallet
            .add_npubcash_mint_quote(paid_server_quote(
                "locked-quote",
                2_000,
                Some(true),
                &mint_url,
            ))
            .await
            .expect("locked import succeeds");
        wallet
            .add_npubcash_mint_quote(paid_server_quote(
                "unlocked-quote",
                4_000,
                Some(false),
                &mint_url,
            ))
            .await
            .expect("unlocked import succeeds");

        let stored = db
            .get_mint_quote("legacy-locked-quote")
            .await
            .expect("quote lookup")
            .expect("quote exists");
        assert!(
            stored.secret_key.is_none(),
            "import must scrub the persisted legacy key"
        );

        // --- Claim all three quotes through the batch path.
        let responses = {
            let mut responses = Vec::new();
            for id in ["legacy-locked-quote", "locked-quote", "unlocked-quote"] {
                let quote = db
                    .get_mint_quote(id)
                    .await
                    .expect("quote lookup")
                    .expect("quote exists");
                let response = cdk_common::MintQuoteResponse::Bolt11(
                    cdk_common::nuts::MintQuoteBolt11Response {
                        quote: quote.id.clone(),
                        request: quote.request.clone(),
                        amount: quote.amount,
                        unit: Some(quote.unit.clone()),
                        method: quote.payment_method.clone(),
                        amount_paid: quote.amount_paid,
                        amount_issued: quote.amount_issued,
                        updated_at: 1,
                        state: crate::nuts::MintQuoteState::Paid,
                        expiry: Some(quote.expiry),
                        pubkey: None,
                    },
                );
                mock_client.set_mint_quote_status_response(id, response.clone());
                responses.push(response);
            }
            responses
        };
        mock_client.push_post_batch_check_mint_quote_status_response(Ok(responses));

        let minted = wallet.mint_unissued_quotes().await.expect("claim succeeds");
        assert_eq!(minted, Amount::from(7_000u64));

        let requests = mock_client.post_batch_mint_requests();
        assert_eq!(requests.len(), 1, "one batch mint request expected");
        let request = &requests[0].1;
        let signatures = request
            .signatures
            .as_ref()
            .expect("locked quotes carry signatures");

        let nip06_pubkey = wallet
            .derive_npubcash_secret_key()
            .expect("nip06 key derives")
            .public_key();
        let legacy_pubkey = SecretKey::from_slice(&seed[..32])
            .expect("legacy key is valid")
            .public_key();

        assert_eq!(request.quotes.len(), 3);
        for (quote_id, signature) in request.quotes.iter().zip(signatures.iter()) {
            match quote_id.as_str() {
                "legacy-locked-quote" => {
                    let signature =
                        Signature::from_str(signature.as_ref().expect("legacy quote signed"))
                            .expect("hex schnorr signature");
                    legacy_pubkey
                        .verify(&request.msg_to_sign(quote_id), &signature)
                        .expect("legacy quote is signed with the legacy key");
                }
                "locked-quote" => {
                    let signature =
                        Signature::from_str(signature.as_ref().expect("locked quote signed"))
                            .expect("hex schnorr signature");
                    nip06_pubkey
                        .verify(&request.msg_to_sign(quote_id), &signature)
                        .expect("locked quote is signed with the NIP-06 key");
                }
                "unlocked-quote" => {
                    assert!(
                        signature.is_none(),
                        "unlocked legacy quote must be claimed unsigned"
                    );
                }
                other => panic!("unexpected quote in batch request: {other}"),
            }
        }
    }

    #[tokio::test]
    async fn claim_npubcash_quotes_leaves_unrelated_unissued_quotes_untouched() {
        use crate::wallet::test_utils::{
            create_test_db, create_test_wallet_with_mock_seed, test_mint_info, test_mint_url,
            MockMintConnector,
        };

        let seed = [0x42u8; 64];
        let mint_url = test_mint_url().to_string();

        let db = create_test_db().await;

        // An unrelated paid quote created through a normal wallet flow: it is
        // unissued and carries no NpubCash provenance, and the mock mint
        // reports it as paid — so an untargeted `mint_unissued_quotes` would
        // mint it.
        let mut unrelated_quote: MintQuote =
            paid_server_quote("unrelated-paid-quote", 2_000, None, &mint_url).into();
        unrelated_quote.state = MintQuoteState::Paid;
        unrelated_quote.amount_paid = Amount::from(2_000u64);
        db.add_mint_quote(unrelated_quote)
            .await
            .expect("unrelated quote is stored");

        let mock_client = Arc::new(MockMintConnector::new());
        mock_client.enable_mint_signing();
        let mut mint_info = test_mint_info();
        mint_info.nuts.nut29 = cdk_common::nut29::Settings::new(Some(100), None);
        mock_client.set_mint_info_response(Ok(mint_info));
        let wallet = create_test_wallet_with_mock_seed(db.clone(), mock_client.clone(), seed).await;

        // Import one paid, locked npub.cash quote, as if it had been listed
        // by the server during sync.
        wallet
            .add_npubcash_mint_quote(paid_server_quote(
                "npubcash-quote",
                1_000,
                Some(true),
                &mint_url,
            ))
            .await
            .expect("npubcash import succeeds");

        // Sanity check: claiming must not hit the sync paths' "NpubCash not
        // enabled" error for reasons unrelated to this test.
        assert!(matches!(
            wallet
                .claim_npubcash_quotes()
                .await
                .expect_err("claim without an enabled client must fail"),
            Error::Custom(_)
        ));

        // Target the npub.cash quote set as `claim_npubcash_quotes` does once
        // sync has returned the server-side quote list.
        let unissued_quotes = wallet
            .get_unissued_mint_quotes()
            .await
            .expect("unissued quotes load");
        assert_eq!(unissued_quotes.len(), 2);
        let npubcash_quotes = unissued_quotes
            .into_iter()
            .filter(|quote| quote.id == "npubcash-quote")
            .collect();

        // Both quotes are paid on the mock mint; only the npub.cash quote may
        // be refreshed and minted. The mint's responses use an updated_at far
        // above the locally stored values, so a refresh is detectable.
        for id in ["npubcash-quote", "unrelated-paid-quote"] {
            let quote = db
                .get_mint_quote(id)
                .await
                .expect("quote lookup")
                .expect("quote exists");
            mock_client.set_mint_quote_status_response(
                id,
                cdk_common::MintQuoteResponse::Bolt11(cdk_common::nuts::MintQuoteBolt11Response {
                    quote: quote.id.clone(),
                    request: quote.request.clone(),
                    amount: quote.amount,
                    unit: Some(quote.unit.clone()),
                    method: quote.payment_method.clone(),
                    amount_paid: quote.amount_paid,
                    amount_issued: quote.amount_issued,
                    updated_at: 100,
                    state: MintQuoteState::Paid,
                    expiry: Some(quote.expiry),
                    pubkey: None,
                }),
            );
        }

        let minted = wallet
            .mint_given_unissued_quotes(npubcash_quotes)
            .await
            .expect("targeted claim succeeds");
        assert_eq!(minted, Amount::from(1_000u64));

        let npubcash_quote = db
            .get_mint_quote("npubcash-quote")
            .await
            .expect("quote lookup")
            .expect("quote exists");
        assert_eq!(npubcash_quote.state, MintQuoteState::Issued);
        assert_eq!(npubcash_quote.amount_issued, Amount::from(1_000u64));

        // The unrelated quote must not have been minted, nor even refreshed:
        // its paid state must come only from local storage, untouched by the
        // mint's status response.
        let unrelated_quote = db
            .get_mint_quote("unrelated-paid-quote")
            .await
            .expect("quote lookup")
            .expect("quote exists");
        assert_eq!(unrelated_quote.state, MintQuoteState::Paid);
        assert_eq!(unrelated_quote.amount_issued, Amount::ZERO);
        assert!(
            unrelated_quote.updated_at < 100,
            "the mint's status response must not have been applied"
        );

        let individual_requests = mock_client.post_mint_requests();
        assert!(
            individual_requests
                .iter()
                .all(|(_, request)| request.quote == "npubcash-quote"),
            "no individual mint request may be issued for the unrelated quote"
        );
        assert!(
            mock_client
                .post_batch_mint_requests()
                .iter()
                .all(|(_, request)| !request.quotes.contains(&"unrelated-paid-quote".to_string())),
            "no batch mint request may include the unrelated quote"
        );

        // The unrelated quote remains claimable through the normal flow.
        let minted = wallet
            .mint_unissued_quotes()
            .await
            .expect("unrelated quote is mintable afterwards");
        assert_eq!(minted, Amount::from(2_000u64));
    }
}