cdk-spilman 0.17.6

Standalone Spilman payment channels library for Cashu
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
use super::*;

impl<H: SpilmanHost<C>, C> SpilmanBridge<H, C> {
    pub fn new(host: H) -> Self {
        Self {
            host,
            _phantom: std::marker::PhantomData,
        }
    }
    pub fn host(&self) -> &H {
        &self.host
    }

    fn decode_payment_header(base64_header: &str) -> Result<Payment, BridgeError> {
        let decoded = BASE64
            .decode(base64_header)
            .map_err(|e| BridgeError::InvalidRequest(e.to_string()))?;
        let json =
            String::from_utf8(decoded).map_err(|e| BridgeError::InvalidRequest(e.to_string()))?;
        serde_json::from_str(&json).map_err(|e| BridgeError::InvalidRequest(e.to_string()))
    }

    pub fn process_payment(
        &self,
        channel_id: &str,
        balance: u64,
        signature: &str,
        params: Option<&serde_json::Value>,
        funding_proofs: Option<&[Proof]>,
        context: &C,
    ) -> Result<PaymentSuccess, BridgeError> {
        if self.host.get_channel_state(channel_id) == ChannelState::Closing {
            return self.refresh_closing_payment(channel_id, balance, signature, context);
        }
        let val = self.validate_payment(
            channel_id,
            balance,
            signature,
            params,
            funding_proofs,
            context,
        )?;
        self.host
            .record_payment(
                &val.channel_id,
                PaymentProof {
                    balance: val.balance,
                    signature: val.sender_signature.clone(),
                },
                context,
            )
            .map_err(|e| {
                BridgeError::Internal(format!("record payment persistence failed: {e}"))
            })?;
        Ok(PaymentSuccess {
            channel_id: val.channel_id,
            balance: val.balance,
            amount_due: val.amount_due,
            capacity: val.capacity,
        })
    }

    fn refresh_closing_payment(
        &self,
        channel_id: &str,
        balance: u64,
        signature: &str,
        context: &C,
    ) -> Result<PaymentSuccess, BridgeError> {
        if channel_id.is_empty() {
            return Err(BridgeError::InvalidRequest("missing channel_id".into()));
        }
        if signature.is_empty() {
            return Err(BridgeError::InvalidRequest("missing signature".into()));
        }
        let closing = self
            .host
            .get_closing_data(channel_id)
            .ok_or_else(|| BridgeError::Internal("closing channel has no close data".into()))?;
        if balance != closing.balance {
            return Err(BridgeError::BalanceMismatch {
                expected: closing.balance,
                actual: balance,
            });
        }
        let funding = self
            .host
            .get_funding(channel_id)
            .ok_or(BridgeError::UnknownChannel)?;
        self.verify_signature(
            &funding.params_json,
            &funding.funding_proofs_json,
            &funding.channel_secret_hex,
            &funding.keyset_info_json,
            channel_id,
            balance,
            signature,
        )
        .map_err(BridgeError::InvalidSignature)?;
        if crate::balance_update::parse_sig_all_signature_bundle(signature)
            .map_err(BridgeError::InvalidSignature)?
            .nutshell_0_20
            .is_none()
        {
            return Err(BridgeError::InvalidSignature(
                "closing-channel refresh requires a compatibility signature".into(),
            ));
        }

        self.host
            .mark_channel_closing(
                channel_id,
                closing.expiry_timestamp,
                PaymentProof {
                    balance,
                    signature: signature.to_string(),
                },
            )
            .map_err(|error| {
                BridgeError::Internal(format!("closing payment persistence failed: {error}"))
            })?;

        let params: serde_json::Value = serde_json::from_str(&funding.params_json)
            .map_err(|error| BridgeError::Internal(error.to_string()))?;
        Ok(PaymentSuccess {
            channel_id: channel_id.to_string(),
            balance,
            amount_due: self.host.get_amount_due(channel_id, Some(context)),
            capacity: params["capacity"].as_u64().unwrap_or(0),
        })
    }

    pub fn process_payment_via_json(
        &self,
        payment_json: &str,
        context: &C,
    ) -> Result<PaymentSuccess, BridgeError> {
        let p: Payment = serde_json::from_str(payment_json)
            .map_err(|e| BridgeError::InvalidRequest(e.to_string()))?;
        self.process_payment(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
            context,
        )
    }

    pub fn process_payment_via_base64_header(
        &self,
        base64_header: &str,
        context: &C,
    ) -> Result<PaymentSuccess, BridgeError> {
        let p = Self::decode_payment_header(base64_header)?;
        self.process_payment(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
            context,
        )
    }

    pub fn validate_payment(
        &self,
        channel_id: &str,
        balance: u64,
        signature: &str,
        params: Option<&serde_json::Value>,
        funding_proofs: Option<&[Proof]>,
        context: &C,
    ) -> Result<PaymentValidationResult, BridgeError> {
        if channel_id.is_empty() {
            return Err(BridgeError::InvalidRequest("missing channel_id".into()));
        }
        if signature.is_empty() {
            return Err(BridgeError::InvalidRequest("missing signature".into()));
        }
        match self.host.get_channel_state(channel_id) {
            ChannelState::Closed => return Err(BridgeError::ChannelClosed),
            ChannelState::Closing => return Err(BridgeError::ChannelClosing),
            ChannelState::Open => {}
        }
        let (funding, is_new) = match self.host.get_funding(channel_id) {
            Some(f) => (f, false),
            None => (
                self.validate_and_save_new_channel(
                    channel_id,
                    params.ok_or(BridgeError::UnknownChannel)?,
                    funding_proofs.ok_or(BridgeError::UnknownChannel)?,
                    balance,
                    signature,
                )?,
                true,
            ),
        };
        let params_val: serde_json::Value = serde_json::from_str(&funding.params_json)
            .map_err(|e| BridgeError::Internal(e.to_string()))?;
        let capacity = params_val["capacity"].as_u64().unwrap_or(0);
        if !is_new {
            if balance > capacity {
                return Err(BridgeError::BalanceExceedsCapacity { balance, capacity });
            }
            self.verify_signature(
                &funding.params_json,
                &funding.funding_proofs_json,
                &funding.channel_secret_hex,
                &funding.keyset_info_json,
                channel_id,
                balance,
                signature,
            )
            .map_err(BridgeError::InvalidSignature)?;
        }
        let amount_due = self.host.get_amount_due(channel_id, Some(context));
        if balance < amount_due {
            return Err(BridgeError::InsufficientBalance {
                balance,
                amount_due,
            });
        }
        Ok(PaymentValidationResult {
            channel_id: channel_id.to_string(),
            balance,
            amount_due,
            capacity,
            sender_signature: signature.to_string(),
        })
    }

    pub fn validate_payment_via_json(
        &self,
        payment_json: &str,
        context: &C,
    ) -> Result<PaymentValidationResult, BridgeError> {
        let p: Payment = serde_json::from_str(payment_json)
            .map_err(|e| BridgeError::InvalidRequest(e.to_string()))?;
        self.validate_payment(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
            context,
        )
    }

    pub fn validate_payment_via_base64_header(
        &self,
        base64_header: &str,
        context: &C,
    ) -> Result<PaymentValidationResult, BridgeError> {
        let p = Self::decode_payment_header(base64_header)?;
        self.validate_payment(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
            context,
        )
    }

    /// Verify that a payment covers the current amount due.
    ///
    /// This performs full validation (including signature checks) and returns the
    /// computed amount_due on success. It does NOT record usage, but may save
    /// funding data for new channels (same behavior as validate_payment).
    pub fn verify_payment_covers_amount_due(
        &self,
        channel_id: &str,
        balance: u64,
        signature: &str,
        params: Option<&serde_json::Value>,
        funding_proofs: Option<&[Proof]>,
        context: &C,
    ) -> Result<u64, BridgeError> {
        let val = self.validate_payment(
            channel_id,
            balance,
            signature,
            params,
            funding_proofs,
            context,
        )?;
        Ok(val.amount_due)
    }

    pub fn verify_payment_covers_amount_due_via_json(
        &self,
        payment_json: &str,
        context: &C,
    ) -> Result<u64, BridgeError> {
        let p: Payment = serde_json::from_str(payment_json)
            .map_err(|e| BridgeError::InvalidRequest(e.to_string()))?;
        self.verify_payment_covers_amount_due(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
            context,
        )
    }

    pub fn verify_payment_covers_amount_due_via_base64_header(
        &self,
        base64_header: &str,
        context: &C,
    ) -> Result<u64, BridgeError> {
        let p = Self::decode_payment_header(base64_header)?;
        self.verify_payment_covers_amount_due(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
            context,
        )
    }

    /// Return true if the payment covers the amount due.
    ///
    /// Returns Ok(false) only for insufficient balance. Other validation errors
    /// are returned as Err.
    pub fn payment_covers_amount_due(
        &self,
        channel_id: &str,
        balance: u64,
        signature: &str,
        params: Option<&serde_json::Value>,
        funding_proofs: Option<&[Proof]>,
        context: &C,
    ) -> Result<bool, BridgeError> {
        match self.verify_payment_covers_amount_due(
            channel_id,
            balance,
            signature,
            params,
            funding_proofs,
            context,
        ) {
            Ok(_) => Ok(true),
            Err(BridgeError::InsufficientBalance { .. }) => Ok(false),
            Err(e) => Err(e),
        }
    }

    pub fn payment_covers_amount_due_via_json(
        &self,
        payment_json: &str,
        context: &C,
    ) -> Result<bool, BridgeError> {
        let p: Payment = serde_json::from_str(payment_json)
            .map_err(|e| BridgeError::InvalidRequest(e.to_string()))?;
        self.payment_covers_amount_due(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
            context,
        )
    }

    pub fn payment_covers_amount_due_via_base64_header(
        &self,
        base64_header: &str,
        context: &C,
    ) -> Result<bool, BridgeError> {
        let p = Self::decode_payment_header(base64_header)?;
        self.payment_covers_amount_due(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
            context,
        )
    }

    pub fn fund_channel(
        &self,
        channel_id: &str,
        balance: u64,
        signature: &str,
        params: Option<&serde_json::Value>,
        funding_proofs: Option<&[Proof]>,
    ) -> Result<FundChannelResult, BridgeError> {
        if channel_id.is_empty() {
            return Err(BridgeError::InvalidRequest("missing channel_id".into()));
        }
        if signature.is_empty() {
            return Err(BridgeError::InvalidRequest("missing signature".into()));
        }
        match self.host.get_channel_state(channel_id) {
            ChannelState::Closed => return Err(BridgeError::ChannelClosed),
            ChannelState::Closing => return Err(BridgeError::ChannelClosing),
            ChannelState::Open => {}
        }
        let (funding, already_known) = match self.host.get_funding(channel_id) {
            Some(f) => (f, true),
            None => (
                self.validate_and_save_new_channel(
                    channel_id,
                    params.ok_or(BridgeError::InvalidRequest("Missing params".into()))?,
                    funding_proofs.ok_or(BridgeError::InvalidRequest("Missing proofs".into()))?,
                    balance,
                    signature,
                )?,
                false,
            ),
        };
        let params_val: serde_json::Value = serde_json::from_str(&funding.params_json)
            .map_err(|e| BridgeError::Internal(e.to_string()))?;
        let capacity = params_val["capacity"].as_u64().unwrap_or(0);
        if already_known {
            self.verify_signature(
                &funding.params_json,
                &funding.funding_proofs_json,
                &funding.channel_secret_hex,
                &funding.keyset_info_json,
                channel_id,
                balance,
                signature,
            )
            .map_err(BridgeError::InvalidSignature)?;
        }
        Ok(FundChannelResult {
            channel_id: channel_id.to_string(),
            capacity,
            already_known,
        })
    }

    pub fn fund_channel_via_json(&self, json: &str) -> Result<FundChannelResult, BridgeError> {
        let p: Payment =
            serde_json::from_str(json).map_err(|e| BridgeError::InvalidRequest(e.to_string()))?;
        self.fund_channel(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
        )
    }

    pub fn fund_channel_via_base64_header(
        &self,
        base64_header: &str,
    ) -> Result<FundChannelResult, BridgeError> {
        let p = Self::decode_payment_header(base64_header)?;
        self.fund_channel(
            &p.channel_id,
            p.balance,
            &p.signature,
            p.params.as_ref(),
            p.funding_proofs.as_deref(),
        )
    }

    pub(super) fn validate_and_save_new_channel(
        &self,
        channel_id: &str,
        params_val: &serde_json::Value,
        proofs: &[Proof],
        balance: u64,
        signature: &str,
    ) -> Result<ChannelFunding, BridgeError> {
        let unit = params_val["unit"]
            .as_str()
            .ok_or(BridgeError::InvalidRequest("Missing unit".into()))?;
        let capacity = params_val["capacity"]
            .as_u64()
            .ok_or(BridgeError::InvalidRequest("Missing capacity".into()))?;
        let expiry_timestamp =
            params_val["expiry_timestamp"]
                .as_u64()
                .ok_or(BridgeError::InvalidRequest(
                    "Missing expiry_timestamp".into(),
                ))?;
        let maximum_amount = params_val["maximum_amount"]
            .as_u64()
            .ok_or(BridgeError::InvalidRequest("Missing maximum_amount".into()))?;
        let receiver_pubkey_hex =
            params_val["receiver_pubkey"]
                .as_str()
                .ok_or(BridgeError::InvalidRequest(
                    "Missing receiver_pubkey".into(),
                ))?;
        let receiver_pubkey = PublicKey::from_hex(receiver_pubkey_hex)
            .map_err(|e| BridgeError::InvalidRequest(e.to_string()))?;
        if !self.host.receiver_key_is_acceptable(&receiver_pubkey) {
            return Err(BridgeError::ReceiverKeyNotAcceptable);
        }
        let sender_pubkey_hex = params_val["sender_pubkey"]
            .as_str()
            .ok_or(BridgeError::InvalidRequest("Missing sender_pubkey".into()))?;
        let keyset_id = Id::from_str(
            params_val["keyset_id"]
                .as_str()
                .ok_or(BridgeError::InvalidRequest("Missing keyset_id".into()))?,
        )
        .map_err(|e| BridgeError::InvalidRequest(e.to_string()))?;
        let mint = params_val["mint"]
            .as_str()
            .ok_or(BridgeError::InvalidRequest("Missing mint".into()))?;
        if !self.host.mint_and_keyset_is_acceptable(mint, &keyset_id) {
            return Err(BridgeError::MintOrKeysetNotAcceptable);
        }
        let keyset_info_json = self
            .host
            .get_keyset_info(mint, &keyset_id)
            .ok_or(BridgeError::MintOrKeysetNotAcceptable)?;
        let policy = self
            .host
            .get_channel_policy(unit)
            .ok_or(BridgeError::UnsupportedUnit(unit.to_string()))?;
        if capacity < policy.min_capacity {
            return Err(BridgeError::CapacityTooSmall {
                capacity,
                min_capacity: policy.min_capacity,
            });
        }
        if let Some(max) = policy.max_amount_per_output {
            if max > 0 && maximum_amount > max {
                return Err(BridgeError::MaxAmountExceeded {
                    amount: maximum_amount,
                    max_allowed: max,
                });
            }
        }
        let now = self.host.now_seconds();
        if expiry_timestamp < now + policy.min_expiry_in_seconds {
            return Err(BridgeError::ExpiryTooSoon {
                expiry_timestamp,
                min_expiry: now + policy.min_expiry_in_seconds,
                now,
            });
        }
        if balance > capacity {
            return Err(BridgeError::BalanceExceedsCapacity { balance, capacity });
        }
        let channel_secret_hex = self
            .host
            .compute_channel_secret(receiver_pubkey_hex, sender_pubkey_hex)
            .map_err(BridgeError::ServerMisconfigured)?;
        let channel_secret: [u8; 32] = hex::decode(&channel_secret_hex)
            .map_err(|e| BridgeError::Internal(e.to_string()))?
            .try_into()
            .map_err(|_| BridgeError::Internal("Invalid secret length".into()))?;
        let params = ChannelParameters::from_json_with_channel_secret(
            &params_val.to_string(),
            crate::parse_keyset_info_from_json(&keyset_info_json)
                .map_err(BridgeError::InvalidRequest)?,
            channel_secret,
        )
        .map_err(|e| BridgeError::Internal(e.to_string()))?;
        if params.get_channel_id() != channel_id {
            return Err(BridgeError::ChannelIdMismatch);
        }
        let verif = verify_valid_channel(proofs, &params);
        if !verif.valid {
            let errors_json =
                serde_json::to_string(&verif.errors).unwrap_or_else(|_| "[]".to_string());
            return Err(BridgeError::ValidationFailed(errors_json));
        }
        let proofs_json =
            serde_json::to_string(proofs).map_err(|e| BridgeError::Internal(e.to_string()))?;
        self.verify_signature(
            &params_val.to_string(),
            &proofs_json,
            &channel_secret_hex,
            &keyset_info_json,
            channel_id,
            balance,
            signature,
        )
        .map_err(BridgeError::InvalidSignature)?;
        let funding = ChannelFunding {
            params_json: params_val.to_string(),
            funding_proofs_json: proofs_json,
            channel_secret_hex,
            keyset_info_json,
        };
        self.host
            .save_funding(
                channel_id,
                funding.clone(),
                PaymentProof {
                    balance,
                    signature: signature.to_string(),
                },
            )
            .map_err(|e| BridgeError::Internal(format!("funding persistence failed: {e}")))?;
        Ok(funding)
    }

    #[allow(clippy::too_many_arguments)]
    fn verify_signature(
        &self,
        params_json: &str,
        proofs_json: &str,
        secret_hex: &str,
        keyset_json: &str,
        channel_id: &str,
        balance: u64,
        signature: &str,
    ) -> Result<(), String> {
        let secret: [u8; 32] = hex::decode(secret_hex)
            .map_err(|e| e.to_string())?
            .try_into()
            .map_err(|_| "Invalid secret length")?;
        let params = ChannelParameters::from_json_with_channel_secret(
            params_json,
            crate::parse_keyset_info_from_json(keyset_json).map_err(|e| e.to_string())?,
            secret,
        )
        .map_err(|e| e.to_string())?;
        let channel = EstablishedChannel::new(
            params,
            serde_json::from_str(proofs_json).map_err(|e| e.to_string())?,
        )
        .map_err(|e| e.to_string())?;
        if channel.params.get_channel_id() != channel_id {
            return Err("channel id does not match funding".to_string());
        }
        crate::balance_update::verify_sender_signature_bundle(&channel, balance, signature)
            .map(|_| ())
    }
}