cashu 0.16.0

Cashu shared types and crypto utilities, used as the foundation for the CDK and their crates
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
//! NUT-06: Mint Information
//!
//! <https://github.com/cashubtc/nuts/blob/main/06.md>

use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use super::nut01::PublicKey;
use super::nut17::SupportedMethods;
use super::nut19::CachedEndpoint;
use super::{
    nut04, nut05, nut15, nut19, nut29, AuthRequired, BlindAuthSettings, ClearAuthSettings,
    MppMethodSettings, ProtectedEndpoint,
};
use crate::util::serde_helpers::deserialize_empty_string_as_none;
use crate::CurrencyUnit;

/// Mint Version
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
pub struct MintVersion {
    /// Mint Software name
    pub name: String,
    /// Mint Version
    pub version: String,
}

impl MintVersion {
    /// Create new [`MintVersion`]
    pub fn new(name: String, version: String) -> Self {
        Self { name, version }
    }
}

impl std::fmt::Display for MintVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}/{}", self.name, self.version)
    }
}

impl Serialize for MintVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let combined = format!("{}/{}", self.name, self.version);
        serializer.serialize_str(&combined)
    }
}

impl<'de> Deserialize<'de> for MintVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let combined = String::deserialize(deserializer)?;
        let parts: Vec<&str> = combined.split('/').collect();
        if parts.len() != 2 {
            return Err(serde::de::Error::custom("Invalid input string"));
        }
        Ok(MintVersion {
            name: parts[0].to_string(),
            version: parts[1].to_string(),
        })
    }
}

/// Mint Info [NUT-06]
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
pub struct MintInfo {
    /// name of the mint and should be recognizable
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// hex pubkey of the mint
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_empty_string_as_none"
    )]
    pub pubkey: Option<PublicKey>,
    /// implementation name and the version running
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<MintVersion>,
    /// short description of the mint
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// long description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description_long: Option<String>,
    /// Contact info
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contact: Option<Vec<ContactInfo>>,
    /// shows which NUTs the mint supports
    pub nuts: Nuts,
    /// Mint's icon URL
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon_url: Option<String>,
    /// Mint's endpoint URLs
    #[serde(skip_serializing_if = "Option::is_none")]
    pub urls: Option<Vec<String>>,
    /// message of the day that the wallet must display to the user
    #[serde(skip_serializing_if = "Option::is_none")]
    pub motd: Option<String>,
    /// server unix timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time: Option<u64>,
    /// terms of url service of the mint
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tos_url: Option<String>,
}

impl MintInfo {
    /// Create new [`MintInfo`]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set name
    pub fn name<S>(self, name: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            name: Some(name.into()),
            ..self
        }
    }

    /// Set pubkey
    pub fn pubkey(self, pubkey: PublicKey) -> Self {
        Self {
            pubkey: Some(pubkey),
            ..self
        }
    }

    /// Set [`MintVersion`]
    pub fn version(self, mint_version: MintVersion) -> Self {
        Self {
            version: Some(mint_version),
            ..self
        }
    }

    /// Set description
    pub fn description<S>(self, description: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            description: Some(description.into()),
            ..self
        }
    }

    /// Set long description
    pub fn long_description<S>(self, description_long: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            description_long: Some(description_long.into()),
            ..self
        }
    }

    /// Set contact info
    pub fn contact_info(self, contact_info: Vec<ContactInfo>) -> Self {
        Self {
            contact: Some(contact_info),
            ..self
        }
    }

    /// Set nuts
    pub fn nuts(self, nuts: Nuts) -> Self {
        Self { nuts, ..self }
    }

    /// Set mint icon url
    pub fn icon_url<S>(self, icon_url: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            icon_url: Some(icon_url.into()),
            ..self
        }
    }

    /// Set motd
    pub fn motd<S>(self, motd: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            motd: Some(motd.into()),
            ..self
        }
    }

    /// Set time
    pub fn time<S>(self, time: S) -> Self
    where
        S: Into<u64>,
    {
        Self {
            time: Some(time.into()),
            ..self
        }
    }

    /// Set tos_url
    pub fn tos_url<S>(self, tos_url: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            tos_url: Some(tos_url.into()),
            ..self
        }
    }

    /// Get protected endpoints
    pub fn protected_endpoints(&self) -> HashMap<ProtectedEndpoint, AuthRequired> {
        let mut protected_endpoints = HashMap::new();

        if let Some(nut21_settings) = &self.nuts.nut21 {
            for endpoint in nut21_settings.protected_endpoints.iter() {
                protected_endpoints.insert(endpoint.clone(), AuthRequired::Clear);
            }
        }

        if let Some(nut22_settings) = &self.nuts.nut22 {
            for endpoint in nut22_settings.protected_endpoints.iter() {
                protected_endpoints.insert(endpoint.clone(), AuthRequired::Blind);
            }
        }
        protected_endpoints
    }

    /// Get Openid discovery of the mint if it is set
    pub fn openid_discovery(&self) -> Option<String> {
        self.nuts
            .nut21
            .as_ref()
            .map(|s| s.openid_discovery.to_string())
    }

    /// Get Openid discovery of the mint if it is set
    pub fn client_id(&self) -> Option<String> {
        self.nuts.nut21.as_ref().map(|s| s.client_id.clone())
    }

    /// Max bat mint
    pub fn bat_max_mint(&self) -> Option<u64> {
        self.nuts.nut22.as_ref().map(|s| s.bat_max_mint)
    }

    /// Get all supported currency units for this mint (both mint and melt)
    pub fn supported_units(&self) -> Vec<&CurrencyUnit> {
        let mut units = HashSet::new();

        units.extend(self.nuts.supported_mint_units());
        units.extend(self.nuts.supported_melt_units());

        units.into_iter().collect()
    }
}

/// Supported nuts and settings
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
pub struct Nuts {
    /// NUT04 Settings
    #[serde(default)]
    #[serde(rename = "4")]
    pub nut04: nut04::Settings,
    /// NUT05 Settings
    #[serde(default)]
    #[serde(rename = "5")]
    pub nut05: nut05::Settings,
    /// NUT07 Settings
    #[serde(default)]
    #[serde(rename = "7")]
    pub nut07: SupportedSettings,
    /// NUT08 Settings
    #[serde(default)]
    #[serde(rename = "8")]
    pub nut08: SupportedSettings,
    /// NUT09 Settings
    #[serde(default)]
    #[serde(rename = "9")]
    pub nut09: SupportedSettings,
    /// NUT10 Settings
    #[serde(rename = "10")]
    #[serde(default)]
    pub nut10: SupportedSettings,
    /// NUT11 Settings
    #[serde(rename = "11")]
    #[serde(default)]
    pub nut11: SupportedSettings,
    /// NUT12 Settings
    #[serde(default)]
    #[serde(rename = "12")]
    pub nut12: SupportedSettings,
    /// NUT14 Settings
    #[serde(default)]
    #[serde(rename = "14")]
    pub nut14: SupportedSettings,
    /// NUT15 Settings
    #[serde(default)]
    #[serde(rename = "15")]
    #[serde(skip_serializing_if = "nut15::Settings::is_empty")]
    pub nut15: nut15::Settings,
    /// NUT17 Settings
    #[serde(default)]
    #[serde(rename = "17")]
    pub nut17: super::nut17::SupportedSettings,
    /// NUT19 Settings
    #[serde(default)]
    #[serde(rename = "19")]
    pub nut19: nut19::Settings,
    /// NUT20 Settings
    #[serde(default)]
    #[serde(rename = "20")]
    pub nut20: SupportedSettings,
    /// NUT21 Settings
    #[serde(rename = "21")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nut21: Option<ClearAuthSettings>,
    /// NUT22 Settings
    #[serde(rename = "22")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nut22: Option<BlindAuthSettings>,
    /// NUT29 Settings
    #[serde(default)]
    #[serde(rename = "29")]
    #[serde(skip_serializing_if = "nut29::Settings::is_empty")]
    pub nut29: nut29::Settings,
}

impl Nuts {
    /// Create new [`Nuts`]
    pub fn new() -> Self {
        Self::default()
    }

    /// Nut04 settings
    pub fn nut04(self, nut04_settings: nut04::Settings) -> Self {
        Self {
            nut04: nut04_settings,
            ..self
        }
    }

    /// Nut05 settings
    pub fn nut05(self, nut05_settings: nut05::Settings) -> Self {
        Self {
            nut05: nut05_settings,
            ..self
        }
    }

    /// Nut07 settings
    pub fn nut07(self, supported: bool) -> Self {
        Self {
            nut07: SupportedSettings { supported },
            ..self
        }
    }

    /// Nut08 settings
    pub fn nut08(self, supported: bool) -> Self {
        Self {
            nut08: SupportedSettings { supported },
            ..self
        }
    }

    /// Nut09 settings
    pub fn nut09(self, supported: bool) -> Self {
        Self {
            nut09: SupportedSettings { supported },
            ..self
        }
    }

    /// Nut10 settings
    pub fn nut10(self, supported: bool) -> Self {
        Self {
            nut10: SupportedSettings { supported },
            ..self
        }
    }

    /// Nut11 settings
    pub fn nut11(self, supported: bool) -> Self {
        Self {
            nut11: SupportedSettings { supported },
            ..self
        }
    }

    /// Nut12 settings
    pub fn nut12(self, supported: bool) -> Self {
        Self {
            nut12: SupportedSettings { supported },
            ..self
        }
    }

    /// Nut14 settings
    pub fn nut14(self, supported: bool) -> Self {
        Self {
            nut14: SupportedSettings { supported },
            ..self
        }
    }

    /// Nut15 settings
    pub fn nut15(self, mpp_settings: Vec<MppMethodSettings>) -> Self {
        Self {
            nut15: nut15::Settings {
                methods: mpp_settings,
            },
            ..self
        }
    }

    /// Nut17 settings
    pub fn nut17(self, supported: Vec<SupportedMethods>) -> Self {
        Self {
            nut17: super::nut17::SupportedSettings { supported },
            ..self
        }
    }

    /// Nut19 settings
    pub fn nut19(self, ttl: Option<u64>, cached_endpoints: Vec<CachedEndpoint>) -> Self {
        Self {
            nut19: nut19::Settings {
                ttl,
                cached_endpoints,
            },
            ..self
        }
    }

    /// Nut20 settings
    pub fn nut20(self, supported: bool) -> Self {
        Self {
            nut20: SupportedSettings { supported },
            ..self
        }
    }

    /// Nut29 settings
    pub fn nut29(self, settings: nut29::Settings) -> Self {
        Self {
            nut29: settings,
            ..self
        }
    }

    /// Units where minting is supported
    pub fn supported_mint_units(&self) -> Vec<&CurrencyUnit> {
        self.nut04
            .methods
            .iter()
            .map(|s| &s.unit)
            .collect::<HashSet<_>>()
            .into_iter()
            .collect()
    }

    /// Units where melting is supported
    pub fn supported_melt_units(&self) -> Vec<&CurrencyUnit> {
        self.nut05
            .methods
            .iter()
            .map(|s| &s.unit)
            .collect::<HashSet<_>>()
            .into_iter()
            .collect()
    }
}

/// Check state Settings
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
pub struct SupportedSettings {
    /// Setting supported
    pub supported: bool,
}

/// Contact Info
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
pub struct ContactInfo {
    /// Contact Method i.e. nostr
    pub method: String,
    /// Contact info i.e. npub...
    pub info: String,
}

impl ContactInfo {
    /// Create new [`ContactInfo`]
    pub fn new(method: String, info: String) -> Self {
        Self { method, info }
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::nut00::KnownMethod;
    use crate::nut04::MintMethodOptions;

    #[test]
    fn test_des_mint_into() {
        let mint_info_str = r#"{
"name": "Cashu mint",
"pubkey": "0296d0aa13b6a31cf0cd974249f28c7b7176d7274712c95a41c7d8066d3f29d679",
"version": "Nutshell/0.15.3",
"contact": [
    ["", ""],
    ["", ""]
    ],
    "nuts": {
        "4": {
            "methods": [
                {"method": "bolt11", "unit": "sat", "description": true},
                {"method": "bolt11", "unit": "usd", "description": true}
            ],
            "disabled": false
        },
        "5": {
            "methods": [
                {"method": "bolt11", "unit": "sat"},
                {"method": "bolt11", "unit": "usd"}
            ],
            "disabled": false
        },
        "7": {"supported": true},
        "8": {"supported": true},
        "9": {"supported": true},
        "10": {"supported": true},
        "11": {"supported": true}
    },
"tos_url": "https://cashu.mint/tos"
}"#;

        let _mint_info: MintInfo = serde_json::from_str(mint_info_str).unwrap();
    }

    #[test]
    fn test_ser_mint_info() {
        /*
                let mint_info = serde_json::to_string(&MintInfo {
                    name: Some("Cashu-crab".to_string()),
                    pubkey: None,
                    version: None,
                    description: Some("A mint".to_string()),
                    description_long: Some("Some longer test".to_string()),
                    contact: None,
                    nuts: Nuts::default(),
                    motd: None,
                })
                .unwrap();

                println!("{}", mint_info);
        */
        let mint_info_str = r#"
{
  "name": "Bob's Cashu mint",
  "pubkey": "0283bf290884eed3a7ca2663fc0260de2e2064d6b355ea13f98dec004b7a7ead99",
  "version": "Nutshell/0.15.0",
  "description": "The short mint description",
  "description_long": "A description that can be a long piece of text.",
  "contact": [
    {
        "method": "nostr",
        "info": "xxxxx"
    },
    {
        "method": "email",
        "info": "contact@me.com"
    }
  ],
  "motd": "Message to display to users.",
  "icon_url": "https://this-is-a-mint-icon-url.com/icon.png",
  "nuts": {
    "4": {
      "methods": [
        {
        "method": "bolt11",
        "unit": "sat",
        "min_amount": 0,
        "max_amount": 10000,
        "options": {
            "description": true
            }
        }
      ],
      "disabled": false
    },
    "5": {
      "methods": [
        {
        "method": "bolt11",
        "unit": "sat",
        "min_amount": 0,
        "max_amount": 10000
        }
      ],
      "disabled": false
    },
    "7": {"supported": true},
    "8": {"supported": true},
    "9": {"supported": true},
    "10": {"supported": true},
    "12": {"supported": true}
  },
  "tos_url": "https://cashu.mint/tos"
}"#;
        let info: MintInfo = serde_json::from_str(mint_info_str).unwrap();
        let mint_info_str = r#"
{
    "name": "Bob's Cashu mint",
    "pubkey": "0283bf290884eed3a7ca2663fc0260de2e2064d6b355ea13f98dec004b7a7ead99",
    "version": "Nutshell/0.15.0",
    "description": "The short mint description",
    "description_long": "A description that can be a long piece of text.",
    "contact": [
    ["nostr", "xxxxx"],
    ["email", "contact@me.com"]
        ],
        "motd": "Message to display to users.",
        "icon_url": "https://this-is-a-mint-icon-url.com/icon.png",
        "nuts": {
            "4": {
            "methods": [
                {
                "method": "bolt11",
                "unit": "sat",
                "min_amount": 0,
                "max_amount": 10000,
                "options": {
                     "description": true
                 }
                }
            ],
            "disabled": false
            },
            "5": {
            "methods": [
                {
                "method": "bolt11",
                "unit": "sat",
                "min_amount": 0,
                "max_amount": 10000
                }
            ],
            "disabled": false
            },
            "7": {"supported": true},
            "8": {"supported": true},
            "9": {"supported": true},
            "10": {"supported": true},
            "12": {"supported": true}
        },
        "tos_url": "https://cashu.mint/tos"
}"#;
        let mint_info: MintInfo = serde_json::from_str(mint_info_str).unwrap();

        let t = mint_info
            .nuts
            .nut04
            .get_settings(
                &crate::CurrencyUnit::Sat,
                &crate::PaymentMethod::Known(KnownMethod::Bolt11),
            )
            .unwrap();

        let t = t.options.unwrap();

        matches!(t, MintMethodOptions::Bolt11 { description: true });

        assert_eq!(info, mint_info);
    }

    #[test]
    fn test_nut15_not_serialized_when_empty() {
        // Test with default (empty) NUT15
        let mint_info = MintInfo {
            name: Some("Test Mint".to_string()),
            nuts: Nuts::default(),
            ..Default::default()
        };

        let json = serde_json::to_string(&mint_info).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        // NUT15 should not be present in the nuts object when methods is empty
        assert!(parsed["nuts"]["15"].is_null());

        // Test with non-empty NUT15
        let mint_info_with_nut15 = MintInfo {
            name: Some("Test Mint".to_string()),
            nuts: Nuts::default().nut15(vec![MppMethodSettings {
                method: crate::PaymentMethod::Known(KnownMethod::Bolt11),
                unit: crate::CurrencyUnit::Sat,
            }]),
            ..Default::default()
        };

        let json = serde_json::to_string(&mint_info_with_nut15).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        // NUT15 should be present when methods is not empty
        assert!(!parsed["nuts"]["15"].is_null());
        assert!(parsed["nuts"]["15"]["methods"].is_array());
        assert_eq!(parsed["nuts"]["15"]["methods"].as_array().unwrap().len(), 1);
    }
}