cashu 0.17.3

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
//! NUT-30 onchain payment method

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use super::nut00::{BlindSignature, BlindedMessage, CurrencyUnit};
use super::nut01::PublicKey;
use super::nut05::MeltRequest;
use super::MeltQuoteState;
#[cfg(feature = "mint")]
use crate::quote_id::QuoteId;
use crate::util::serde_helpers::deserialize_empty_string_as_none;
use crate::{Amount, Proofs};

/// Mint quote onchain request
///
/// Request for an onchain mint quote. Requires a pubkey (NUT-20).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MintQuoteOnchainRequest {
    /// Unit wallet would like to mint
    pub unit: CurrencyUnit,
    /// NUT-20 Pubkey (required)
    pub pubkey: PublicKey,
}

/// Mint quote onchain response
///
/// Response containing the onchain quote details.
///
/// Unknown fields are accepted to preserve forward compatibility when mints
/// add optional onchain extensions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "Q: Serialize + DeserializeOwned")]
pub struct MintQuoteOnchainResponse<Q> {
    /// Quote Id
    pub quote: Q,
    /// Bitcoin address to send funds to
    pub request: String,
    /// Unit
    pub unit: CurrencyUnit,
    /// Unix timestamp until the quote is valid
    pub expiry: Option<u64>,
    /// NUT-20 Pubkey from the request
    pub pubkey: PublicKey,
    /// Total confirmed amount paid to the request
    #[serde(default)]
    pub amount_paid: Amount,
    /// Amount of ecash that has been issued for the given mint quote
    #[serde(default)]
    pub amount_issued: Amount,
}

impl<Q: ToString> MintQuoteOnchainResponse<Q> {
    /// Convert the MintQuoteOnchainResponse with a quote type Q to a String
    pub fn to_string_id(&self) -> MintQuoteOnchainResponse<String> {
        MintQuoteOnchainResponse {
            quote: self.quote.to_string(),
            request: self.request.clone(),
            unit: self.unit.clone(),
            expiry: self.expiry,
            pubkey: self.pubkey,
            amount_paid: self.amount_paid,
            amount_issued: self.amount_issued,
        }
    }
}

#[cfg(feature = "mint")]
impl From<MintQuoteOnchainResponse<QuoteId>> for MintQuoteOnchainResponse<String> {
    fn from(value: MintQuoteOnchainResponse<QuoteId>) -> Self {
        Self {
            quote: value.quote.to_string(),
            request: value.request,
            unit: value.unit,
            expiry: value.expiry,
            pubkey: value.pubkey,
            amount_paid: value.amount_paid,
            amount_issued: value.amount_issued,
        }
    }
}

/// Melt quote onchain request
///
/// Request for an onchain melt quote.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MeltQuoteOnchainRequest {
    /// Bitcoin address to send to
    pub request: String,
    /// Unit wallet would like to pay with
    pub unit: CurrencyUnit,
    /// Amount to send in the specified unit
    pub amount: Amount,
}

/// Melt onchain request
///
/// Request to execute an onchain melt quote. The wallet selects one of the
/// quote's fee options by including that option's `fee_index` value.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "Q: Serialize + DeserializeOwned")]
pub struct MeltOnchainRequest<Q> {
    /// Quote ID
    pub quote: Q,
    /// Selected fee option index from the quote's `fee_options`
    pub fee_index: u32,
    /// Proofs
    pub inputs: Proofs,
    /// Blinded messages that can be used to return overpaid onchain fee reserve
    pub outputs: Option<Vec<BlindedMessage>>,
}

impl<Q> From<MeltOnchainRequest<Q>> for MeltRequest<Q>
where
    Q: Serialize + DeserializeOwned,
{
    fn from(request: MeltOnchainRequest<Q>) -> Self {
        MeltRequest::new(request.quote, request.inputs, request.outputs)
            .fee_index(request.fee_index)
    }
}

/// Fee option for an onchain melt quote.
///
/// Each item in an onchain melt quote's `fee_options` represents one
/// available fee reserve and confirmation estimate for the same payment. The wallet
/// selects one option when executing the quote by echoing its
/// `fee_index` value in the melt request.
///
/// The mint enforces these NUT rules on the `fee_options` list as a whole:
///
/// - MUST return at least one item.
/// - MUST NOT contain two items with the same `fee_index`.
/// - The list is fixed for the lifetime of the quote.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MeltQuoteOnchainFeeOption {
    /// Server-assigned identifier the wallet echoes back to select this option
    pub fee_index: u32,
    /// Maximum onchain transaction fee the mint may charge for this option
    pub fee_reserve: Amount,
    /// Estimated number of blocks until confirmation
    pub estimated_blocks: u32,
}

/// Melt quote onchain response
///
/// Response containing the onchain melt quote details.
/// The `POST /v1/melt/quote/onchain` endpoint returns one quote with one or
/// more `fee_options`. The wallet chooses one option when executing the quote.
///
/// Unknown fields are accepted to preserve forward compatibility when mints
/// add optional onchain extensions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "Q: Serialize + DeserializeOwned")]
pub struct MeltQuoteOnchainResponse<Q> {
    /// Quote Id
    pub quote: Q,
    /// Amount to be melted
    pub amount: Amount,
    /// Unit
    pub unit: CurrencyUnit,
    /// Quote state
    pub state: MeltQuoteState,
    /// Unix timestamp until the quote is valid
    pub expiry: u64,
    /// Bitcoin address to send to
    pub request: String,
    /// Fee options for the transaction.
    ///
    /// Each entry represents one fee-reserve/confirmation-target pair the mint is
    /// willing to honor for this quote. Per NUT the mint MUST return at
    /// least one entry; MUST NOT return multiple entries with the same
    /// `fee_index`; and the list is fixed for the lifetime of the quote.
    pub fee_options: Vec<MeltQuoteOnchainFeeOption>,
    /// Selected fee option index once the quote is executed
    pub selected_fee_index: Option<u32>,
    /// Transaction outpoint (txid:vout) once broadcast
    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
    pub outpoint: Option<String>,
    /// Blind signatures for overpaid onchain fee reserve
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub change: Option<Vec<BlindSignature>>,
}

impl<Q: ToString> MeltQuoteOnchainResponse<Q> {
    /// Convert the MeltQuoteOnchainResponse with a quote type Q to a String
    pub fn to_string_id(&self) -> MeltQuoteOnchainResponse<String> {
        MeltQuoteOnchainResponse {
            quote: self.quote.to_string(),
            amount: self.amount,
            unit: self.unit.clone(),
            state: self.state,
            expiry: self.expiry,
            request: self.request.clone(),
            fee_options: self.fee_options.clone(),
            selected_fee_index: self.selected_fee_index,
            outpoint: self.outpoint.clone(),
            change: self.change.clone(),
        }
    }
}

#[cfg(feature = "mint")]
impl From<MeltQuoteOnchainResponse<QuoteId>> for MeltQuoteOnchainResponse<String> {
    fn from(value: MeltQuoteOnchainResponse<QuoteId>) -> Self {
        Self {
            quote: value.quote.to_string(),
            amount: value.amount,
            unit: value.unit,
            state: value.state,
            expiry: value.expiry,
            request: value.request,
            fee_options: value.fee_options,
            selected_fee_index: value.selected_fee_index,
            outpoint: value.outpoint,
            change: value.change,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mint_quote_onchain_request_serialization() {
        let request = MintQuoteOnchainRequest {
            unit: CurrencyUnit::Sat,
            pubkey: PublicKey::from_hex(
                "03d56ce4e446a85bbdaa547b4ec2b073d40ff802831352b8272b7dd7a4de5a7cac",
            )
            .unwrap(),
        };

        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: MintQuoteOnchainRequest = serde_json::from_str(&serialized).unwrap();

        assert_eq!(request.unit, deserialized.unit);
        assert_eq!(request.pubkey, deserialized.pubkey);
    }

    #[test]
    fn test_melt_quote_onchain_request_serialization() {
        let request = MeltQuoteOnchainRequest {
            request: "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh".to_string(),
            unit: CurrencyUnit::Sat,
            amount: Amount::from(1000),
        };

        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: MeltQuoteOnchainRequest = serde_json::from_str(&serialized).unwrap();

        assert_eq!(request.request, deserialized.request);
        assert_eq!(request.unit, deserialized.unit);
        assert_eq!(request.amount, deserialized.amount);
    }

    #[test]
    fn test_melt_quote_onchain_response_serialization() {
        let response: MeltQuoteOnchainResponse<String> = MeltQuoteOnchainResponse {
            quote: "TRmjduhIsPxd...".to_string(),
            amount: Amount::from(100000),
            unit: CurrencyUnit::Sat,
            state: MeltQuoteState::Pending,
            expiry: 1701704757,
            request: "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh".to_string(),
            fee_options: vec![MeltQuoteOnchainFeeOption {
                fee_index: 0,
                fee_reserve: Amount::from(5000),
                estimated_blocks: 1,
            }],
            selected_fee_index: Some(0),
            outpoint: Some(
                "3b7f3b85c5f1a3c4d2b8e9f6a7c5d8e9f1a2b3c4d5e6f7a8b9c1d2e3f4a5b6c7:2".to_string(),
            ),
            change: None,
        };

        let serialized = serde_json::to_string(&response).unwrap();
        assert!(serialized.contains("\"fee_reserve\""));
        assert!(serialized.contains("\"fee_index\""));
        assert!(!serialized.contains("\"fee\":"));

        let deserialized: MeltQuoteOnchainResponse<String> =
            serde_json::from_str(&serialized).unwrap();

        assert_eq!(response.quote, deserialized.quote);
        assert_eq!(response.request, deserialized.request);
        assert_eq!(response.amount, deserialized.amount);
        assert_eq!(response.fee_options, deserialized.fee_options);
        assert_eq!(response.selected_fee_index, deserialized.selected_fee_index);
        assert_eq!(response.state, deserialized.state);
        assert_eq!(response.outpoint, deserialized.outpoint);
        assert_eq!(response.change, deserialized.change);
    }

    #[test]
    fn test_melt_quote_onchain_response_serializes_null_outpoint() {
        let response: MeltQuoteOnchainResponse<String> = MeltQuoteOnchainResponse {
            quote: "TRmjduhIsPxd...".to_string(),
            amount: Amount::from(100000),
            unit: CurrencyUnit::Sat,
            state: MeltQuoteState::Pending,
            expiry: 1701704757,
            request: "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh".to_string(),
            fee_options: vec![MeltQuoteOnchainFeeOption {
                fee_index: 0,
                fee_reserve: Amount::from(5000),
                estimated_blocks: 1,
            }],
            selected_fee_index: None,
            outpoint: None,
            change: None,
        };

        let serialized = serde_json::to_string(&response).unwrap();
        assert!(serialized.contains("\"outpoint\":null"));

        let deserialized: MeltQuoteOnchainResponse<String> =
            serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized.outpoint, None);
    }

    #[test]
    fn test_mint_quote_onchain_response_tolerates_unknown_fields() {
        // Responses from newer mints may carry additional optional fields
        // (e.g. payjoin instructions); released wallets must not reject them.
        let encoded = r#"{
            "quote": "DSGLX9kevM...",
            "request": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
            "unit": "sat",
            "expiry": 1701704757,
            "pubkey": "03d56ce4e446a85bbdaa547b4ec2b073d40ff802831352b8272b7dd7a4de5a7cac",
            "amount_paid": 100000,
            "amount_issued": 0,
            "payjoin": {"endpoint": "https://payjoin.example/pj"}
        }"#;

        let deserialized: MintQuoteOnchainResponse<String> = serde_json::from_str(encoded).unwrap();
        assert_eq!(deserialized.quote, "DSGLX9kevM...");
        assert_eq!(deserialized.amount_paid, Amount::from(100000));
    }

    #[test]
    fn test_melt_quote_onchain_response_tolerates_unknown_fields() {
        let encoded = r#"{
            "quote": "TRmjduhIsPxd...",
            "amount": 100000,
            "unit": "sat",
            "state": "PENDING",
            "expiry": 1701704757,
            "request": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
            "fee_options": [{"fee_index": 0, "fee_reserve": 5000, "estimated_blocks": 1}],
            "selected_fee_index": null,
            "outpoint": null,
            "payjoin": {"endpoint": "https://payjoin.example/pj"}
        }"#;

        let deserialized: MeltQuoteOnchainResponse<String> = serde_json::from_str(encoded).unwrap();
        assert_eq!(deserialized.quote, "TRmjduhIsPxd...");
        assert_eq!(deserialized.state, MeltQuoteState::Pending);
    }

    #[test]
    fn test_mint_quote_onchain_response_to_string_id() {
        use crate::nuts::nut00::CurrencyUnit;
        use crate::nuts::nut01::PublicKey;
        use crate::Amount;

        let response: MintQuoteOnchainResponse<String> = MintQuoteOnchainResponse {
            quote: "DSGLX9kevM...".to_string(),
            request: "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh".to_string(),
            unit: CurrencyUnit::Sat,
            expiry: Some(1701704757),
            pubkey: PublicKey::from_hex(
                "03d56ce4e446a85bbdaa547b4ec2b073d40ff802831352b8272b7dd7a4de5a7cac",
            )
            .unwrap(),
            amount_paid: Amount::from(100000),
            amount_issued: Amount::from(0),
        };

        let string_id_response = response.to_string_id();
        assert_eq!(string_id_response.quote, "DSGLX9kevM...");
    }

    #[test]
    fn test_melt_quote_onchain_response_to_string_id() {
        use crate::nuts::nut00::CurrencyUnit;
        use crate::Amount;

        let response: MeltQuoteOnchainResponse<String> = MeltQuoteOnchainResponse {
            quote: "TRmjduhIsPxd...".to_string(),
            amount: Amount::from(100000),
            unit: CurrencyUnit::Sat,
            state: MeltQuoteState::Pending,
            expiry: 1701704757,
            request: "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh".to_string(),
            fee_options: vec![MeltQuoteOnchainFeeOption {
                fee_index: 0,
                fee_reserve: Amount::from(5000),
                estimated_blocks: 1,
            }],
            selected_fee_index: Some(0),
            outpoint: Some(
                "3b7f3b85c5f1a3c4d2b8e9f6a7c5d8e9f1a2b3c4d5e6f7a8b9c1d2e3f4a5b6c7:2".to_string(),
            ),
            change: None,
        };

        let string_id_response = response.to_string_id();
        assert_eq!(string_id_response.quote, "TRmjduhIsPxd...");
    }
}