cdk 0.16.0

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
//! Mint Builder

use std::collections::HashMap;
use std::sync::Arc;

use bitcoin::bip32::DerivationPath;
use cdk_common::database::{DynMintAuthDatabase, DynMintDatabase, MintKeysDatabase};
use cdk_common::error::Error;
use cdk_common::nut00::KnownMethod;
use cdk_common::nut04::MintMethodOptions;
use cdk_common::nut05::MeltMethodOptions;
use cdk_common::payment::DynMintPayment;
use cdk_common::{nut21, nut22};
use cdk_signatory::signatory::{RotateKeyArguments, Signatory};

use super::nut17::SupportedMethods;
use super::nut19::{self, CachedEndpoint};
use super::Nuts;
use crate::amount::Amount;
use crate::cdk_database;
use crate::mint::Mint;
use crate::nuts::{
    ContactInfo, CurrencyUnit, MeltMethodSettings, MintInfo, MintMethodSettings, MintVersion,
    MppMethodSettings, PaymentMethod, ProtectedEndpoint,
};
use crate::types::PaymentProcessorKey;

/// Configuration for a mint unit (keyset)
#[derive(Debug, Clone)]
pub struct UnitConfig {
    /// List of amounts to support (e.g., [1, 2, 4, 8, 16, 32])
    pub amounts: Vec<u64>,
    /// Input fee in parts per thousand
    pub input_fee_ppk: u64,
}

impl Default for UnitConfig {
    fn default() -> Self {
        Self {
            amounts: (0..32).map(|i| 2_u64.pow(i)).collect(),
            input_fee_ppk: 0,
        }
    }
}

/// Describes an extra keyset rotation to perform during mint build.
/// Used to create inactive/expired keysets for testing.
#[derive(Debug, Clone)]
pub struct KeysetRotation {
    /// Currency unit for this rotation
    pub unit: CurrencyUnit,
    /// Amounts for the keyset
    pub amounts: Vec<u64>,
    /// Input fee
    pub input_fee_ppk: u64,
    /// Whether to use keyset V2 (Version01) or V1 (Version00)
    pub use_keyset_v2: bool,
    /// Optional expiry timestamp (unix seconds)
    pub final_expiry: Option<u64>,
}

/// Cashu Mint Builder
pub struct MintBuilder {
    mint_info: MintInfo,
    localstore: DynMintDatabase,
    auth_localstore: Option<DynMintAuthDatabase>,
    payment_processors: HashMap<PaymentProcessorKey, DynMintPayment>,
    supported_units: HashMap<CurrencyUnit, (u64, Vec<u64>)>,
    custom_paths: HashMap<CurrencyUnit, DerivationPath>,
    use_keyset_v2: Option<bool>,
    keyset_rotations: Vec<KeysetRotation>,
    max_inputs: usize,
    max_outputs: usize,
    max_batch_size: Option<u64>,
}

impl std::fmt::Debug for MintBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MintBuilder")
            .field("mint_info", &self.mint_info)
            .field("supported_units", &self.supported_units)
            .finish_non_exhaustive()
    }
}

impl MintBuilder {
    /// New [`MintBuilder`]
    pub fn new(localstore: DynMintDatabase) -> MintBuilder {
        let mint_info = MintInfo {
            nuts: Nuts::new()
                .nut07(true)
                .nut08(true)
                .nut09(true)
                .nut10(true)
                .nut11(true)
                .nut12(true)
                .nut14(true)
                .nut20(true)
                .nut29(cdk_common::nut29::Settings::default()),
            ..Default::default()
        };

        MintBuilder {
            mint_info,
            localstore,
            auth_localstore: None,
            payment_processors: HashMap::new(),
            supported_units: HashMap::new(),
            custom_paths: HashMap::new(),
            use_keyset_v2: None,
            keyset_rotations: Vec::new(),
            max_inputs: 1000,
            max_outputs: 1000,
            max_batch_size: None,
        }
    }

    /// Set use keyset v2
    pub fn with_keyset_v2(mut self, use_keyset_v2: Option<bool>) -> Self {
        self.use_keyset_v2 = use_keyset_v2;
        self
    }

    /// Add a keyset rotation to execute during build.
    /// Used to create inactive/expired keysets for testing.
    pub fn with_keyset_rotation(mut self, rotation: KeysetRotation) -> Self {
        self.keyset_rotations.push(rotation);
        self
    }

    /// Set clear auth settings
    pub fn with_auth(
        mut self,
        auth_localstore: DynMintAuthDatabase,
        openid_discovery: String,
        client_id: String,
        protected_endpoints: Vec<ProtectedEndpoint>,
    ) -> Self {
        self.auth_localstore = Some(auth_localstore);
        self.mint_info.nuts.nut21 = Some(nut21::Settings::new(
            openid_discovery,
            client_id,
            protected_endpoints,
        ));
        self
    }

    /// Initialize builder's MintInfo from the database if present.
    /// If not present or parsing fails, keeps the current MintInfo.
    pub async fn init_from_db_if_present(&mut self) -> Result<(), cdk_database::Error> {
        // Attempt to read existing mint_info from the KV store
        let bytes_opt = self
            .localstore
            .kv_read(
                super::CDK_MINT_PRIMARY_NAMESPACE,
                super::CDK_MINT_CONFIG_SECONDARY_NAMESPACE,
                super::CDK_MINT_CONFIG_KV_KEY,
            )
            .await?;

        if let Some(bytes) = bytes_opt {
            if let Ok(info) = serde_json::from_slice::<MintInfo>(&bytes) {
                self.mint_info = info;
            } else {
                // If parsing fails, leave the current builder state untouched
                tracing::warn!("Failed to parse existing mint_info from DB; using builder state");
            }
        }

        Ok(())
    }

    /// Set blind auth settings
    pub fn with_blind_auth(
        mut self,
        bat_max_mint: u64,
        protected_endpoints: Vec<ProtectedEndpoint>,
    ) -> Self {
        let mut nuts = self.mint_info.nuts;

        nuts.nut22 = Some(nut22::Settings::new(bat_max_mint, protected_endpoints));

        self.mint_info.nuts = nuts;

        self
    }

    /// Set mint info
    pub fn with_mint_info(mut self, mint_info: MintInfo) -> Self {
        self.mint_info = mint_info;
        self
    }

    /// Set name
    pub fn with_name(mut self, name: String) -> Self {
        self.mint_info.name = Some(name);
        self
    }

    /// Set initial mint URLs
    pub fn with_urls(mut self, urls: Vec<String>) -> Self {
        self.mint_info.urls = Some(urls);
        self
    }

    /// Set icon url
    pub fn with_icon_url(mut self, icon_url: String) -> Self {
        self.mint_info.icon_url = Some(icon_url);
        self
    }

    /// Set icon url
    pub fn with_motd(mut self, motd: String) -> Self {
        self.mint_info.motd = Some(motd);
        self
    }

    /// Get a clone of the current MintInfo configured on the builder
    /// This allows using config-derived settings to initialize persistent state
    /// before any attempt to read from the database, which avoids first-run
    /// failures when the DB is empty.
    pub fn current_mint_info(&self) -> MintInfo {
        self.mint_info.clone()
    }

    /// Set terms of service URL
    pub fn with_tos_url(mut self, tos_url: String) -> Self {
        self.mint_info.tos_url = Some(tos_url);
        self
    }

    /// Set description
    pub fn with_description(mut self, description: String) -> Self {
        self.mint_info.description = Some(description);
        self
    }

    /// Set long description
    pub fn with_long_description(mut self, description: String) -> Self {
        self.mint_info.description_long = Some(description);
        self
    }

    /// Set version
    pub fn with_version(mut self, version: MintVersion) -> Self {
        self.mint_info.version = Some(version);
        self
    }

    /// Set contact info
    pub fn with_contact_info(mut self, contact_info: ContactInfo) -> Self {
        let mut contacts = self.mint_info.contact.clone().unwrap_or_default();
        contacts.push(contact_info);
        self.mint_info.contact = Some(contacts);
        self
    }

    /// Set pubkey
    pub fn with_pubkey(mut self, pubkey: crate::nuts::PublicKey) -> Self {
        self.mint_info.pubkey = Some(pubkey);

        self
    }

    /// Support websockets
    pub fn with_supported_websockets(mut self, supported_method: SupportedMethods) -> Self {
        let mut supported_settings = self.mint_info.nuts.nut17.supported.clone();

        if !supported_settings.contains(&supported_method) {
            supported_settings.push(supported_method);

            self.mint_info.nuts = self.mint_info.nuts.nut17(supported_settings);
        }

        self
    }

    /// Add support for NUT19
    pub fn with_cache(mut self, ttl: Option<u64>, cached_endpoints: Vec<CachedEndpoint>) -> Self {
        let nut19_settings = nut19::Settings {
            ttl,
            cached_endpoints,
        };

        self.mint_info.nuts.nut19 = nut19_settings;

        self
    }

    /// Set custom derivation paths for mint units
    pub fn with_custom_derivation_paths(
        mut self,
        custom_paths: HashMap<CurrencyUnit, DerivationPath>,
    ) -> Self {
        self.custom_paths = custom_paths;
        self
    }

    /// Set transaction limits for DoS protection
    pub fn with_limits(mut self, max_inputs: usize, max_outputs: usize) -> Self {
        self.max_inputs = max_inputs;
        self.max_outputs = max_outputs;
        self
    }

    /// Set batch minting settings (NUT-29)
    ///
    /// Configures the maximum number of quotes allowed in a single batch request
    /// and optionally specifies which payment methods support batch minting.
    ///
    /// # Arguments
    /// * `max_batch_size` - Maximum number of quotes in a batch request
    /// * `methods` - Optional list of payment methods that support batch minting
    pub fn with_batch_minting(
        mut self,
        max_batch_size: Option<u64>,
        methods: Option<Vec<String>>,
    ) -> Self {
        self.max_batch_size = max_batch_size;
        self.mint_info.nuts.nut29 = cdk_common::nut29::Settings::new(max_batch_size, methods);
        self
    }

    /// Configure a unit with custom amounts and fee
    ///
    /// This is optional - if not called before [`add_payment_processor`](Self::add_payment_processor),
    /// the unit will be auto-configured with default values (powers of 2 amounts, zero fee).
    ///
    /// # Arguments
    /// * `unit` - The currency unit to configure
    /// * `config` - The unit configuration (amounts and fee)
    ///
    /// # Example
    /// ```rust,ignore
    /// mint_builder.configure_unit(
    ///     CurrencyUnit::Sat,
    ///     UnitConfig {
    ///         amounts: vec![1, 2, 4, 8, 16, 32],
    ///         input_fee_ppk: 100,
    ///     }
    /// );
    /// ```
    pub fn configure_unit(&mut self, unit: CurrencyUnit, config: UnitConfig) -> Result<(), Error> {
        // Validate amounts
        if config.amounts.is_empty() {
            return Err(Error::Custom("Amounts list cannot be empty".to_string()));
        }

        // Check for duplicates and ensure sorted
        let mut sorted = config.amounts.clone();
        sorted.sort_unstable();
        sorted.dedup();
        if sorted.len() != config.amounts.len() {
            return Err(Error::Custom(
                "Amounts list contains duplicates".to_string(),
            ));
        }
        if sorted != config.amounts {
            return Err(Error::Custom(
                "Amounts must be sorted in ascending order".to_string(),
            ));
        }

        // Check all amounts are positive
        if config.amounts.contains(&0) {
            return Err(Error::Custom("Amounts must be greater than 0".to_string()));
        }

        self.supported_units
            .insert(unit, (config.input_fee_ppk, config.amounts));
        Ok(())
    }

    /// Add a payment processor for the given unit and payment method
    ///
    /// If the unit has not been configured via [`configure_unit`](Self::configure_unit),
    /// it will be auto-configured with default values (powers of 2 amounts, zero fee).
    ///
    /// # Arguments
    /// * `unit` - The currency unit for this payment processor
    /// * `method` - The payment method (e.g., bolt11, bolt12)
    /// * `limits` - Mint and melt amount limits
    /// * `payment_processor` - The payment processor implementation
    pub async fn add_payment_processor(
        &mut self,
        unit: CurrencyUnit,
        method: PaymentMethod,
        limits: MintMeltLimits,
        payment_processor: DynMintPayment,
    ) -> Result<(), Error> {
        let key = PaymentProcessorKey {
            unit: unit.clone(),
            method: method.clone(),
        };

        let settings = payment_processor.get_settings().await?;

        match method {
            // Handle bolt11 methods
            PaymentMethod::Known(KnownMethod::Bolt11) => {
                if let Some(ref bolt11_settings) = settings.bolt11 {
                    // Add MPP support if available
                    if bolt11_settings.mpp {
                        let mpp_settings = MppMethodSettings {
                            method: method.clone(),
                            unit: unit.clone(),
                        };

                        let mut mpp = self.mint_info.nuts.nut15.clone();
                        mpp.methods.push(mpp_settings);
                        self.mint_info.nuts.nut15 = mpp;
                    }

                    // Add to NUT04 (mint)
                    let mint_method_settings = MintMethodSettings {
                        method: method.clone(),
                        unit: unit.clone(),
                        min_amount: Some(limits.mint_min),
                        max_amount: Some(limits.mint_max),
                        options: Some(MintMethodOptions::Bolt11 {
                            description: bolt11_settings.invoice_description,
                        }),
                    };
                    self.mint_info.nuts.nut04.methods.push(mint_method_settings);
                    self.mint_info.nuts.nut04.disabled = false;

                    // Add to NUT05 (melt)
                    let melt_method_settings = MeltMethodSettings {
                        method: method.clone(),
                        unit: unit.clone(),
                        min_amount: Some(limits.melt_min),
                        max_amount: Some(limits.melt_max),
                        options: Some(MeltMethodOptions::Bolt11 {
                            amountless: bolt11_settings.amountless,
                        }),
                    };
                    self.mint_info.nuts.nut05.methods.push(melt_method_settings);
                    self.mint_info.nuts.nut05.disabled = false;
                }
            }
            // Handle bolt12 methods
            PaymentMethod::Known(KnownMethod::Bolt12) => {
                if settings.bolt12.is_some() {
                    // Add to NUT04 (mint) - bolt12 doesn't have specific options yet
                    let mint_method_settings = MintMethodSettings {
                        method: method.clone(),
                        unit: unit.clone(),
                        min_amount: Some(limits.mint_min),
                        max_amount: Some(limits.mint_max),
                        options: None, // No bolt12-specific options in NUT04 yet
                    };
                    self.mint_info.nuts.nut04.methods.push(mint_method_settings);
                    self.mint_info.nuts.nut04.disabled = false;

                    // Add to NUT05 (melt) - bolt12 doesn't have specific options in MeltMethodOptions yet
                    let melt_method_settings = MeltMethodSettings {
                        method: method.clone(),
                        unit: unit.clone(),
                        min_amount: Some(limits.melt_min),
                        max_amount: Some(limits.melt_max),
                        options: None, // No bolt12-specific options in NUT05 yet
                    };
                    self.mint_info.nuts.nut05.methods.push(melt_method_settings);
                    self.mint_info.nuts.nut05.disabled = false;
                }
            }
            // Handle custom methods
            PaymentMethod::Custom(_) => {
                // Check if this custom method is supported by the payment processor
                if settings.custom.contains_key(method.as_str()) {
                    // Add to NUT04 (mint)
                    let mint_method_settings = MintMethodSettings {
                        method: method.clone(),
                        unit: unit.clone(),
                        min_amount: Some(limits.mint_min),
                        max_amount: Some(limits.mint_max),
                        options: Some(MintMethodOptions::Custom {}),
                    };
                    self.mint_info.nuts.nut04.methods.push(mint_method_settings);
                    self.mint_info.nuts.nut04.disabled = false;

                    // Add to NUT05 (melt)
                    let melt_method_settings = MeltMethodSettings {
                        method: method.clone(),
                        unit: unit.clone(),
                        min_amount: Some(limits.melt_min),
                        max_amount: Some(limits.melt_max),
                        options: None, // No custom-specific options in NUT05 yet
                    };
                    self.mint_info.nuts.nut05.methods.push(melt_method_settings);
                    self.mint_info.nuts.nut05.disabled = false;
                }
            }
        }

        // Check that the unit has been pre-configured
        if !self.supported_units.contains_key(&key.unit) {
            self.configure_unit(key.unit.clone(), Default::default())?;
        }

        self.payment_processors.insert(key, payment_processor);
        Ok(())
    }
    /// Sets the input fee ppk for a given unit
    ///
    /// The unit **MUST** already have been added with a ln backend
    pub fn set_unit_fee(&mut self, unit: &CurrencyUnit, input_fee_ppk: u64) -> Result<(), Error> {
        let (input_fee, _) = self
            .supported_units
            .get_mut(unit)
            .ok_or(Error::UnsupportedUnit)?;

        *input_fee = input_fee_ppk;

        Ok(())
    }

    /// Build the mint with the provided signatory
    pub async fn build_with_signatory(
        #[allow(unused_mut)] mut self,
        signatory: Arc<dyn Signatory + Send + Sync>,
    ) -> Result<Mint, Error> {
        // Check active keysets and rotate if necessary
        let active_keysets = signatory.keysets().await?;

        // Ensure Auth keyset is created when auth is enabled
        if self.auth_localstore.is_some() {
            self.supported_units
                .entry(CurrencyUnit::Auth)
                .or_insert((0, vec![1]));
        }

        for (unit, (fee, amounts)) in &self.supported_units {
            // Check if we have an active keyset for this unit
            let keyset = active_keysets
                .keysets
                .iter()
                .find(|k| k.active && k.unit == *unit);

            let mut rotate = false;

            if let Some(keyset) = keyset {
                // Check if fee matches
                if keyset.input_fee_ppk != *fee {
                    tracing::info!(
                        "Rotating keyset for unit {} due to fee mismatch (current: {}, expected: {})",
                        unit,
                        keyset.input_fee_ppk,
                        fee
                    );
                    rotate = true;
                }

                // Check if amounts match
                if keyset.amounts != *amounts {
                    tracing::info!("Rotating keyset for unit {} due to amounts mismatch", unit);
                    rotate = true;
                }

                // Check if version matches explicit preference
                if let Some(want_v2) = self.use_keyset_v2 {
                    let is_v2 =
                        keyset.id.get_version() == cdk_common::nut02::KeySetVersion::Version01;
                    if want_v2 && !is_v2 {
                        tracing::info!("Rotating keyset for unit {} due to explicit V2 preference (current is V1)", unit);
                        rotate = true;
                    } else if !want_v2 && is_v2 {
                        tracing::info!("Rotating keyset for unit {} due to explicit V1 preference (current is V2)", unit);
                        rotate = true;
                    }
                }
            } else {
                // No active keyset for this unit
                tracing::info!("Rotating keyset for unit {} (no active keyset found)", unit);
                rotate = true;
            }

            if rotate {
                signatory
                    .rotate_keyset(RotateKeyArguments {
                        unit: unit.clone(),
                        amounts: amounts.clone(),
                        input_fee_ppk: *fee,
                        keyset_id_type: if self.use_keyset_v2.unwrap_or(true) {
                            cdk_common::nut02::KeySetVersion::Version01
                        } else {
                            cdk_common::nut02::KeySetVersion::Version00
                        },
                        final_expiry: None,
                    })
                    .await?;
            }
        }

        // Execute configured keyset rotations (e.g. for test keysets)
        for rotation in &self.keyset_rotations {
            signatory
                .rotate_keyset(RotateKeyArguments {
                    unit: rotation.unit.clone(),
                    amounts: rotation.amounts.clone(),
                    input_fee_ppk: rotation.input_fee_ppk,
                    keyset_id_type: if rotation.use_keyset_v2 {
                        cdk_common::nut02::KeySetVersion::Version01
                    } else {
                        cdk_common::nut02::KeySetVersion::Version00
                    },
                    final_expiry: rotation.final_expiry,
                })
                .await?;
        }

        if let Some(auth_localstore) = self.auth_localstore {
            return Mint::new_with_auth(
                self.mint_info,
                signatory,
                self.localstore,
                auth_localstore,
                self.payment_processors,
                self.max_inputs,
                self.max_outputs,
            )
            .await;
        }
        Mint::new(
            self.mint_info,
            signatory,
            self.localstore,
            self.payment_processors,
            self.max_inputs,
            self.max_outputs,
        )
        .await
    }

    /// Build the mint with the provided keystore and seed
    pub async fn build_with_seed(
        self,
        keystore: Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync>,
        seed: &[u8],
    ) -> Result<Mint, Error> {
        let in_memory_signatory = cdk_signatory::db_signatory::DbSignatory::new(
            keystore,
            seed,
            self.supported_units.clone(),
            self.custom_paths.clone(),
        )
        .await?;

        let signatory = Arc::new(cdk_signatory::embedded::Service::new(Arc::new(
            in_memory_signatory,
        )));

        self.build_with_signatory(signatory).await
    }
}

/// Mint and Melt Limits
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MintMeltLimits {
    /// Min mint amount
    pub mint_min: Amount,
    /// Max mint amount
    pub mint_max: Amount,
    /// Min melt amount
    pub melt_min: Amount,
    /// Max melt amount
    pub melt_max: Amount,
}

impl MintMeltLimits {
    /// Create new [`MintMeltLimits`]. The `min` and `max` limits apply to both minting and melting.
    pub fn new(min: u64, max: u64) -> Self {
        Self {
            mint_min: min.into(),
            mint_max: max.into(),
            melt_min: min.into(),
            melt_max: max.into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::pin::Pin;
    use std::sync::Arc;

    use async_trait::async_trait;
    use cdk_common::payment::{
        Bolt11Settings, Bolt12Settings, CreateIncomingPaymentResponse, Event,
        IncomingPaymentOptions, MakePaymentResponse, OutgoingPaymentOptions, PaymentIdentifier,
        PaymentQuoteResponse, SettingsResponse,
    };
    use cdk_sqlite::mint::memory;
    use futures::Stream;
    use KnownMethod;

    use super::*;

    // Mock payment processor for testing
    struct MockPaymentProcessor {
        settings: SettingsResponse,
    }

    #[async_trait]
    impl cdk_common::payment::MintPayment for MockPaymentProcessor {
        type Err = cdk_common::payment::Error;

        async fn get_settings(&self) -> Result<SettingsResponse, Self::Err> {
            Ok(self.settings.clone())
        }

        async fn create_incoming_payment_request(
            &self,
            _options: IncomingPaymentOptions,
        ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
            unimplemented!()
        }

        async fn get_payment_quote(
            &self,
            _unit: &CurrencyUnit,
            _options: OutgoingPaymentOptions,
        ) -> Result<PaymentQuoteResponse, Self::Err> {
            unimplemented!()
        }

        async fn make_payment(
            &self,
            _unit: &CurrencyUnit,
            _options: OutgoingPaymentOptions,
        ) -> Result<MakePaymentResponse, Self::Err> {
            unimplemented!()
        }

        async fn wait_payment_event(
            &self,
        ) -> Result<Pin<Box<dyn Stream<Item = Event> + Send>>, Self::Err> {
            unimplemented!()
        }

        fn is_wait_invoice_active(&self) -> bool {
            false
        }

        fn cancel_wait_invoice(&self) {}

        async fn check_incoming_payment_status(
            &self,
            _payment_identifier: &PaymentIdentifier,
        ) -> Result<Vec<cdk_common::payment::WaitPaymentResponse>, Self::Err> {
            unimplemented!()
        }

        async fn check_outgoing_payment(
            &self,
            _payment_identifier: &PaymentIdentifier,
        ) -> Result<MakePaymentResponse, Self::Err> {
            unimplemented!()
        }
    }

    #[tokio::test]
    async fn test_mint_builder_default_nuts_support() {
        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore);
        let mint_info = builder.current_mint_info();

        assert!(
            mint_info.nuts.nut07.supported,
            "NUT-07 should be supported by default"
        );
        assert!(
            mint_info.nuts.nut08.supported,
            "NUT-08 should be supported by default"
        );
        assert!(
            mint_info.nuts.nut09.supported,
            "NUT-09 should be supported by default"
        );
        assert!(
            mint_info.nuts.nut10.supported,
            "NUT-10 should be supported by default"
        );
        assert!(
            mint_info.nuts.nut11.supported,
            "NUT-11 should be supported by default"
        );
        assert!(
            mint_info.nuts.nut12.supported,
            "NUT-12 should be supported by default"
        );
        assert!(
            mint_info.nuts.nut14.supported,
            "NUT-14 (HTLC) should be supported by default"
        );
        assert!(
            mint_info.nuts.nut20.supported,
            "NUT-20 should be supported by default"
        );
        assert!(
            mint_info.nuts.nut29.is_empty(),
            "NUT-29 should have empty settings by default"
        );
    }

    #[tokio::test]
    async fn test_mint_builder_batch_minting_settings() {
        let localstore = Arc::new(memory::empty().await.unwrap());
        let builder = MintBuilder::new(localstore).with_batch_minting(
            Some(100),
            Some(vec!["bolt11".to_string(), "bolt12".to_string()]),
        );
        let mint_info = builder.current_mint_info();

        assert_eq!(
            mint_info.nuts.nut29.max_batch_size,
            Some(100),
            "NUT-29 max_batch_size should be set"
        );
        assert_eq!(
            mint_info.nuts.nut29.methods,
            Some(vec!["bolt11".to_string(), "bolt12".to_string()]),
            "NUT-29 methods should be set"
        );
    }

    #[tokio::test]
    async fn test_add_payment_processor_bolt11() {
        let localstore = Arc::new(memory::empty().await.unwrap());
        let mut builder = MintBuilder::new(localstore);

        // Configure the unit first
        builder
            .configure_unit(
                CurrencyUnit::Sat,
                UnitConfig {
                    amounts: vec![1, 2, 4, 8, 16, 32],
                    input_fee_ppk: 0,
                },
            )
            .unwrap();

        let bolt11_settings = Bolt11Settings {
            mpp: true,
            amountless: true,
            invoice_description: true,
        };

        let settings = SettingsResponse {
            unit: "sat".to_string(),
            bolt11: Some(bolt11_settings),
            bolt12: None,
            custom: HashMap::new(),
        };

        let payment_processor = Arc::new(MockPaymentProcessor { settings });
        let unit = CurrencyUnit::Sat;
        let method = PaymentMethod::Known(KnownMethod::Bolt11);
        let limits = MintMeltLimits::new(100, 10000);

        builder
            .add_payment_processor(unit.clone(), method.clone(), limits, payment_processor)
            .await
            .unwrap();

        let mint_info = builder.current_mint_info();

        // Check NUT04 (mint) settings
        assert!(!mint_info.nuts.nut04.disabled);
        assert_eq!(mint_info.nuts.nut04.methods.len(), 1);
        let mint_method = &mint_info.nuts.nut04.methods[0];
        assert_eq!(mint_method.method, method);
        assert_eq!(mint_method.unit, unit);
        assert_eq!(mint_method.min_amount, Some(limits.mint_min));
        assert_eq!(mint_method.max_amount, Some(limits.mint_max));
        assert!(matches!(
            mint_method.options,
            Some(MintMethodOptions::Bolt11 { description: true })
        ));

        // Check NUT05 (melt) settings
        assert!(!mint_info.nuts.nut05.disabled);
        assert_eq!(mint_info.nuts.nut05.methods.len(), 1);
        let melt_method = &mint_info.nuts.nut05.methods[0];
        assert_eq!(melt_method.method, method);
        assert_eq!(melt_method.unit, unit);
        assert_eq!(melt_method.min_amount, Some(limits.melt_min));
        assert_eq!(melt_method.max_amount, Some(limits.melt_max));
        assert!(matches!(
            melt_method.options,
            Some(MeltMethodOptions::Bolt11 { amountless: true })
        ));

        // Check NUT15 (MPP) settings
        assert_eq!(mint_info.nuts.nut15.methods.len(), 1);
        let mpp_method = &mint_info.nuts.nut15.methods[0];
        assert_eq!(mpp_method.method, method);
        assert_eq!(mpp_method.unit, unit);
    }

    #[tokio::test]
    async fn test_add_payment_processor_bolt11_without_mpp() {
        let localstore = Arc::new(memory::empty().await.unwrap());
        let mut builder = MintBuilder::new(localstore);

        // Configure the unit first
        builder
            .configure_unit(
                CurrencyUnit::Sat,
                UnitConfig {
                    amounts: vec![1, 2, 4, 8, 16, 32],
                    input_fee_ppk: 0,
                },
            )
            .unwrap();

        let bolt11_settings = Bolt11Settings {
            mpp: false, // MPP disabled
            amountless: false,
            invoice_description: false,
        };

        let settings = SettingsResponse {
            unit: "sat".to_string(),
            bolt11: Some(bolt11_settings),
            bolt12: None,
            custom: HashMap::new(),
        };

        let payment_processor = Arc::new(MockPaymentProcessor { settings });
        let unit = CurrencyUnit::Sat;
        let method = PaymentMethod::Known(KnownMethod::Bolt11);
        let limits = MintMeltLimits::new(100, 10000);

        builder
            .add_payment_processor(unit, method, limits, payment_processor)
            .await
            .unwrap();

        let mint_info = builder.current_mint_info();

        // NUT15 should be empty when MPP is disabled
        assert_eq!(mint_info.nuts.nut15.methods.len(), 0);

        // But NUT04 and NUT05 should still be populated
        assert_eq!(mint_info.nuts.nut04.methods.len(), 1);
        assert_eq!(mint_info.nuts.nut05.methods.len(), 1);
    }

    #[tokio::test]
    async fn test_add_payment_processor_bolt12() {
        let localstore = Arc::new(memory::empty().await.unwrap());
        let mut builder = MintBuilder::new(localstore);

        // Configure the unit first
        builder
            .configure_unit(
                CurrencyUnit::Sat,
                UnitConfig {
                    amounts: vec![1, 2, 4, 8, 16, 32],
                    input_fee_ppk: 0,
                },
            )
            .unwrap();

        let bolt12_settings = Bolt12Settings { amountless: true };

        let settings = SettingsResponse {
            unit: "sat".to_string(),
            bolt11: None,
            bolt12: Some(bolt12_settings),
            custom: HashMap::new(),
        };

        let payment_processor = Arc::new(MockPaymentProcessor { settings });
        let unit = CurrencyUnit::Sat;
        let method = PaymentMethod::Known(KnownMethod::Bolt12);
        let limits = MintMeltLimits::new(100, 10000);

        builder
            .add_payment_processor(unit.clone(), method.clone(), limits, payment_processor)
            .await
            .unwrap();

        let mint_info = builder.current_mint_info();

        // Check NUT04 (mint) settings
        assert!(!mint_info.nuts.nut04.disabled);
        assert_eq!(mint_info.nuts.nut04.methods.len(), 1);
        let mint_method = &mint_info.nuts.nut04.methods[0];
        assert_eq!(mint_method.method, method);
        assert_eq!(mint_method.unit, unit);
        assert_eq!(mint_method.min_amount, Some(limits.mint_min));
        assert_eq!(mint_method.max_amount, Some(limits.mint_max));
        assert!(mint_method.options.is_none());

        // Check NUT05 (melt) settings
        assert!(!mint_info.nuts.nut05.disabled);
        assert_eq!(mint_info.nuts.nut05.methods.len(), 1);
        let melt_method = &mint_info.nuts.nut05.methods[0];
        assert_eq!(melt_method.method, method);
        assert_eq!(melt_method.unit, unit);
        assert_eq!(melt_method.min_amount, Some(limits.melt_min));
        assert_eq!(melt_method.max_amount, Some(limits.melt_max));
        assert!(melt_method.options.is_none());
    }

    #[tokio::test]
    async fn test_add_payment_processor_custom() {
        let localstore = Arc::new(memory::empty().await.unwrap());
        let mut builder = MintBuilder::new(localstore);

        // Configure the unit first
        builder
            .configure_unit(
                CurrencyUnit::Usd,
                UnitConfig {
                    amounts: vec![1, 2, 4, 8, 16, 32],
                    input_fee_ppk: 0,
                },
            )
            .unwrap();

        let mut custom_methods = HashMap::new();
        custom_methods.insert("paypal".to_string(), "{}".to_string());

        let settings = SettingsResponse {
            unit: "usd".to_string(),
            bolt11: None,
            bolt12: None,
            custom: custom_methods,
        };

        let payment_processor = Arc::new(MockPaymentProcessor { settings });
        let unit = CurrencyUnit::Usd;
        let method = PaymentMethod::Custom("paypal".to_string());
        let limits = MintMeltLimits::new(100, 10000);

        builder
            .add_payment_processor(unit.clone(), method.clone(), limits, payment_processor)
            .await
            .unwrap();

        let mint_info = builder.current_mint_info();

        // Check NUT04 (mint) settings
        assert!(!mint_info.nuts.nut04.disabled);
        assert_eq!(mint_info.nuts.nut04.methods.len(), 1);
        let mint_method = &mint_info.nuts.nut04.methods[0];
        assert_eq!(mint_method.method, method);
        assert_eq!(mint_method.unit, unit);
        assert_eq!(mint_method.min_amount, Some(limits.mint_min));
        assert_eq!(mint_method.max_amount, Some(limits.mint_max));
        assert!(matches!(
            mint_method.options,
            Some(MintMethodOptions::Custom {})
        ));

        // Check NUT05 (melt) settings
        assert!(!mint_info.nuts.nut05.disabled);
        assert_eq!(mint_info.nuts.nut05.methods.len(), 1);
        let melt_method = &mint_info.nuts.nut05.methods[0];
        assert_eq!(melt_method.method, method);
        assert_eq!(melt_method.unit, unit);
        assert_eq!(melt_method.min_amount, Some(limits.melt_min));
        assert_eq!(melt_method.max_amount, Some(limits.melt_max));
        assert!(melt_method.options.is_none());
    }

    #[tokio::test]
    async fn test_add_payment_processor_custom_not_supported() {
        let localstore = Arc::new(memory::empty().await.unwrap());
        let mut builder = MintBuilder::new(localstore);

        // Configure the unit first
        builder
            .configure_unit(
                CurrencyUnit::Usd,
                UnitConfig {
                    amounts: vec![1, 2, 4, 8, 16, 32],
                    input_fee_ppk: 0,
                },
            )
            .unwrap();

        // Settings with no custom methods
        let settings = SettingsResponse {
            unit: "usd".to_string(),
            bolt11: None,
            bolt12: None,
            custom: HashMap::new(), // Empty - no custom methods supported
        };

        let payment_processor = Arc::new(MockPaymentProcessor { settings });
        let unit = CurrencyUnit::Usd;
        let method = PaymentMethod::Custom("paypal".to_string());
        let limits = MintMeltLimits::new(1, 1000);

        builder
            .add_payment_processor(unit, method, limits, payment_processor)
            .await
            .unwrap();

        let mint_info = builder.current_mint_info();

        // NUT04 and NUT05 should remain empty since the custom method is not in settings
        assert_eq!(mint_info.nuts.nut04.methods.len(), 0);
        assert_eq!(mint_info.nuts.nut05.methods.len(), 0);
    }

    #[tokio::test]
    async fn test_add_multiple_payment_processors() {
        let localstore = Arc::new(memory::empty().await.unwrap());
        let mut builder = MintBuilder::new(localstore);

        // Configure the unit first
        builder
            .configure_unit(
                CurrencyUnit::Sat,
                UnitConfig {
                    amounts: vec![1, 2, 4, 8, 16, 32],
                    input_fee_ppk: 0,
                },
            )
            .unwrap();

        // Add Bolt11
        let bolt11_settings = Bolt11Settings {
            mpp: false,
            amountless: true,
            invoice_description: false,
        };
        let settings1 = SettingsResponse {
            unit: "sat".to_string(),
            bolt11: Some(bolt11_settings),
            bolt12: None,
            custom: HashMap::new(),
        };
        let processor1 = Arc::new(MockPaymentProcessor {
            settings: settings1,
        });
        builder
            .add_payment_processor(
                CurrencyUnit::Sat,
                PaymentMethod::Known(KnownMethod::Bolt11),
                MintMeltLimits::new(100, 10000),
                processor1,
            )
            .await
            .unwrap();

        // Add Bolt12
        let bolt12_settings = Bolt12Settings { amountless: false };
        let settings2 = SettingsResponse {
            unit: "sat".to_string(),
            bolt11: None,
            bolt12: Some(bolt12_settings),
            custom: HashMap::new(),
        };
        let processor2 = Arc::new(MockPaymentProcessor {
            settings: settings2,
        });
        builder
            .add_payment_processor(
                CurrencyUnit::Sat,
                PaymentMethod::Known(KnownMethod::Bolt12),
                MintMeltLimits::new(200, 20000),
                processor2,
            )
            .await
            .unwrap();

        let mint_info = builder.current_mint_info();

        // Should have both methods in NUT04 and NUT05
        assert_eq!(mint_info.nuts.nut04.methods.len(), 2);
        assert_eq!(mint_info.nuts.nut05.methods.len(), 2);
    }
}