cdk 0.18.2

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
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
//! Issue (Mint) module for the wallet.
//!
//! This module provides functionality for minting new proofs via Bolt11, Bolt12, and Custom methods.

use std::collections::HashMap;

pub(crate) mod saga;

#[cfg(test)]
mod status_tests;

use cdk_common::nut00::KnownMethod;
use cdk_common::nut04::MintMethodOptions;
use cdk_common::{MintQuoteRequest, MintQuoteResponse, PaymentMethod};
pub(crate) use saga::MintSaga;
use tracing::instrument;

use crate::amount::SplitTarget;
use crate::nuts::{BatchCheckMintQuoteRequest, Proofs, SecretKey, SpendingConditions};
use crate::util::unix_time;
use crate::wallet::recovery::RecoveryAction;
use crate::wallet::{DerivationCounterNamespace, MintQuote, MintQuoteState};
use crate::{Amount, Error, Wallet};

/// Keep automatic batches bounded when a mint advertises NUT-29 without a
/// `max_batch_size`.
const DEFAULT_BATCH_SIZE: usize = 100;

fn automatic_batch_size(
    settings: &cdk_common::nut29::Settings,
    payment_method: &PaymentMethod,
) -> Option<usize> {
    if settings.is_empty() {
        return None;
    }

    if let Some(methods) = &settings.methods {
        if !methods
            .iter()
            .any(|method| method == payment_method.as_str())
        {
            return None;
        }
    }

    let max_batch_size = settings
        .max_batch_size
        .and_then(|size| usize::try_from(size).ok())
        .unwrap_or(DEFAULT_BATCH_SIZE);

    (max_batch_size >= 2).then_some(max_batch_size)
}

fn validate_mint_quote_response_id(
    quote_id: &str,
    response: &MintQuoteResponse<String>,
) -> Result<(), Error> {
    if response.quote() != quote_id {
        return Err(Error::InvalidMintResponse(format!(
            "Quote ID mismatch: expected {quote_id}, received {}",
            response.quote()
        )));
    }
    Ok(())
}

pub(crate) fn apply_mint_quote_response(
    quote: &mut MintQuote,
    response: &MintQuoteResponse<String>,
) -> bool {
    match response {
        MintQuoteResponse::Bolt11(response) => {
            let state =
                if response.amount_paid > Amount::ZERO || response.amount_issued > Amount::ZERO {
                    match cdk_common::mint_quote::quote_state_from_amounts(
                        response.amount_paid,
                        response.amount_issued,
                    ) {
                        Ok(state) => state,
                        Err(err) => {
                            tracing::debug!("Ignoring invalid mint quote accounting: {}", err);
                            return false;
                        }
                    }
                } else {
                    response.state
                };
            let (amount_paid, amount_issued) = match state {
                MintQuoteState::Paid => {
                    let amount_paid = if response.amount_paid > Amount::ZERO {
                        response.amount_paid
                    } else {
                        response.amount.unwrap_or_default()
                    };
                    (amount_paid, response.amount_issued)
                }
                MintQuoteState::Issued => {
                    let amount = response.amount.unwrap_or_default();
                    let amount_paid = if response.amount_paid > Amount::ZERO {
                        response.amount_paid
                    } else {
                        amount
                    };
                    let amount_issued = if response.amount_issued > Amount::ZERO {
                        response.amount_issued
                    } else {
                        amount
                    };
                    (amount_paid, amount_issued)
                }
                MintQuoteState::Unpaid => (response.amount_paid, response.amount_issued),
            };

            if is_stale_mint_quote_update(quote, response.updated_at, amount_paid, amount_issued) {
                return false;
            }

            quote.state = state;
            quote.amount_paid = amount_paid;
            quote.amount_issued = amount_issued;
            quote.updated_at = quote.updated_at.max(response.updated_at);
            true
        }
        MintQuoteResponse::Bolt12(response) => apply_accounting_mint_quote_update(
            quote,
            response.amount_paid,
            response.amount_issued,
            response.updated_at,
        ),
        MintQuoteResponse::Onchain(response) => apply_accounting_mint_quote_update(
            quote,
            response.amount_paid,
            response.amount_issued,
            response.updated_at,
        ),
        MintQuoteResponse::Custom { response, .. } => apply_accounting_mint_quote_update(
            quote,
            response.amount_paid,
            response.amount_issued,
            response.updated_at,
        ),
    }
}

pub(crate) fn apply_accounting_mint_quote_update(
    quote: &mut MintQuote,
    amount_paid: Amount,
    amount_issued: Amount,
    updated_at: u64,
) -> bool {
    if amount_issued > amount_paid {
        tracing::debug!(
            "Ignoring invalid mint quote accounting: amount_issued {} exceeds amount_paid {}",
            amount_issued,
            amount_paid
        );
        return false;
    }

    if is_stale_mint_quote_update(quote, updated_at, amount_paid, amount_issued) {
        return false;
    }

    quote.amount_paid = amount_paid;
    quote.amount_issued = amount_issued;
    quote.updated_at = quote.updated_at.max(updated_at);
    quote.update_state_from_amounts();
    true
}

fn is_stale_mint_quote_update(
    quote: &MintQuote,
    updated_at: u64,
    amount_paid: Amount,
    amount_issued: Amount,
) -> bool {
    updated_at < quote.updated_at
        || amount_paid < quote.amount_paid
        || amount_issued < quote.amount_issued
}

fn local_mint_quote_amount(method: &PaymentMethod, amount: Option<Amount>) -> Option<Amount> {
    match method {
        PaymentMethod::Known(KnownMethod::Onchain) => None,
        _ => amount,
    }
}

fn mint_quote_response_amount(response: &MintQuoteResponse<String>) -> Option<Amount> {
    match response {
        MintQuoteResponse::Bolt11(r) => r.amount,
        MintQuoteResponse::Bolt12(r) => r.amount,
        MintQuoteResponse::Custom { response: r, .. } => r.amount,
        MintQuoteResponse::Onchain(_) => None,
    }
}

impl Wallet {
    async fn next_mint_quote_signing_key(&self) -> Result<SecretKey, Error> {
        let counter = self
            .reserve_derivation_index(DerivationCounterNamespace::Nut20Quote, 0)
            .await?;

        Ok(crate::nuts::nut20::derive_quote_locking_key(
            &self.seed, counter,
        )?)
    }

    /// Resolve the NUT-20 signing key for a mint quote
    ///
    /// Re-derives the key for explicitly marked NpubCash quotes. For all other
    /// quotes, returns the stored key without modifying wallet state.
    pub(crate) async fn mint_quote_signing_key(
        &self,
        quote: &MintQuote,
    ) -> Result<Option<SecretKey>, Error> {
        #[cfg(feature = "npubcash")]
        if let Some(key) = self.npubcash_quote_key(&quote.id).await? {
            return Ok(Some(self.npubcash_quote_secret_key(key)?));
        }

        Ok(quote.secret_key.clone())
    }

    /// Create a mint quote for the given payment method and amount
    #[instrument(skip(self, method, extra))]
    pub async fn mint_quote(
        &self,
        method: PaymentMethod,
        amount: Option<Amount>,
        description: Option<String>,
        extra: Option<String>,
    ) -> Result<MintQuote, Error> {
        let quote = self
            .request_mint_quote(method, amount, description, extra)
            .await?;

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

        Ok(quote)
    }

    /// Request a mint quote without persisting it to the wallet database.
    pub(crate) async fn request_mint_quote(
        &self,
        method: PaymentMethod,
        amount: Option<Amount>,
        description: Option<String>,
        extra: Option<String>,
    ) -> Result<MintQuote, Error> {
        let mint_info = self.load_mint_info().await?;
        let mint_url = self.mint_url.clone();
        let unit = self.unit.clone();

        // Check settings and description support
        if description.is_some() {
            let settings = mint_info
                .nuts
                .nut04
                .get_settings(&unit, &method)
                .ok_or(Error::UnsupportedUnit)?;

            let description_supported = match (&method, settings.options) {
                (
                    PaymentMethod::Known(KnownMethod::Bolt11),
                    Some(MintMethodOptions::Bolt11 { description }),
                )
                | (
                    PaymentMethod::Known(KnownMethod::Bolt12),
                    Some(MintMethodOptions::Bolt12 { description }),
                ) => description,
                _ => false,
            };

            if !description_supported {
                return Err(Error::InvoiceDescriptionUnsupported);
            }
        }

        self.keysets(Default::default()).await?;

        let secret_key = self.next_mint_quote_signing_key().await?;

        let request = match &method {
            PaymentMethod::Known(KnownMethod::Bolt11) => {
                let amount = amount.ok_or(Error::AmountUndefined)?;
                MintQuoteRequest::Bolt11(cdk_common::nut23::MintQuoteBolt11Request {
                    amount,
                    unit: unit.clone(),
                    description,
                    pubkey: Some(secret_key.public_key()),
                })
            }
            PaymentMethod::Known(KnownMethod::Bolt12) => {
                MintQuoteRequest::Bolt12(cdk_common::nut25::MintQuoteBolt12Request {
                    amount,
                    unit: unit.clone(),
                    description,
                    pubkey: secret_key.public_key(),
                })
            }
            PaymentMethod::Custom(_) => {
                let amount = amount.ok_or(Error::AmountUndefined)?;
                MintQuoteRequest::Custom {
                    method: method.clone(),
                    request: cdk_common::nuts::MintQuoteCustomRequest {
                        amount: Some(amount),
                        unit: unit.clone(),
                        description,
                        pubkey: Some(secret_key.public_key()),
                        extra: serde_json::from_str(extra.as_deref().unwrap_or("{}"))?,
                    },
                }
            }
            PaymentMethod::Known(KnownMethod::Onchain) => {
                MintQuoteRequest::Onchain(cdk_common::nuts::nut30::MintQuoteOnchainRequest {
                    unit: unit.clone(),
                    pubkey: secret_key.public_key(),
                })
            }
        };

        let response: MintQuoteResponse<String> = self.client.post_mint_quote(request).await?;
        let quote_id = response.quote().to_string();
        let request_str = response.request().to_string();
        let expiry = response.expiry();

        let mut quote = MintQuote::new(
            quote_id,
            mint_url,
            method.clone(),
            local_mint_quote_amount(&method, amount),
            unit,
            request_str,
            expiry.unwrap_or(0),
            Some(secret_key),
        );
        apply_mint_quote_response(&mut quote, &response);

        Ok(quote)
    }

    /// Checks the state of a mint quote with the mint
    async fn check_state(&self, mint_quote: &mut MintQuote) -> Result<(), Error> {
        let mint_quote_response: MintQuoteResponse<String> = self
            .client
            .get_mint_quote_status(mint_quote.payment_method.clone(), &mint_quote.id)
            .await?;
        validate_mint_quote_response_id(&mint_quote.id, &mint_quote_response)?;
        apply_mint_quote_response(mint_quote, &mint_quote_response);

        Ok(())
    }

    /// This method:
    /// 1. Fetches the current quote state from the mint
    /// 2. If there's an in-progress saga for this quote, attempts to complete it
    /// 3. Persists the current accounting without overwriting recovery changes
    /// 4. Returns the persisted quote
    #[instrument(skip_all)]
    async fn inner_check_mint_quote_status(
        &self,
        mut mint_quote: MintQuote,
    ) -> Result<MintQuote, Error> {
        let quote_id = mint_quote.id.clone();
        // Validate the response before recovery can change local state. Apply it
        // below to the latest snapshot so recovery accounting is not overwritten.
        let response = self
            .client
            .get_mint_quote_status(mint_quote.payment_method.clone(), &quote_id)
            .await?;
        validate_mint_quote_response_id(&quote_id, &response)?;

        // Check if there's an in-progress saga for this quote
        if let Some(ref operation_id_str) = mint_quote.used_by_operation {
            if let Ok(operation_id) = uuid::Uuid::parse_str(operation_id_str) {
                match self.localstore.get_saga(&operation_id).await {
                    Ok(Some(saga)) => {
                        // Saga exists - try to complete it (like recovery does)
                        tracing::info!(
                            "Mint quote {} has in-progress saga {}, attempting to complete",
                            quote_id,
                            operation_id
                        );

                        let recovery_action = self.resume_issue_saga(&saga).await?;

                        // Compensation makes the quote available for a later mint.
                        if recovery_action == RecoveryAction::Compensated {
                            tracing::info!(
                                "Saga {} was compensated for quote {}",
                                operation_id,
                                quote_id
                            );
                        }
                    }
                    Ok(None) => {
                        // Orphaned reservation - release it
                        tracing::warn!(
                            "Mint quote {} has orphaned reservation for operation {}, releasing",
                            quote_id,
                            operation_id
                        );
                        if let Err(e) = self.localstore.release_mint_quote(&operation_id).await {
                            tracing::warn!("Failed to release orphaned mint quote: {}", e);
                        }
                    }
                    Err(e) => {
                        tracing::warn!("Failed to check saga for mint quote {}: {}", quote_id, e);
                        return Err(Error::Database(e));
                    }
                }
                // Recovery and reservation release may change accounting, version,
                // or ownership. Never write the pre-recovery snapshot back.
                mint_quote = self
                    .localstore
                    .get_mint_quote(&quote_id)
                    .await?
                    .ok_or(Error::UnknownQuote)?;
            }
        }

        apply_mint_quote_response(&mut mint_quote, &response);
        self.localstore.add_mint_quote(mint_quote).await?;
        self.localstore
            .get_mint_quote(&quote_id)
            .await?
            .ok_or(Error::UnknownQuote)
    }

    /// Check the status of a single mint quote from the mint.
    ///
    /// Calls `GET /v1/mint/quote/{method}/{quote_id}` per NUT-04.
    /// Updates local store with current state from mint.
    /// Returns the persisted quote, including its database version and ownership.
    /// Rejects a mismatched response quote ID before changing local state.
    /// If there was a crashed mid-mint (pending saga), attempts to complete it.
    /// Does NOT mint tokens directly - use mint() for that.
    ///
    /// **Note:** The mint quote must be known to the wallet (stored locally) for this
    /// function to work. If the quote is not stored locally, use `fetch_mint_quote`
    /// instead.
    #[instrument(skip(self, quote_id))]
    pub async fn check_mint_quote_status(&self, quote_id: &str) -> Result<MintQuote, Error> {
        let mint_quote = self
            .localstore
            .get_mint_quote(quote_id)
            .await?
            .ok_or(Error::UnknownQuote)?;

        let mint_quote = self.inner_check_mint_quote_status(mint_quote).await?;

        Ok(mint_quote)
    }

    /// Check a mint quote status (alias for `check_mint_quote_status`)
    #[instrument(skip(self, quote_id))]
    pub async fn check_mint_quote(&self, quote_id: &str) -> Result<MintQuote, Error> {
        self.check_mint_quote_status(quote_id).await
    }

    /// Check all unissued mint quote states from the mint.
    ///
    /// Calls `GET /v1/mint/quote/{method}/{quote_id}` per NUT-04 for each quote.
    /// Updates local store with current state from mint for each quote.
    /// If there was a crashed mid-mint (pending saga), attempts to complete it.
    /// Does NOT mint tokens directly - use mint() or mint_unissued_quotes() for that.
    #[instrument(skip(self))]
    pub async fn check_all_mint_quotes(&self) -> Result<Vec<MintQuote>, Error> {
        let mint_quotes = self.localstore.get_unissued_mint_quotes().await?;
        let mut updated_quotes = Vec::new();

        for mint_quote in mint_quotes {
            if mint_quote.mint_url != self.mint_url || mint_quote.unit != self.unit {
                continue;
            }

            match self.inner_check_mint_quote_status(mint_quote).await {
                Ok(q) => updated_quotes.push(q),
                Err(err) => {
                    tracing::warn!("Could not check quote state: {}", err);
                    continue;
                }
            }
        }
        Ok(updated_quotes)
    }

    /// Refresh states and mint all unissued quotes that have mintable amounts.
    /// Uses NUT-29 batch quote checks and batch minting automatically when the
    /// mint advertises support for the quotes' payment method.
    /// Returns the total amount minted across all quotes.
    ///
    /// # Privacy
    ///
    /// This method retrieves all unissued mint quotes from the local store and
    /// checks their state with the mint. This has a negative privacy effect of
    /// linking all these quotes to a single wallet session.
    #[instrument(skip(self))]
    pub async fn mint_unissued_quotes(&self) -> Result<Amount, Error> {
        let mint_quotes = self.get_unissued_mint_quotes().await?;
        self.mint_given_unissued_quotes(mint_quotes).await
    }

    /// Mint the mintable quotes among a pre-filtered set of unissued quotes.
    ///
    /// Refreshes each quote's state with the mint and mints whatever is
    /// mintable, using NUT-29 batch quote checks and batch minting when the
    /// mint advertises support for the quotes' payment method. Returns the
    /// total amount minted across the given quotes.
    ///
    /// The caller is responsible for the selection of quotes; this is used by
    /// flows that must only touch a known subset of quotes (e.g. claiming
    /// NpubCash quotes without sweeping unrelated deposits).
    #[instrument(skip(self, mint_quotes))]
    pub(crate) async fn mint_given_unissued_quotes(
        &self,
        mint_quotes: Vec<MintQuote>,
    ) -> Result<Amount, Error> {
        let mut total_amount = Amount::ZERO;
        let batch_settings = self
            .load_mint_info()
            .await
            .map(|info| info.nuts.nut29)
            .inspect_err(|err| {
                tracing::warn!(
                    "Could not load mint info for automatic batch minting; using individual requests: {}",
                    err
                );
            })
            .ok();
        let mut batch_groups: HashMap<PaymentMethod, Vec<MintQuote>> = HashMap::new();

        for mint_quote in mint_quotes {
            // A reservation indicates an interrupted operation. Keep it on the
            // individual path so inner_check_mint_quote_status can resume its
            // existing saga rather than placing the quote in a new batch.
            let batch_size = batch_settings
                .as_ref()
                .and_then(|settings| automatic_batch_size(settings, &mint_quote.payment_method));
            if mint_quote.used_by_operation.is_none() && batch_size.is_some() {
                batch_groups
                    .entry(mint_quote.payment_method.clone())
                    .or_default()
                    .push(mint_quote);
            } else {
                total_amount = total_amount
                    .checked_add(self.refresh_and_mint_quote(mint_quote).await?)
                    .ok_or(Error::AmountOverflow)?;
            }
        }

        for (payment_method, quotes) in batch_groups {
            let batch_size = batch_settings
                .as_ref()
                .and_then(|settings| automatic_batch_size(settings, &payment_method))
                .unwrap_or(1);

            for chunk in quotes.chunks(batch_size) {
                if chunk.len() < 2 {
                    total_amount = total_amount
                        .checked_add(self.refresh_and_mint_quote(chunk[0].clone()).await?)
                        .ok_or(Error::AmountOverflow)?;
                    continue;
                }

                let quote_ids = chunk
                    .iter()
                    .map(|quote| quote.id.as_str())
                    .collect::<Vec<_>>();
                let refreshed = match self.batch_check_mint_quote_status(&quote_ids).await {
                    Ok(quotes) => quotes,
                    Err(err) => {
                        // Status checks are read-only, so falling back to
                        // individual requests is safe.
                        tracing::warn!(
                            "Could not batch check {} mint quotes: {}; using individual requests",
                            chunk.len(),
                            err
                        );
                        for quote in chunk {
                            total_amount = total_amount
                                .checked_add(self.refresh_and_mint_quote(quote.clone()).await?)
                                .ok_or(Error::AmountOverflow)?;
                        }
                        continue;
                    }
                };

                let mintable = refreshed
                    .into_iter()
                    .filter(|quote| quote.amount_mintable() > Amount::ZERO)
                    .collect::<Vec<_>>();

                if mintable.len() < 2 {
                    for quote in mintable {
                        total_amount = total_amount
                            .checked_add(self.mint_refreshed_quote(quote).await?)
                            .ok_or(Error::AmountOverflow)?;
                    }
                    continue;
                }

                let previous_amounts = mintable
                    .iter()
                    .map(|quote| (quote.id.clone(), quote.amount_issued))
                    .collect::<HashMap<_, _>>();
                let mintable_ids = mintable
                    .iter()
                    .map(|quote| quote.id.as_str())
                    .collect::<Vec<_>>();

                if let Err(err) = self
                    .batch_mint(&mintable_ids, SplitTarget::default(), None, None)
                    .await
                {
                    if matches!(err, Error::BatchSizeExceeded { .. }) {
                        // The mint rejected the request while validating it,
                        // so nothing was written — e.g. it enforces a smaller
                        // batch limit than its NUT-29 settings advertise.
                        // Retrying as individual mint requests is safe.
                        tracing::warn!(
                            "Batch mint of {} quotes rejected ({}); using individual requests",
                            mintable.len(),
                            err
                        );
                        for quote in mintable {
                            total_amount = total_amount
                                .checked_add(self.mint_refreshed_quote(quote).await?)
                                .ok_or(Error::AmountOverflow)?;
                        }
                        continue;
                    }

                    // Do not retry an ambiguous write as individual mint
                    // requests. The persisted batch saga owns recovery.
                    tracing::warn!("Could not batch mint quotes: {}", err);
                    continue;
                }

                for quote in mintable {
                    let Some(updated_quote) = self.localstore.get_mint_quote(&quote.id).await?
                    else {
                        continue;
                    };
                    let previous = previous_amounts.get(&quote.id).copied().unwrap_or_default();
                    total_amount = total_amount
                        .checked_add(
                            updated_quote
                                .amount_issued
                                .checked_sub(previous)
                                .unwrap_or_default(),
                        )
                        .ok_or(Error::AmountOverflow)?;
                }
            }
        }

        Ok(total_amount)
    }

    async fn refresh_and_mint_quote(&self, mint_quote: MintQuote) -> Result<Amount, Error> {
        let mint_quote = match self.inner_check_mint_quote_status(mint_quote).await {
            Ok(quote) => quote,
            Err(err) => {
                tracing::warn!("Could not check quote state: {}", err);
                return Ok(Amount::ZERO);
            }
        };

        self.mint_refreshed_quote(mint_quote).await
    }

    async fn mint_refreshed_quote(&self, mint_quote: MintQuote) -> Result<Amount, Error> {
        let current_amount_issued = mint_quote.amount_issued;

        if mint_quote.amount_mintable() > Amount::ZERO {
            if let Err(err) = self
                .mint(&mint_quote.id, SplitTarget::default(), None)
                .await
            {
                tracing::warn!("Could not mint quote {}: {}", mint_quote.id, err);
                return Ok(Amount::ZERO);
            }
        }

        let Some(updated_quote) = self.localstore.get_mint_quote(&mint_quote.id).await? else {
            return Ok(Amount::ZERO);
        };

        Ok(updated_quote
            .amount_issued
            .checked_sub(current_amount_issued)
            .unwrap_or_default())
    }

    /// Get active mint quotes
    /// Returns mint quotes that are not expired and not yet issued.
    #[instrument(skip(self))]
    pub async fn get_active_mint_quotes(&self) -> Result<Vec<MintQuote>, Error> {
        let mut mint_quotes = self.localstore.get_mint_quotes().await?;
        let unix_time = unix_time();
        mint_quotes.retain(|quote| {
            quote.mint_url == self.mint_url
                && quote.unit == self.unit
                && quote.state != MintQuoteState::Issued
                && quote.expiry > unix_time
        });
        Ok(mint_quotes)
    }

    /// Get unissued mint quotes
    /// Returns bolt11 quotes where nothing has been issued yet (amount_issued = 0) and all bolt12 quotes.
    /// Includes unpaid bolt11 quotes to allow checking with the mint if they've been paid (wallet state may be outdated).
    /// Filters out quotes from other mints and units. Does not filter by expiry time to allow
    /// checking with the mint if expired quotes can still be minted.
    #[instrument(skip(self))]
    pub async fn get_unissued_mint_quotes(&self) -> Result<Vec<MintQuote>, Error> {
        let mut pending_quotes = self.localstore.get_unissued_mint_quotes().await?;
        pending_quotes.retain(|quote| quote.mint_url == self.mint_url && quote.unit == self.unit);
        Ok(pending_quotes)
    }

    /// Mint
    #[instrument(skip(self))]
    pub async fn mint(
        &self,
        quote_id: &str,
        amount_split_target: SplitTarget,
        spending_conditions: Option<SpendingConditions>,
    ) -> Result<Proofs, Error> {
        self.retry_on_inactive_keyset(|| async {
            let saga = MintSaga::new(self);
            let saga = saga
                .prepare(
                    quote_id,
                    amount_split_target.clone(),
                    spending_conditions.clone(),
                )
                .await?;
            let saga = saga.execute().await?;
            Ok(saga.into_proofs())
        })
        .await
    }

    /// Mint tokens for a quote (alias for `mint`)
    #[instrument(skip(self))]
    pub async fn mint_unified(
        &self,
        quote_id: &str,
        amount_split_target: SplitTarget,
        spending_conditions: Option<SpendingConditions>,
    ) -> Result<Proofs, Error> {
        self.mint(quote_id, amount_split_target, spending_conditions)
            .await
    }

    /// Fetch a mint quote from the mint and store it locally
    ///
    /// This method contacts the mint to get the current state of a quote,
    /// creates or updates the quote in local storage, and returns the stored quote.
    ///
    /// Works with all payment methods (Bolt11, Bolt12, and custom payment methods).
    ///
    /// A quote not created by this wallet instance, such as one fetched after
    /// restoring from seed, is stored without its NUT-20 signing key. Use
    /// [`Self::fetch_mint_quote_with_key_search`] to recover that key.
    ///
    /// # Arguments
    /// * `quote_id` - The ID of the quote to fetch
    /// * `payment_method` - The payment method for the quote. Required if the quote
    ///   is not already stored locally. If the quote exists locally, the stored
    ///   payment method will be used and this parameter is ignored.
    ///
    /// # Errors
    /// Returns `Error::PaymentMethodRequired` if the quote is not found locally
    /// and no payment method is provided.
    /// Returns `Error::InvalidMintResponse` if the response quote ID does not match.
    #[instrument(skip(self, quote_id))]
    pub async fn fetch_mint_quote(
        &self,
        quote_id: &str,
        payment_method: Option<PaymentMethod>,
    ) -> Result<MintQuote, Error> {
        self.fetch_mint_quote_with_key_search(quote_id, payment_method, 0)
            .await
    }

    /// Fetch a mint quote and try to recover its NUT-20 signing key from the seed.
    ///
    /// Use this after restoring a wallet from seed to claim a quote whose ID is
    /// known but whose signing key was lost with the old database. Plain
    /// [`Self::fetch_mint_quote`] never searches.
    ///
    /// The mint reports the public key the quote is locked to. This method derives
    /// the wallet's NUT-20 keys at counters `0..key_search_limit` (capped at the
    /// BIP32 non-hardened index boundary) and stores the first one that matches.
    /// On a match, the wallet's NUT-20 counter is advanced past that index so new
    /// quotes never reuse it.
    ///
    /// Returns `Ok` even if no key matched. Check `quote.secret_key.is_some()` on
    /// the result: if set, call [`Self::mint`]; if not, retry with a larger limit.
    /// The quote stays stored either way.
    ///
    /// The search is skipped when the quote already has a key, is not locked, is
    /// an NpubCash quote (its key comes from the NpubCash identity), or
    /// `key_search_limit` is zero. Keys that were generated randomly rather than
    /// derived from the seed cannot be recovered.
    ///
    /// See `crates/cdk/examples/restore-mint-quote.rs` for a complete example.
    ///
    /// # Arguments
    /// * `quote_id` - The ID of the quote to recover
    /// * `payment_method` - As for [`Self::fetch_mint_quote`]
    /// * `key_search_limit` - Exclusive upper bound on counters to try. It must
    ///   exceed the index the original wallet used for this quote, which is below
    ///   the number of locked quotes it created. Each key costs a BIP32 derivation.
    ///
    /// # Errors
    /// Same as [`Self::fetch_mint_quote`], plus key derivation or database errors.
    #[instrument(skip_all)]
    pub async fn fetch_mint_quote_with_key_search(
        &self,
        quote_id: &str,
        payment_method: Option<PaymentMethod>,
        key_search_limit: u32,
    ) -> Result<MintQuote, Error> {
        // Check if we already have this quote stored locally
        let existing_quote = self.localstore.get_mint_quote(quote_id).await?;

        // Determine the payment method to use
        let method = match (&existing_quote, &payment_method) {
            (Some(q), _) => q.payment_method.clone(),
            (None, Some(m)) => m.clone(),
            (None, None) => return Err(Error::PaymentMethodRequired),
        };

        // Fetch the quote status from the mint using unified method
        let response: MintQuoteResponse<String> = self
            .client
            .get_mint_quote_status(method.clone(), quote_id)
            .await?;
        validate_mint_quote_response_id(quote_id, &response)?;

        let mut quote = match existing_quote {
            Some(mut existing) => {
                apply_mint_quote_response(&mut existing, &response);
                existing
            }
            None => {
                // Create a new quote from the response
                let amount = mint_quote_response_amount(&response);
                let unit = match &response {
                    MintQuoteResponse::Bolt11(r) => r.unit.clone(),
                    MintQuoteResponse::Bolt12(r) => Some(r.unit.clone()),
                    MintQuoteResponse::Custom { response: r, .. } => r.unit.clone(),
                    MintQuoteResponse::Onchain(r) => Some(r.unit.clone()),
                };
                let mut quote = MintQuote::new(
                    quote_id.to_string(),
                    self.mint_url.clone(),
                    method,
                    amount,
                    unit.unwrap_or(self.unit.clone()),
                    response.request().to_string(),
                    response.expiry().unwrap_or(0),
                    None,
                );
                apply_mint_quote_response(&mut quote, &response);
                quote
            }
        };

        #[cfg(feature = "npubcash")]
        let key_search_limit = match self.npubcash_quote_key(quote_id).await? {
            Some(_) => 0,
            None => key_search_limit,
        };

        if quote.secret_key.is_none() && key_search_limit > 0 {
            let pubkey = match &response {
                MintQuoteResponse::Bolt11(r) => r.pubkey,
                MintQuoteResponse::Bolt12(r) => Some(r.pubkey),
                MintQuoteResponse::Onchain(r) => Some(r.pubkey),
                MintQuoteResponse::Custom { response: r, .. } => r.pubkey,
            };
            if let Some(pubkey) = pubkey {
                let counters = 0..key_search_limit.min(1 << 31);
                let keys =
                    crate::nuts::nut20::derive_quote_locking_keys(&self.seed, counters.clone())?;
                for (counter, key) in counters.zip(keys) {
                    let key = key?;
                    if key.public_key() == pubkey {
                        let namespace = DerivationCounterNamespace::Nut20Quote.as_str();
                        let current = self
                            .localstore
                            .increment_derivation_counter(namespace, 0)
                            .await?;
                        self.localstore
                            .increment_derivation_counter(
                                namespace,
                                (counter + 1).saturating_sub(current),
                            )
                            .await?;
                        quote.secret_key = Some(key);
                        break;
                    }
                    // Keep long recovery scans cooperative, including on WASM.
                    if counter % 100 == 99 {
                        tokio::task::yield_now().await;
                    }
                }
                if quote.secret_key.is_none() {
                    tracing::warn!(key_search_limit, "Quote signing key not recovered; try a larger key search limit or restore the original key backup");
                }
            }
        }

        // Return the authoritative version assigned by the database.
        self.localstore.add_mint_quote(quote).await?;
        self.localstore
            .get_mint_quote(quote_id)
            .await?
            .ok_or(Error::UnknownQuote)
    }

    /// Batch check status of multiple mint quotes from the mint.
    ///
    /// Calls `POST /v1/mint/quote/{method}/check` per NUT-29.
    /// All quotes must share the same payment method.
    /// Updates local store with current state from mint for each quote.
    /// Rejects mismatched response counts or quote IDs before updating any quote.
    #[instrument(skip(self, quote_ids))]
    pub async fn batch_check_mint_quote_status(
        &self,
        quote_ids: &[&str],
    ) -> Result<Vec<MintQuote>, Error> {
        if quote_ids.is_empty() {
            return Err(Error::UnknownQuote);
        }

        // Load all quotes and determine payment method
        let mut quotes: Vec<MintQuote> = Vec::new();
        for quote_id in quote_ids {
            let quote = self
                .localstore
                .get_mint_quote(quote_id)
                .await?
                .ok_or(Error::UnknownQuote)?;
            quotes.push(quote);
        }

        // All quotes must share the same payment method
        let payment_method = quotes[0].payment_method.clone();
        for quote in &quotes {
            if quote.payment_method != payment_method {
                return Err(Error::InvalidPaymentMethod);
            }
        }

        // Call batch check endpoint
        let request = BatchCheckMintQuoteRequest {
            quotes: quote_ids.iter().map(|s| s.to_string()).collect(),
        };

        let responses = self
            .client
            .post_batch_check_mint_quote_status(&payment_method, request)
            .await?;

        // NUT-29 requires one response per requested quote, in request order.
        // Validate the entire batch before writing any local updates.
        if responses.len() != quote_ids.len() {
            return Err(Error::InvalidMintResponse(format!(
                "Quote response count mismatch: expected {}, received {}",
                quote_ids.len(),
                responses.len()
            )));
        }
        for (quote_id, response) in quote_ids.iter().zip(&responses) {
            validate_mint_quote_response_id(quote_id, response)?;
        }

        // Update local quotes with response data
        for (quote, response) in quotes.iter_mut().zip(responses.iter()) {
            apply_mint_quote_response(quote, response);
            self.localstore.add_mint_quote(quote.clone()).await?;
            *quote = self
                .localstore
                .get_mint_quote(&quote.id)
                .await?
                .ok_or(Error::UnknownQuote)?;
        }

        Ok(quotes)
    }

    /// Mint tokens for multiple quotes in a single batch operation.
    ///
    /// Calls `POST /v1/mint/{method}/batch` per NUT-29.
    /// All quotes must share the same payment method and unit.
    /// Uses the saga pattern for crash recovery.
    ///
    /// # Arguments
    /// * `quote_ids` - Array of unique quote IDs to mint
    /// * `amount_split_target` - How to split the minted amount into proofs
    /// * `spending_conditions` - Optional conditions to attach to the proofs
    /// * `external_keys` - Optional signing keys for quotes not in local store
    #[instrument(skip(self, quote_ids, spending_conditions, external_keys))]
    pub async fn batch_mint(
        &self,
        quote_ids: &[&str],
        amount_split_target: SplitTarget,
        spending_conditions: Option<SpendingConditions>,
        external_keys: Option<std::collections::HashMap<String, SecretKey>>,
    ) -> Result<Proofs, Error> {
        // Create saga and prepare batch
        let saga = MintSaga::new(self);

        let prepared = saga
            .prepare_batch(
                quote_ids,
                amount_split_target,
                spending_conditions,
                external_keys.as_ref(),
            )
            .await?;

        // Execute the mint
        let finalized = prepared.execute().await?;

        Ok(finalized.into_proofs())
    }
}

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

    use bip39::Mnemonic;
    use cdk_common::mint_url::MintUrl;
    use cdk_common::nuts::CurrencyUnit;

    use super::*;

    #[tokio::test]
    async fn quote_status_returns_persisted_onchain_quote() {
        use crate::wallet::test_utils::{
            create_test_db, create_test_wallet_with_mock, test_mint_quote, test_mint_url,
            MockMintConnector,
        };

        let db = create_test_db().await;
        let client = Arc::new(MockMintConnector::new());
        let wallet = create_test_wallet_with_mock(db.clone(), client.clone()).await;
        let mut quote = test_mint_quote(test_mint_url());
        quote.payment_method = PaymentMethod::Known(KnownMethod::Onchain);
        quote.amount = None;
        db.add_mint_quote(quote.clone()).await.unwrap();
        client.set_mint_quote_status_response(
            &quote.id,
            MintQuoteResponse::Onchain(cdk_common::nuts::nut30::MintQuoteOnchainResponse {
                quote: quote.id.clone(),
                request: quote.request.clone(),
                unit: quote.unit.clone(),
                method: quote.payment_method.clone(),
                expiry: Some(quote.expiry),
                pubkey: SecretKey::generate().public_key(),
                amount_paid: Amount::from(1_000),
                amount_issued: Amount::ZERO,
                updated_at: 1,
            }),
        );

        // All entry points must return the current SQLite version, including
        // repeated checks with an unchanged mint response.
        for expected_version in 1..=4 {
            let returned = match expected_version {
                1 => wallet.check_mint_quote_status(&quote.id).await.unwrap(),
                2 => wallet.check_mint_quote(&quote.id).await.unwrap(),
                3 => wallet.check_all_mint_quotes().await.unwrap().remove(0),
                _ => wallet.fetch_mint_quote(&quote.id, None).await.unwrap(),
            };
            let stored = db.get_mint_quote(&quote.id).await.unwrap().unwrap();
            assert_eq!(stored.version, expected_version);
            assert_eq!(returned, stored);
            assert_eq!(returned.amount_paid, Amount::from(1_000));
            assert_eq!(returned.amount_issued, Amount::ZERO);
            assert_eq!(returned.state, MintQuoteState::Paid);
            assert_eq!(returned.used_by_operation, None);
        }
    }

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

        let seed = [42; 64];
        let key = crate::nuts::nut20::derive_quote_locking_key(&seed, 3).unwrap();
        let db = create_test_db().await;
        let client = Arc::new(MockMintConnector::new());
        client.enable_mint_signing();
        let wallet = create_test_wallet_with_mock_seed(db.clone(), client.clone(), seed).await;
        client.set_mint_quote_status_response(
            "lost-quote",
            MintQuoteResponse::Onchain(cdk_common::nuts::nut30::MintQuoteOnchainResponse {
                quote: "lost-quote".to_string(),
                request: "onchain-address".to_string(),
                unit: CurrencyUnit::Sat,
                method: PaymentMethod::Known(KnownMethod::Onchain),
                expiry: None,
                pubkey: key.public_key(),
                amount_paid: Amount::from(250_366),
                amount_issued: Amount::ZERO,
                updated_at: 1,
            }),
        );

        // The upper bound is exclusive; a failed search can be retried on the
        // now-local quote without losing its current payment state.
        let quote = wallet
            .fetch_mint_quote_with_key_search(
                "lost-quote",
                Some(PaymentMethod::Known(KnownMethod::Onchain)),
                3,
            )
            .await
            .unwrap();
        assert!(quote.secret_key.is_none());
        assert_eq!(
            db.increment_derivation_counter("nut20_quote", 0)
                .await
                .unwrap(),
            0
        );
        let quote = wallet
            .fetch_mint_quote_with_key_search("lost-quote", None, 4)
            .await
            .unwrap();
        assert_eq!(quote.secret_key, Some(key.clone()));
        assert_eq!(quote.amount_paid, Amount::from(250_366));
        assert_eq!(quote.amount_issued, Amount::ZERO);
        assert_eq!(quote.state, MintQuoteState::Paid);
        assert_eq!(quote.amount, None);
        assert_eq!(db.get_mint_quote("lost-quote").await.unwrap(), Some(quote));
        let next_key = wallet.next_mint_quote_signing_key().await.unwrap();
        assert_eq!(
            next_key,
            crate::nuts::nut20::derive_quote_locking_key(&seed, 4).unwrap()
        );

        // Existing keys survive even with recovery disabled, and fetching does
        // not consume another derivation index.
        let quote = wallet
            .fetch_mint_quote_with_key_search("lost-quote", None, 0)
            .await
            .unwrap();
        assert_eq!(quote.secret_key, Some(key));
        assert_eq!(
            db.increment_derivation_counter("nut20_quote", 0)
                .await
                .unwrap(),
            5
        );

        // Claiming uses the recovered key to sign the mint request.
        use crate::nuts::nut00::ProofsMethods;
        let proofs = wallet
            .mint("lost-quote", SplitTarget::default(), None)
            .await
            .unwrap();
        assert_eq!(proofs.total_amount().unwrap(), Amount::from(250_366));
        let requests = client.post_mint_requests();
        assert_eq!(requests.len(), 1);
        requests[0]
            .1
            .verify_signature(
                crate::nuts::nut20::derive_quote_locking_key(&seed, 3)
                    .unwrap()
                    .public_key(),
            )
            .unwrap();
    }

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

        let seed = [42; 64];
        let db = create_test_db().await;
        let client = Arc::new(MockMintConnector::new());
        let wallet = create_test_wallet_with_mock_seed(db.clone(), client.clone(), seed).await;
        let key = crate::nuts::nut20::derive_quote_locking_key(&seed, 0).unwrap();
        let unrelated_key = crate::nuts::nut20::derive_quote_locking_key(&[43; 64], 0).unwrap();
        // A higher existing counter must never be rewound by recovery.
        db.increment_derivation_counter("nut20_quote", 10)
            .await
            .unwrap();
        for (id, pubkey, expected_key, limit) in [
            ("unlocked", None, None, 1),
            ("unrelated", Some(unrelated_key.public_key()), None, 1),
            ("disabled", Some(key.public_key()), None, 0),
            ("recover", Some(key.public_key()), Some(key.clone()), 1),
            (
                "preserve",
                Some(unrelated_key.public_key()),
                Some(unrelated_key.clone()),
                0,
            ),
        ] {
            let mut quote = test_mint_quote(test_mint_url());
            quote.id = id.to_string();
            quote.secret_key = None;
            if id == "preserve" {
                quote.secret_key = Some(unrelated_key.clone());
                db.add_mint_quote(quote.clone()).await.unwrap();
            }
            let mut response = paid_bolt11_quote_response(&quote);
            if let MintQuoteResponse::Bolt11(r) = &mut response {
                r.pubkey = pubkey;
            }
            client.set_mint_quote_status_response(id, response);
            let fetched = wallet
                .fetch_mint_quote_with_key_search(id, Some(PaymentMethod::BOLT11), limit)
                .await
                .unwrap();
            assert_eq!(fetched.secret_key, expected_key);
            assert_eq!(db.get_mint_quote(id).await.unwrap(), Some(fetched));
            assert_eq!(
                db.increment_derivation_counter("nut20_quote", 0)
                    .await
                    .unwrap(),
                10
            );
        }

        // Plain fetches never search, for new or already stored quotes.
        let mut quote = test_mint_quote(test_mint_url());
        quote.id = "plain".to_string();
        let mut response = paid_bolt11_quote_response(&quote);
        if let MintQuoteResponse::Bolt11(r) = &mut response {
            r.pubkey = Some(key.public_key());
        }
        client.set_mint_quote_status_response("plain", response);
        for id in ["plain", "disabled"] {
            let fetched = wallet
                .fetch_mint_quote(id, Some(PaymentMethod::BOLT11))
                .await
                .unwrap();
            assert_eq!(fetched.secret_key, None);
        }
        assert_eq!(
            db.increment_derivation_counter("nut20_quote", 0)
                .await
                .unwrap(),
            10
        );
    }

    #[tokio::test]
    async fn mint_quote_signing_keys_follow_nut20_counter_across_wallet_instances() {
        let mnemonic = Mnemonic::from_str(
            "half depart obvious quality work element tank gorilla view sugar picture humble",
        )
        .expect("valid mnemonic");
        let seed = mnemonic.to_seed_normalized("");
        let db = crate::wallet::test_utils::create_test_db().await;
        let wallet = Wallet::new(
            "https://mint.example.com",
            CurrencyUnit::Sat,
            db.clone(),
            seed,
            None,
        )
        .expect("wallet should build");

        let first = wallet
            .next_mint_quote_signing_key()
            .await
            .expect("first key should derive");
        let second = wallet
            .next_mint_quote_signing_key()
            .await
            .expect("second key should derive");

        let restarted_wallet = Wallet::new(
            "https://mint.example.com",
            CurrencyUnit::Sat,
            db,
            seed,
            None,
        )
        .expect("wallet should rebuild");
        let third = restarted_wallet
            .next_mint_quote_signing_key()
            .await
            .expect("third key should derive");

        assert_eq!(
            first.public_key().to_hex(),
            "03062837166e56114b59a4d1fd3a5a812bf7aadc1dde758428cf943d80acd41539"
        );
        assert_eq!(
            second.public_key().to_hex(),
            "02b47d9d41725f5ce6f08c874835cef25376cb1e95f6cb073fef52ca8fd986cf15"
        );
        assert_eq!(
            third.public_key().to_hex(),
            "029acbd3a46fd75bc05ba0226d0b4d909b2fb6e96c80544a094a1a3567737e44d3"
        );
    }

    #[test]
    fn automatic_batching_honors_nut29_method_and_limit() {
        let settings = cdk_common::nut29::Settings::new(Some(25), Some(vec!["bolt11".to_string()]));

        assert_eq!(
            automatic_batch_size(&settings, &PaymentMethod::BOLT11),
            Some(25)
        );
        assert_eq!(
            automatic_batch_size(&settings, &PaymentMethod::BOLT12),
            None
        );
    }

    #[test]
    fn automatic_batching_uses_bounded_default() {
        let settings = cdk_common::nut29::Settings::new(None, Some(vec!["bolt11".to_string()]));

        assert_eq!(
            automatic_batch_size(&settings, &PaymentMethod::BOLT11),
            Some(DEFAULT_BATCH_SIZE)
        );
    }

    #[test]
    fn automatic_batching_rejects_absent_or_single_quote_batches() {
        assert_eq!(
            automatic_batch_size(
                &cdk_common::nut29::Settings::default(),
                &PaymentMethod::BOLT11
            ),
            None
        );
        assert_eq!(
            automatic_batch_size(
                &cdk_common::nut29::Settings::new(Some(1), None),
                &PaymentMethod::BOLT11
            ),
            None
        );
    }

    #[test]
    fn local_onchain_mint_quote_amount_is_not_stored() {
        let amount = Some(Amount::from(1_000));

        assert_eq!(
            local_mint_quote_amount(&PaymentMethod::Known(KnownMethod::Onchain), amount),
            None
        );
    }

    #[test]
    fn fetched_onchain_mint_quote_does_not_use_amount_paid_as_amount() {
        let response =
            MintQuoteResponse::Onchain(cdk_common::nuts::nut30::MintQuoteOnchainResponse {
                quote: "quote-id".to_string(),
                request: "bc1qexample".to_string(),
                unit: CurrencyUnit::Sat,
                method: PaymentMethod::Known(KnownMethod::Onchain),
                expiry: Some(1_700_000_000),
                pubkey: SecretKey::generate().public_key(),
                amount_paid: Amount::from(1_000),
                amount_issued: Amount::from(250),
                updated_at: 0,
            });

        assert_eq!(mint_quote_response_amount(&response), None);
    }

    #[test]
    fn stale_mint_quote_response_does_not_decrease_accounting() {
        let mut quote = MintQuote::new(
            "quote-id".to_string(),
            MintUrl::from_str("https://mint.example.com").expect("valid mint url"),
            PaymentMethod::Custom("custom".to_string()),
            Some(Amount::from(200)),
            CurrencyUnit::Sat,
            "custom-request".to_string(),
            1_700_000_000,
            None,
        );
        quote.amount_paid = Amount::from(100);
        quote.amount_issued = Amount::from(20);
        quote.updated_at = 10;
        quote.update_state_from_amounts();

        let stale_response = custom_mint_quote_response(Amount::from(200), Amount::from(20), 9);
        assert!(!apply_mint_quote_response(&mut quote, &stale_response));

        assert_eq!(quote.amount_paid, Amount::from(100));
        assert_eq!(quote.amount_issued, Amount::from(20));
        assert_eq!(quote.updated_at, 10);

        let decreasing_response =
            custom_mint_quote_response(Amount::from(90), Amount::from(20), 11);
        assert!(!apply_mint_quote_response(&mut quote, &decreasing_response));

        assert_eq!(quote.amount_paid, Amount::from(100));
        assert_eq!(quote.amount_issued, Amount::from(20));
        assert_eq!(quote.updated_at, 10);

        let fresh_response = custom_mint_quote_response(Amount::from(150), Amount::from(30), 12);
        assert!(apply_mint_quote_response(&mut quote, &fresh_response));

        assert_eq!(quote.amount_paid, Amount::from(150));
        assert_eq!(quote.amount_issued, Amount::from(30));
        assert_eq!(quote.updated_at, 12);
    }

    #[test]
    fn invalid_mint_quote_response_does_not_apply_accounting() {
        let mut quote = MintQuote::new(
            "quote-id".to_string(),
            MintUrl::from_str("https://mint.example.com").expect("valid mint url"),
            PaymentMethod::Custom("custom".to_string()),
            Some(Amount::from(200)),
            CurrencyUnit::Sat,
            "custom-request".to_string(),
            1_700_000_000,
            None,
        );
        quote.amount_paid = Amount::from(100);
        quote.amount_issued = Amount::from(20);
        quote.updated_at = 10;
        quote.update_state_from_amounts();

        let invalid_response = custom_mint_quote_response(Amount::from(120), Amount::from(150), 11);
        assert!(!apply_mint_quote_response(&mut quote, &invalid_response));

        assert_eq!(quote.amount_paid, Amount::from(100));
        assert_eq!(quote.amount_issued, Amount::from(20));
        assert_eq!(quote.updated_at, 10);
        assert_eq!(quote.state, MintQuoteState::Paid);
    }

    fn custom_mint_quote_response(
        amount_paid: Amount,
        amount_issued: Amount,
        updated_at: u64,
    ) -> MintQuoteResponse<String> {
        MintQuoteResponse::Custom {
            method: PaymentMethod::Custom("custom".to_string()),
            response: cdk_common::nut04::MintQuoteCustomResponse {
                quote: "quote-id".to_string(),
                request: "custom-request".to_string(),
                method: PaymentMethod::Custom("custom".to_string()),
                amount: Some(Amount::from(200)),
                amount_paid,
                amount_issued,
                updated_at,
                unit: Some(CurrencyUnit::Sat),
                expiry: Some(1_700_000_000),
                pubkey: None,
                extra: serde_json::Value::Null,
            },
        }
    }

    fn paid_bolt11_quote_response(quote: &MintQuote) -> MintQuoteResponse<String> {
        MintQuoteResponse::Bolt11(crate::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.unwrap_or_default(),
            amount_issued: Amount::ZERO,
            updated_at: 1,
            state: crate::nuts::MintQuoteState::Paid,
            expiry: Some(quote.expiry),
            pubkey: None,
        })
    }

    /// Stage a wallet whose mock mint advertises NUT-29 batching and holds
    /// `quote_count` paid, unissued bolt11 quotes.
    async fn batch_claim_wallet(
        quote_count: usize,
    ) -> (
        Wallet,
        Arc<crate::wallet::test_utils::MockMintConnector>,
        Vec<MintQuote>,
    ) {
        use crate::wallet::test_utils::{
            create_test_db, create_test_wallet_with_mock, test_mint_quote, MockMintConnector,
        };

        let db = create_test_db().await;
        let mock_client = Arc::new(MockMintConnector::new());
        let mut mint_info = crate::wallet::test_utils::test_mint_info();
        mint_info.nuts.nut29 = cdk_common::nut29::Settings::new(Some(100), None);
        mock_client.set_active_keyset(crate::wallet::test_utils::test_keyset());
        mock_client.set_mint_info_response(Ok(mint_info));
        let wallet = create_test_wallet_with_mock(db.clone(), mock_client.clone()).await;

        let mut quotes = Vec::new();
        for _ in 0..quote_count {
            let mut quote = test_mint_quote(wallet.mint_url.clone());
            quote.state = crate::nuts::MintQuoteState::Paid;
            quote.amount_paid = quote.amount.unwrap_or_default();
            db.add_mint_quote(quote.clone())
                .await
                .expect("add mint quote");
            quotes.push(quote);
        }

        (wallet, mock_client, quotes)
    }

    #[tokio::test]
    async fn batch_quote_status_rejects_inconsistent_responses_without_updates() {
        // Include a valid first response in several cases to verify that the
        // entire batch is validated before any quote is persisted.
        for indices in [
            vec![],
            vec![0],
            vec![0, 1, 2],
            vec![1, 0],
            vec![0, 0],
            vec![0, 2],
        ] {
            let (wallet, mock_client, quotes) = batch_claim_wallet(3).await;
            let responses = indices
                .iter()
                .map(|&index| issued_bolt11_quote_response(&quotes[index]))
                .collect();
            mock_client.push_post_batch_check_mint_quote_status_response(Ok(responses));

            let result = wallet
                .batch_check_mint_quote_status(&[&quotes[0].id, &quotes[1].id])
                .await;

            assert!(matches!(result, Err(Error::InvalidMintResponse(_))));
            for quote in &quotes {
                assert_eq!(
                    wallet.localstore.get_mint_quote(&quote.id).await.unwrap(),
                    Some(quote.clone()),
                    "invalid batch {indices:?} must leave all quotes unchanged"
                );
            }
        }
    }

    #[tokio::test]
    async fn batch_quote_status_applies_matching_responses() {
        let (wallet, mock_client, quotes) = batch_claim_wallet(2).await;
        mock_client.push_post_batch_check_mint_quote_status_response(Ok(vec![
            issued_bolt11_quote_response(&quotes[0]),
            paid_bolt11_quote_response(&quotes[1]),
        ]));

        let refreshed = wallet
            .batch_check_mint_quote_status(&[&quotes[0].id, &quotes[1].id])
            .await
            .unwrap();

        assert_eq!(refreshed.len(), 2);
        assert_eq!(refreshed[0].state, MintQuoteState::Issued);
        assert_eq!(refreshed[0].amount_issued, quotes[0].amount_paid);
        assert_eq!(refreshed[1].state, MintQuoteState::Paid);
        assert_eq!(refreshed[1].amount_issued, Amount::ZERO);
        for (original, refreshed) in quotes.iter().zip(refreshed) {
            assert_eq!(refreshed.id, original.id);
            let stored = wallet
                .localstore
                .get_mint_quote(&original.id)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(stored.state, refreshed.state);
            assert_eq!(stored.amount_paid, refreshed.amount_paid);
            assert_eq!(stored.amount_issued, refreshed.amount_issued);
            assert_eq!(stored.updated_at, refreshed.updated_at);
            assert_eq!(stored, refreshed);
        }
    }

    #[tokio::test]
    async fn single_quote_status_rejects_mismatched_id_without_updates() {
        let (wallet, mock_client, quotes) = batch_claim_wallet(2).await;
        mock_client.set_mint_quote_status_response(
            &quotes[0].id,
            issued_bolt11_quote_response(&quotes[1]),
        );

        let result = wallet.check_mint_quote_status(&quotes[0].id).await;
        assert!(matches!(result, Err(Error::InvalidMintResponse(_))));
        for quote in &quotes {
            assert_eq!(
                wallet.localstore.get_mint_quote(&quote.id).await.unwrap(),
                Some(quote.clone())
            );
        }

        mock_client.set_mint_quote_status_response(
            &quotes[0].id,
            issued_bolt11_quote_response(&quotes[0]),
        );
        let refreshed = wallet.check_mint_quote_status(&quotes[0].id).await.unwrap();
        assert_eq!(refreshed.state, MintQuoteState::Issued);
        assert_eq!(refreshed.amount_issued, quotes[0].amount_paid);
    }

    #[tokio::test]
    async fn fetch_quote_rejects_mismatched_id_without_storing_response() {
        let (wallet, mock_client, quotes) = batch_claim_wallet(2).await;
        for quote_id in [quotes[0].id.as_str(), "unknown-quote"] {
            mock_client
                .set_mint_quote_status_response(quote_id, issued_bolt11_quote_response(&quotes[1]));
            let result = wallet
                .fetch_mint_quote(quote_id, Some(PaymentMethod::BOLT11))
                .await;
            assert!(matches!(result, Err(Error::InvalidMintResponse(_))));
        }

        for quote in &quotes {
            assert_eq!(
                wallet.localstore.get_mint_quote(&quote.id).await.unwrap(),
                Some(quote.clone())
            );
        }
        assert!(wallet
            .localstore
            .get_mint_quote("unknown-quote")
            .await
            .unwrap()
            .is_none());
    }

    fn issued_bolt11_quote_response(quote: &MintQuote) -> MintQuoteResponse<String> {
        let mut response = paid_bolt11_quote_response(quote);
        if let MintQuoteResponse::Bolt11(response) = &mut response {
            response.state = MintQuoteState::Issued;
            response.amount_issued = response.amount_paid;
        }
        response
    }

    #[tokio::test]
    async fn batch_size_rejection_falls_back_to_individual_minting() {
        let (wallet, mock_client, quotes) = batch_claim_wallet(2).await;

        let refreshed = quotes.iter().map(paid_bolt11_quote_response).collect();
        mock_client.push_post_batch_check_mint_quote_status_response(Ok(refreshed));
        // The mint enforces a smaller batch limit than it advertises and
        // rejects the request during validation — nothing was written.
        mock_client
            .push_post_batch_mint_response(Err(Error::BatchSizeExceeded { actual: 2, max: 1 }));
        // The individual retries fail as well (no signatures staged); the
        // fallback only needs to attempt one request per quote.
        mock_client.push_post_mint_response(Err(Error::Custom("staged".to_string())));
        mock_client.push_post_mint_response(Err(Error::Custom("staged".to_string())));

        let minted = wallet
            .mint_unissued_quotes()
            .await
            .expect("claim should complete");

        assert_eq!(minted, Amount::ZERO);
        assert_eq!(mock_client.post_batch_mint_requests().len(), 1);
        assert_eq!(
            mock_client.post_mint_requests().len(),
            2,
            "a definitive batch-size rejection must retry each quote individually"
        );
    }

    #[tokio::test]
    async fn ambiguous_batch_mint_error_is_left_to_saga_recovery() {
        let (wallet, mock_client, quotes) = batch_claim_wallet(2).await;

        let refreshed = quotes.iter().map(paid_bolt11_quote_response).collect();
        mock_client.push_post_batch_check_mint_quote_status_response(Ok(refreshed));
        // A transport-style failure is an ambiguous write: the batch saga
        // owns recovery, no individual retry may be attempted.
        mock_client
            .push_post_batch_mint_response(Err(Error::Custom("connection reset".to_string())));

        let minted = wallet
            .mint_unissued_quotes()
            .await
            .expect("claim should complete");

        assert_eq!(minted, Amount::ZERO);
        assert_eq!(mock_client.post_batch_mint_requests().len(), 1);
        assert_eq!(
            mock_client.post_mint_requests().len(),
            0,
            "ambiguous writes must not be retried as individual mints"
        );
    }
}