cashu 0.17.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
//! NUT-10: Spending Conditions
//!
//! <https://github.com/cashubtc/nuts/blob/main/10.md>

use std::collections::HashSet;
use std::str::FromStr;

use bitcoin::hashes::sha256::Hash as Sha256Hash;
use serde::{Deserialize, Serialize};

use crate::nut10::{Error, Tag};
use crate::secret::Secret;
use crate::util::unix_time;
use crate::{ensure_cdk, nut14, Kind, Nut10Secret, PublicKey, SigFlag};

/// Spending Conditions
///
/// Defined in [NUT10](https://github.com/cashubtc/nuts/blob/main/10.md)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SpendingConditions {
    /// NUT11 Spending conditions
    ///
    /// Defined in [NUT11](https://github.com/cashubtc/nuts/blob/main/11.md)
    P2PKConditions {
        /// The public key of the recipient of the locked ecash
        data: PublicKey,
        /// Additional Optional Spending [`Conditions`]
        conditions: Option<Conditions>,
    },
    /// NUT14 Spending conditions
    ///
    /// Dedined in [NUT14](https://github.com/cashubtc/nuts/blob/main/14.md)
    HTLCConditions {
        /// Hash Lock of ecash
        data: Sha256Hash,
        /// Additional Optional Spending [`Conditions`]
        conditions: Option<Conditions>,
    },
}

impl SpendingConditions {
    /// Kind of [SpendingConditions]
    pub fn kind(&self) -> Kind {
        match self {
            Self::P2PKConditions { .. } => Kind::P2PK,
            Self::HTLCConditions { .. } => Kind::HTLC,
        }
    }

    /// Number if signatures required to unlock
    pub fn num_sigs(&self) -> Option<u64> {
        match self {
            Self::P2PKConditions { conditions, .. } => conditions.as_ref().and_then(|c| c.num_sigs),
            Self::HTLCConditions { conditions, .. } => conditions.as_ref().and_then(|c| c.num_sigs),
        }
    }

    /// Public keys of locked
    pub fn pubkeys(&self) -> Option<Vec<PublicKey>> {
        match self {
            Self::P2PKConditions { data, conditions } => {
                let mut pubkeys = vec![*data];
                if let Some(conditions) = conditions {
                    pubkeys.extend(conditions.pubkeys.clone().unwrap_or_default());
                }
                // Remove duplicates
                let unique_pubkeys: HashSet<_> = pubkeys.into_iter().collect();
                Some(unique_pubkeys.into_iter().collect())
            }
            Self::HTLCConditions { conditions, .. } => conditions.clone().and_then(|c| c.pubkeys),
        }
    }

    /// Locktime of Spending Conditions
    pub fn locktime(&self) -> Option<u64> {
        match self {
            Self::P2PKConditions { conditions, .. } => conditions.as_ref().and_then(|c| c.locktime),
            Self::HTLCConditions { conditions, .. } => conditions.as_ref().and_then(|c| c.locktime),
        }
    }

    /// Refund keys
    pub fn refund_keys(&self) -> Option<Vec<PublicKey>> {
        match self {
            Self::P2PKConditions { conditions, .. } => {
                conditions.clone().and_then(|c| c.refund_keys)
            }
            Self::HTLCConditions { conditions, .. } => {
                conditions.clone().and_then(|c| c.refund_keys)
            }
        }
    }
}

impl TryFrom<&Secret> for SpendingConditions {
    type Error = Error;
    fn try_from(secret: &Secret) -> Result<SpendingConditions, Error> {
        let nut10_secret: Nut10Secret = secret.try_into()?;

        nut10_secret.try_into()
    }
}

impl TryFrom<Nut10Secret> for SpendingConditions {
    type Error = Error;
    fn try_from(secret: Nut10Secret) -> Result<SpendingConditions, Error> {
        match secret.kind() {
            Kind::P2PK => Ok(SpendingConditions::P2PKConditions {
                data: PublicKey::from_str(secret.secret_data().data())?,
                conditions: secret
                    .secret_data()
                    .tags()
                    .cloned()
                    .map(Conditions::try_from)
                    .transpose()?,
            }),
            Kind::HTLC => Ok(Self::HTLCConditions {
                data: Sha256Hash::from_str(secret.secret_data().data())
                    .map_err(|_| Error::NUT14(nut14::Error::InvalidHash))?,
                conditions: secret
                    .secret_data()
                    .tags()
                    .cloned()
                    .map(Conditions::try_from)
                    .transpose()?,
            }),
        }
    }
}

impl From<SpendingConditions> for super::Secret {
    fn from(conditions: SpendingConditions) -> super::Secret {
        match conditions {
            SpendingConditions::P2PKConditions { data, conditions } => super::Secret::new(
                Kind::P2PK,
                super::SecretData::new(data.to_hex(), conditions),
            ),
            SpendingConditions::HTLCConditions { data, conditions } => super::Secret::new(
                Kind::HTLC,
                super::SecretData::new(data.to_string(), conditions),
            ),
        }
    }
}

impl TryFrom<SpendingConditions> for Secret {
    type Error = Error;
    fn try_from(conditions: SpendingConditions) -> Result<Secret, Self::Error> {
        conditions.validate()?;
        let secret: Nut10Secret = conditions.into();
        Secret::try_from(secret)
    }
}

/// P2PK and HTLC spending conditions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct Conditions {
    /// Unix locktime after which refund keys can be used
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locktime: Option<u64>,
    /// Additional Public keys
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pubkeys: Option<Vec<PublicKey>>,
    /// Refund keys
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refund_keys: Option<Vec<PublicKey>>,
    /// Number of signatures required
    ///
    /// Default is 1
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_sigs: Option<u64>,
    /// Signature flag
    ///
    /// Default [`SigFlag::SigInputs`]
    pub sig_flag: SigFlag,
    /// Number of refund signatures required
    ///
    /// Default is 1
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_sigs_refund: Option<u64>,
}

impl Conditions {
    fn validate(&self, primary_key_count: u64) -> Result<(), Error> {
        if let Some(n) = self.num_sigs {
            if n == 0 {
                return Err(Error::NUT11(crate::nut11::Error::ZeroSignaturesRequired));
            }

            let available_keys =
                primary_key_count + self.pubkeys.as_ref().map(Vec::len).unwrap_or(0) as u64;
            if n > available_keys {
                return Err(Error::NUT11(
                    crate::nut11::Error::ImpossibleMultisigConfiguration {
                        required: n,
                        available: available_keys,
                    },
                ));
            }
        }

        match (&self.refund_keys, self.num_sigs_refund) {
            (Some(_), Some(0)) => {
                return Err(Error::NUT11(crate::nut11::Error::ZeroSignaturesRequired));
            }
            (Some(refund_keys), Some(required)) if required > refund_keys.len() as u64 => {
                return Err(Error::NUT11(
                    crate::nut11::Error::ImpossibleRefundMultisigConfiguration {
                        required,
                        available: refund_keys.len() as u64,
                    },
                ));
            }
            (None, Some(0)) => {
                return Err(Error::NUT11(crate::nut11::Error::ZeroSignaturesRequired));
            }
            (None, Some(required)) => {
                return Err(Error::NUT11(
                    crate::nut11::Error::ImpossibleRefundMultisigConfiguration {
                        required,
                        available: 0,
                    },
                ));
            }
            (Some(refund_keys), None) if refund_keys.is_empty() => {
                return Err(Error::NUT11(
                    crate::nut11::Error::ImpossibleRefundMultisigConfiguration {
                        required: 1,
                        available: 0,
                    },
                ));
            }
            _ => {}
        }

        Ok(())
    }

    /// Create new Spending [`Conditions`]
    pub fn new(
        locktime: Option<u64>,
        pubkeys: Option<Vec<PublicKey>>,
        refund_keys: Option<Vec<PublicKey>>,
        num_sigs: Option<u64>,
        sig_flag: Option<SigFlag>,
        num_sigs_refund: Option<u64>,
    ) -> Result<Self, Error> {
        if let Some(locktime) = locktime {
            ensure_cdk!(
                locktime.ge(&unix_time()),
                Error::NUT11(crate::nut11::Error::LocktimeInPast)
            );
        }

        let conditions = Self {
            locktime,
            pubkeys,
            refund_keys,
            num_sigs,
            sig_flag: sig_flag.unwrap_or_default(),
            num_sigs_refund,
        };
        conditions.validate(1)?;

        Ok(conditions)
    }
}

impl SpendingConditions {
    fn validate(&self) -> Result<(), Error> {
        match self {
            Self::P2PKConditions { conditions, .. } => {
                if let Some(conditions) = conditions {
                    conditions.validate(1)?;
                }
            }
            Self::HTLCConditions { conditions, .. } => {
                if let Some(conditions) = conditions {
                    conditions.validate(0)?;
                }
            }
        }

        Ok(())
    }
}

impl From<Conditions> for Vec<Vec<String>> {
    fn from(conditions: Conditions) -> Vec<Vec<String>> {
        let Conditions {
            locktime,
            pubkeys,
            refund_keys,
            num_sigs,
            sig_flag,
            num_sigs_refund,
        } = conditions;

        let mut tags = Vec::new();

        if let Some(pubkeys) = pubkeys {
            tags.push(Tag::PubKeys(pubkeys.into_iter().collect()).as_vec());
        }

        if let Some(locktime) = locktime {
            tags.push(Tag::LockTime(locktime).as_vec());
        }

        if let Some(num_sigs) = num_sigs {
            tags.push(Tag::NSigs(num_sigs).as_vec());
        }

        if let Some(refund_keys) = refund_keys.filter(|keys| !keys.is_empty()) {
            tags.push(Tag::Refund(refund_keys).as_vec())
        }

        if let Some(num_sigs_refund) = num_sigs_refund {
            tags.push(Tag::NSigsRefund(num_sigs_refund).as_vec())
        }

        tags.push(Tag::SigFlag(sig_flag).as_vec());
        tags
    }
}

impl TryFrom<Vec<Vec<String>>> for Conditions {
    type Error = Error;
    fn try_from(tags: Vec<Vec<String>>) -> Result<Conditions, Self::Error> {
        let mut locktime = None;
        let mut pubkeys = None;
        let mut refund_keys = None;
        let mut sig_flag = None;
        let mut num_sigs = None;
        let mut num_sigs_refund = None;

        for tag_vec in tags {
            let tag = Tag::try_from(tag_vec)?;
            match tag {
                Tag::LockTime(lt) => {
                    if locktime.is_none() {
                        locktime = Some(lt);
                    }
                }
                Tag::PubKeys(pks) => {
                    if pubkeys.is_none() {
                        pubkeys = Some(pks);
                    }
                }
                Tag::Refund(keys) => {
                    if refund_keys.is_none() {
                        refund_keys = Some(keys);
                    }
                }
                Tag::SigFlag(sf) => {
                    if sig_flag.is_none() {
                        sig_flag = Some(sf);
                    }
                }
                Tag::NSigs(sigs) => {
                    if num_sigs.is_none() {
                        num_sigs = Some(sigs);
                    }
                }
                Tag::NSigsRefund(sigs) => {
                    if num_sigs_refund.is_none() {
                        num_sigs_refund = Some(sigs);
                    }
                }
                Tag::Custom(_, _) => {}
            }
        }

        if let Some(0) = num_sigs {
            return Err(Error::NUT11(crate::nut11::Error::ZeroSignaturesRequired));
        }
        if let Some(0) = num_sigs_refund {
            return Err(Error::NUT11(crate::nut11::Error::ZeroSignaturesRequired));
        }

        if let Some(refund_keys) = &refund_keys {
            let required = num_sigs_refund.unwrap_or(1);
            if required > refund_keys.len() as u64 {
                return Err(Error::NUT11(
                    crate::nut11::Error::ImpossibleRefundMultisigConfiguration {
                        required,
                        available: refund_keys.len() as u64,
                    },
                ));
            }
        } else if let Some(required) = num_sigs_refund {
            return Err(Error::NUT11(
                crate::nut11::Error::ImpossibleRefundMultisigConfiguration {
                    required,
                    available: 0,
                },
            ));
        }

        Ok(Conditions {
            locktime,
            pubkeys,
            refund_keys,
            num_sigs,
            sig_flag: sig_flag.unwrap_or_default(),
            num_sigs_refund,
        })
    }
}

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

    use super::*;
    use crate::nut01::PublicKey;

    #[test]
    fn test_duplicate_tags_first_match() {
        let pk1 = "026562efcfadc8e86d44da6a8adf80633d974302e62c850774db1fb36ff4cc7198";
        let pk2 = "02a4ed09e9b22c0563f2043593902973d040054ff03be93c990264177d65123982";

        let tags = vec![
            vec!["locktime".to_string(), "100".to_string()],
            vec!["locktime".to_string(), "1".to_string()],
            vec!["n_sigs".to_string(), "2".to_string()],
            vec!["n_sigs".to_string(), "1".to_string()],
            vec!["sigflag".to_string(), "SIG_ALL".to_string()],
            vec!["sigflag".to_string(), "SIG_INPUTS".to_string()],
            vec!["pubkeys".to_string(), pk1.to_string()],
            vec!["pubkeys".to_string(), pk2.to_string()],
            vec!["refund".to_string(), pk1.to_string()],
            vec!["refund".to_string(), pk2.to_string()],
        ];

        let conditions = Conditions::try_from(tags).unwrap();

        // Verify first-match semantics
        assert_eq!(conditions.locktime, Some(100));
        assert_eq!(conditions.num_sigs, Some(2));
        assert_eq!(conditions.sig_flag, crate::SigFlag::SigAll);
        assert_eq!(
            conditions.pubkeys,
            Some(vec![PublicKey::from_str(pk1).unwrap()])
        );
        assert_eq!(
            conditions.refund_keys,
            Some(vec![PublicKey::from_str(pk1).unwrap()])
        );
    }

    #[test]
    fn test_empty_refund_tag_is_rejected() {
        let tags = vec![
            vec!["refund".to_string()],
            vec!["sigflag".to_string(), "SIG_INPUTS".to_string()],
        ];

        let result = Conditions::try_from(tags);

        assert!(matches!(
            result,
            Err(Error::NUT11(
                crate::nut11::Error::ImpossibleRefundMultisigConfiguration {
                    required: 1,
                    available: 0
                }
            ))
        ));
    }

    #[test]
    fn test_empty_refund_keys_are_not_serialized() {
        let conditions = Conditions {
            locktime: Some(1),
            pubkeys: None,
            refund_keys: Some(vec![]),
            num_sigs: None,
            sig_flag: crate::SigFlag::default(),
            num_sigs_refund: None,
        };

        let tags = Vec::<Vec<String>>::from(conditions);

        assert!(!tags
            .iter()
            .any(|tag| tag.first() == Some(&"refund".to_string())));
    }

    #[test]
    fn test_n_sigs_refund_without_refund_keys_is_rejected() {
        let tags = vec![
            vec!["n_sigs_refund".to_string(), "1".to_string()],
            vec!["sigflag".to_string(), "SIG_INPUTS".to_string()],
        ];

        let result = Conditions::try_from(tags);

        assert!(matches!(
            result,
            Err(Error::NUT11(
                crate::nut11::Error::ImpossibleRefundMultisigConfiguration {
                    required: 1,
                    available: 0
                }
            ))
        ));
    }

    #[test]
    fn test_spending_conditions_try_from_propagates_invalid_tags() {
        let pubkey = PublicKey::from_str(
            "026562efcfadc8e86d44da6a8adf80633d974302e62c850774db1fb36ff4cc7198",
        )
        .unwrap();
        let nut10_secret = Nut10Secret::new(
            Kind::P2PK,
            crate::nuts::nut10::SecretData::new(
                pubkey.to_string(),
                Some(vec![vec!["n_sigs".to_string(), "0".to_string()]]),
            ),
        );

        let result = SpendingConditions::try_from(nut10_secret);

        assert!(matches!(
            result,
            Err(Error::NUT11(crate::nut11::Error::ZeroSignaturesRequired))
        ));
    }
}