cdk 0.18.0-rc.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
use std::collections::{HashMap, HashSet};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use cdk_common::mint::MeltQuote;
use cdk_common::nut00::KnownMethod;
use cdk_common::nuts::{CurrencyUnit, MeltQuoteState, Proofs};
use cdk_common::payment::{
    self, CreateIncomingPaymentResponse, Event, IncomingPaymentOptions, MakePaymentResponse,
    MintPayment, OutgoingPaymentOptions, PaymentIdentifier, PaymentQuoteResponse, SettingsResponse,
    WaitPaymentResponse,
};
use cdk_common::{Amount, MeltQuoteBolt11Request, PaymentMethod, ProofsMethods};
use cdk_fake_wallet::{create_fake_invoice, FakeInvoiceDescription, FakeWallet};
use futures::Stream;
use tokio::sync::Notify;

use crate::mint::{Mint, MintBuilder, MintMeltLimits};
use crate::test_helpers::mint::mint_test_proofs;
use crate::types::{FeeReserve, QuoteTTL};
use crate::Error;

struct NoEventPendingBackend {
    inner: FakeWallet,
    status_checks: AtomicUsize,
    settle_after_checks: usize,
    final_status: Option<MeltQuoteState>,
    strip_quote_lookup_id: bool,
    dispatch_gate: Option<Arc<DispatchGate>>,
}

#[derive(Default)]
struct DispatchGate {
    make_payment_started: Notify,
    allow_dispatch: Notify,
    dispatched: AtomicBool,
}

impl DispatchGate {
    async fn wait_for_make_payment(&self) {
        self.make_payment_started.notified().await;
    }

    fn release_dispatch(&self) {
        self.allow_dispatch.notify_one();
    }
}

impl NoEventPendingBackend {
    fn new(settle_after_checks: usize, final_status: Option<MeltQuoteState>) -> Self {
        let fee_reserve = FeeReserve {
            min_fee_reserve: 1.into(),
            percent_fee_reserve: 1.0,
        };

        Self {
            inner: FakeWallet::new(
                fee_reserve,
                HashMap::default(),
                HashSet::default(),
                2,
                CurrencyUnit::Sat,
            ),
            status_checks: AtomicUsize::new(0),
            settle_after_checks,
            final_status,
            strip_quote_lookup_id: false,
            dispatch_gate: None,
        }
    }

    /// Simulates backends (e.g. bolt12) that cannot provide a lookup id at
    /// quote creation because no invoice exists until `make_payment`.
    fn with_stripped_quote_lookup_id(mut self) -> Self {
        self.strip_quote_lookup_id = true;
        self
    }

    fn with_dispatch_gate(mut self, dispatch_gate: Arc<DispatchGate>) -> Self {
        self.dispatch_gate = Some(dispatch_gate);
        self
    }
}

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

    async fn get_settings(&self) -> Result<SettingsResponse, Self::Err> {
        self.inner.get_settings().await
    }

    async fn create_incoming_payment_request(
        &self,
        options: IncomingPaymentOptions,
    ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
        self.inner.create_incoming_payment_request(options).await
    }

    async fn get_payment_quote(
        &self,
        unit: &CurrencyUnit,
        options: OutgoingPaymentOptions,
    ) -> Result<PaymentQuoteResponse, Self::Err> {
        let mut response = self.inner.get_payment_quote(unit, options).await?;
        if self.strip_quote_lookup_id {
            response.request_lookup_id = None;
        }
        Ok(response)
    }

    async fn make_payment(
        &self,
        unit: &CurrencyUnit,
        options: OutgoingPaymentOptions,
    ) -> Result<MakePaymentResponse, Self::Err> {
        if let Some(dispatch_gate) = &self.dispatch_gate {
            dispatch_gate.make_payment_started.notify_one();
            dispatch_gate.allow_dispatch.notified().await;
        }

        let mut response = self.inner.make_payment(unit, options).await?;
        if let Some(dispatch_gate) = &self.dispatch_gate {
            dispatch_gate.dispatched.store(true, Ordering::SeqCst);
        }
        response.status = MeltQuoteState::Pending;
        response.payment_proof = None;
        Ok(response)
    }

    async fn wait_payment_event(
        &self,
    ) -> Result<Pin<Box<dyn Stream<Item = Event> + Send>>, Self::Err> {
        Ok(Box::pin(futures::stream::pending()))
    }

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

    fn cancel_payment_event_stream(&self) {}

    async fn check_incoming_payment_status(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<Vec<WaitPaymentResponse>, Self::Err> {
        self.inner
            .check_incoming_payment_status(payment_identifier)
            .await
    }

    async fn check_outgoing_payment(
        &self,
        payment_identifier: &PaymentIdentifier,
    ) -> Result<MakePaymentResponse, Self::Err> {
        if self
            .dispatch_gate
            .as_ref()
            .is_some_and(|gate| !gate.dispatched.load(Ordering::SeqCst))
        {
            return Ok(MakePaymentResponse {
                payment_lookup_id: payment_identifier.clone(),
                payment_proof: None,
                status: MeltQuoteState::Unpaid,
                total_spent: Amount::new(0, CurrencyUnit::Sat),
            });
        }

        let mut response = self
            .inner
            .check_outgoing_payment(payment_identifier)
            .await?;
        let attempts = self.status_checks.fetch_add(1, Ordering::SeqCst) + 1;
        if attempts < self.settle_after_checks {
            response.status = MeltQuoteState::Pending;
            response.payment_proof = None;
            response.total_spent = Amount::new(0, CurrencyUnit::Sat);
            return Ok(response);
        }

        let Some(final_status) = self.final_status else {
            response.status = MeltQuoteState::Pending;
            response.payment_proof = None;
            response.total_spent = Amount::new(0, CurrencyUnit::Sat);
            return Ok(response);
        };

        response.status = final_status;
        if final_status != MeltQuoteState::Paid {
            response.payment_proof = None;
            response.total_spent = Amount::new(0, CurrencyUnit::Sat);
        }
        Ok(response)
    }
}

async fn create_pending_test_mint(
    backend: Arc<dyn MintPayment<Err = payment::Error> + Send + Sync>,
) -> Result<Mint, Error> {
    let db = Arc::new(cdk_sqlite::mint::memory::empty().await?);
    let mut mint_builder = MintBuilder::new(db.clone());

    mint_builder
        .add_payment_processor(
            CurrencyUnit::Sat,
            PaymentMethod::Known(KnownMethod::Bolt11),
            MintMeltLimits::new(1, 10_000),
            backend,
        )
        .await?;

    let mnemonic = bip39::Mnemonic::generate(12).map_err(|e| Error::Custom(e.to_string()))?;
    let mint = mint_builder
        .with_name("test mint".to_string())
        .with_description("test mint for async melt tests".to_string())
        .with_urls(vec!["https://test-mint".to_string()])
        .build_with_seed(db.clone(), &mnemonic.to_seed_normalized(""))
        .await?;

    mint.set_quote_ttl(QuoteTTL::new(10000, 10000)).await?;
    mint.start().await?;

    Ok(mint)
}

async fn create_test_melt_quote(mint: &Mint, amount: Amount) -> MeltQuote {
    let fake_description = FakeInvoiceDescription {
        pay_invoice_state: MeltQuoteState::Paid,
        check_payment_state: MeltQuoteState::Paid,
        pay_err: false,
        check_err: false,
    };

    let amount_msats: u64 = amount.into();
    let invoice = create_fake_invoice(
        amount_msats,
        serde_json::to_string(&fake_description).expect("fake invoice description"),
    );

    let quote_response = mint
        .get_melt_quote(cdk_common::melt::MeltQuoteRequest::Bolt11(
            MeltQuoteBolt11Request {
                request: invoice,
                unit: CurrencyUnit::Sat,
                options: None,
            },
        ))
        .await
        .expect("melt quote created");

    mint.localstore()
        .get_melt_quote(quote_response.quote().expect("single-quote method"))
        .await
        .expect("db read")
        .expect("quote exists")
}

fn create_test_melt_request(
    proofs: &Proofs,
    quote: &MeltQuote,
) -> cdk_common::nuts::MeltRequest<cdk_common::QuoteId> {
    cdk_common::nuts::MeltRequest::new(quote.id.clone(), proofs.clone(), None)
}

#[tokio::test]
async fn quote_check_waits_for_live_dispatch_before_trusting_unpaid() {
    let dispatch_gate = Arc::new(DispatchGate::default());
    let backend = Arc::new(
        NoEventPendingBackend::new(2, Some(MeltQuoteState::Paid))
            .with_dispatch_gate(dispatch_gate.clone()),
    );
    let mint = create_pending_test_mint(backend.clone()).await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    let pending = mint.melt(&melt_request).await.unwrap();
    dispatch_gate.wait_for_make_payment().await;

    let check_mint = mint.clone();
    let check_quote_id = quote.id.clone();
    let mut check = tokio::spawn(async move { check_mint.check_melt_quote(&check_quote_id).await });

    assert!(
        tokio::time::timeout(Duration::from_millis(50), &mut check)
            .await
            .is_err(),
        "quote check must wait while make_payment can still dispatch"
    );

    dispatch_gate.release_dispatch();

    let response = pending.await.unwrap();
    assert_eq!(response.state(), MeltQuoteState::Paid);

    let checked = check.await.unwrap().unwrap();
    assert_eq!(checked.state(), MeltQuoteState::Paid);
}

#[tokio::test]
async fn pending_melt_completes_via_explicit_status_check_without_notification() {
    let backend: Arc<dyn MintPayment<Err = payment::Error> + Send + Sync> =
        Arc::new(NoEventPendingBackend::new(2, Some(MeltQuoteState::Paid)));
    let mint = create_pending_test_mint(backend).await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    let pending = mint.melt(&melt_request).await.unwrap();
    let checked = mint.check_melt_quote(&quote.id).await.unwrap();
    assert_eq!(checked.state(), MeltQuoteState::Paid);

    let response = pending.await.unwrap();

    assert_eq!(response.state(), MeltQuoteState::Paid);

    let stored_quote = mint
        .localstore()
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(stored_quote.state, MeltQuoteState::Paid);
}

#[tokio::test]
async fn pending_melt_rolls_back_via_explicit_status_check_without_notification() {
    let backend: Arc<dyn MintPayment<Err = payment::Error> + Send + Sync> =
        Arc::new(NoEventPendingBackend::new(2, Some(MeltQuoteState::Failed)));
    let mint = create_pending_test_mint(backend).await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    let pending = mint.melt(&melt_request).await.unwrap();
    let checked = mint.check_melt_quote(&quote.id).await.unwrap();
    assert_eq!(checked.state(), MeltQuoteState::Unpaid);

    let response = pending.await.unwrap();

    assert_eq!(response.state(), MeltQuoteState::Unpaid);

    let stored_quote = mint
        .localstore()
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(stored_quote.state, MeltQuoteState::Unpaid);

    let proof_states = mint
        .localstore()
        .get_proofs_states(&input_ys)
        .await
        .unwrap();
    assert!(proof_states.iter().all(|state| state.is_none()));
}

#[tokio::test]
async fn pending_melt_wait_resolves_via_external_successful_event() {
    // Backend stays Pending forever on both pay and check; only the external
    // event delivered via handle_successful_melt_payment_event should resolve
    // the wait loop.
    let backend: Arc<dyn MintPayment<Err = payment::Error> + Send + Sync> =
        Arc::new(NoEventPendingBackend::new(usize::MAX, None));
    let mint = create_pending_test_mint(backend).await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    let pending = mint.melt(&melt_request).await.unwrap();

    // Simulate an async event arriving while the wait loop is running.
    let event_mint = Arc::new(mint.clone());
    let event_localstore = mint.localstore();
    let event_pubsub = mint.pubsub_manager();
    let event_quote_id = quote.id.clone();
    let total_spent = quote.amount();
    let lookup_id = PaymentIdentifier::CustomId(quote.id.to_string());
    let event_task = tokio::spawn(async move {
        // Small delay so the wait loop is actually waiting when the event arrives.
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        let payment_result = MakePaymentResponse {
            payment_lookup_id: lookup_id,
            payment_proof: Some("external_event_preimage".to_string()),
            status: MeltQuoteState::Paid,
            total_spent,
        };
        Mint::handle_successful_melt_payment_event(
            &event_mint,
            &event_localstore,
            &event_pubsub,
            &event_quote_id,
            payment_result,
        )
        .await
    });

    let response = pending.await.unwrap();
    event_task.await.unwrap().unwrap();

    assert_eq!(response.state(), MeltQuoteState::Paid);

    let stored_quote = mint
        .localstore()
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(stored_quote.state, MeltQuoteState::Paid);

    // Saga must be deleted exactly once — racing paths should not leave it orphaned
    // nor double-process.
    let sagas = mint
        .localstore()
        .get_incomplete_sagas(cdk_common::mint::OperationKind::Melt)
        .await
        .unwrap();
    assert!(
        sagas.is_empty(),
        "saga should be deleted after successful finalization"
    );
}

#[tokio::test]
async fn pending_melt_wait_times_out_without_settled_progress() {
    let backend: Arc<dyn MintPayment<Err = payment::Error> + Send + Sync> =
        Arc::new(NoEventPendingBackend::new(usize::MAX, None));
    let mint = create_pending_test_mint(backend).await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    let pending = mint.melt(&melt_request).await.unwrap();
    assert_eq!(pending.pending_response().state(), MeltQuoteState::Pending);

    let err = pending.await.unwrap_err();
    assert!(matches!(err, Error::PendingMeltTimeout { .. }));

    let stored_quote = mint
        .localstore()
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(stored_quote.state, MeltQuoteState::Pending);

    let saga = mint
        .localstore()
        .get_melt_saga_by_quote_id(&quote.id)
        .await
        .unwrap();
    assert!(
        saga.is_some(),
        "pending melt should remain recoverable after timeout"
    );
}

#[tokio::test]
async fn pending_melt_persists_payment_lookup_id_when_quote_has_none() {
    // Simulates the bolt12 situation: no lookup id exists at quote creation,
    // so the quote is persisted with request_lookup_id: None. When the payment
    // parks as Pending, the saga must persist the lookup id returned by
    // make_payment — it is the only durable handle to the in-flight payment
    // for the pending wait loop and startup recovery.
    let backend: Arc<dyn MintPayment<Err = payment::Error> + Send + Sync> =
        Arc::new(NoEventPendingBackend::new(usize::MAX, None).with_stripped_quote_lookup_id());
    let mint = create_pending_test_mint(backend).await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    assert!(
        quote.request_lookup_id.is_none(),
        "test premise: quote persisted without a lookup id"
    );
    let melt_request = create_test_melt_request(&proofs, &quote);

    let pending = mint.melt(&melt_request).await.unwrap();
    let err = pending.await.unwrap_err();
    assert!(matches!(err, Error::PendingMeltTimeout { .. }));

    let expected_lookup_id = match &quote.request {
        cdk_common::mint::MeltPaymentRequest::Bolt11 { bolt11 } => {
            PaymentIdentifier::PaymentHash(*bolt11.payment_hash().as_ref())
        }
        request => panic!("expected bolt11 melt payment request, got {request}"),
    };

    let stored_quote = mint
        .localstore()
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(stored_quote.state, MeltQuoteState::Pending);
    assert_eq!(
        stored_quote.request_lookup_id,
        Some(expected_lookup_id),
        "lookup id returned by make_payment must be persisted while pending"
    );
}

#[tokio::test]
async fn pending_melt_without_quote_lookup_id_resolves_via_explicit_status_check() {
    // End-to-end regression for the bolt12-style flow: with the quote created
    // without a lookup id, an explicit quote check settles the payment using
    // the lookup id persisted when make_payment parked as Pending.
    let backend: Arc<dyn MintPayment<Err = payment::Error> + Send + Sync> = Arc::new(
        NoEventPendingBackend::new(2, Some(MeltQuoteState::Paid)).with_stripped_quote_lookup_id(),
    );
    let mint = create_pending_test_mint(backend).await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    assert!(
        quote.request_lookup_id.is_none(),
        "test premise: quote persisted without a lookup id"
    );
    let melt_request = create_test_melt_request(&proofs, &quote);

    let pending = mint.melt(&melt_request).await.unwrap();
    let checked = mint.check_melt_quote(&quote.id).await.unwrap();
    assert_eq!(checked.state(), MeltQuoteState::Paid);

    let response = pending.await.unwrap();

    assert_eq!(response.state(), MeltQuoteState::Paid);

    let stored_quote = mint
        .localstore()
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(stored_quote.state, MeltQuoteState::Paid);
    assert!(stored_quote.request_lookup_id.is_some());
}

/// Internally-settled melts never touch the backend, so a quote without a
/// lookup id must still be finalized by on-demand checks rather than waiting
/// for the next restart.
#[tokio::test]
async fn internal_settlement_without_lookup_id_finalizes_on_demand() {
    let backend: Arc<dyn MintPayment<Err = payment::Error> + Send + Sync> =
        Arc::new(NoEventPendingBackend::new(usize::MAX, None).with_stripped_quote_lookup_id());
    let mint = create_pending_test_mint(backend).await.unwrap();

    // A mint quote on THIS mint; its invoice makes the melt below an internal
    // settlement.
    let mint_quote_response = mint
        .get_mint_quote(
            cdk_common::MintQuoteBolt11Request {
                amount: Amount::from(4_000),
                unit: CurrencyUnit::Sat,
                description: None,
                pubkey: None,
            }
            .into(),
        )
        .await
        .unwrap();
    let mint_quote = mint
        .localstore()
        .get_mint_quote(mint_quote_response.quote())
        .await
        .unwrap()
        .expect("mint quote should exist");

    let melt_quote_response = mint
        .get_melt_quote(cdk_common::melt::MeltQuoteRequest::Bolt11(
            MeltQuoteBolt11Request {
                request: mint_quote.request.to_string().parse().unwrap(),
                unit: CurrencyUnit::Sat,
                options: None,
            },
        ))
        .await
        .unwrap();
    let quote = mint
        .localstore()
        .get_melt_quote(melt_quote_response.quote().expect("single-quote method"))
        .await
        .unwrap()
        .expect("melt quote should exist");
    assert!(
        quote.request_lookup_id.is_none(),
        "test premise: quote persisted without a lookup id"
    );

    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();
    let melt_request = create_test_melt_request(&proofs, &quote);

    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = crate::mint::melt::melt_saga::MeltSaga::new(
        Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    let (payment_saga, _decision) = setup
        .attempt_internal_settlement(&melt_request)
        .await
        .unwrap();

    // Simulate a crash before finalize: mint quote credited, proofs pending.
    drop(payment_saga);
    assert_eq!(
        mint.localstore()
            .get_mint_quote(mint_quote_response.quote())
            .await
            .unwrap()
            .expect("mint quote should exist")
            .state(),
        cdk_common::MintQuoteState::Paid
    );

    // On-demand check finalizes instead of requiring a restart.
    let mut quote = mint
        .localstore()
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    mint.handle_pending_melt_quote(&mut quote).await.unwrap();

    assert_eq!(quote.state, MeltQuoteState::Paid);
    let states = mint
        .localstore()
        .get_proofs_states(&input_ys)
        .await
        .unwrap();
    assert!(
        states.iter().all(|s| *s == Some(cdk_common::State::Spent)),
        "internally-settled proofs must be consumed"
    );
}

/// Startup recovery derives a stable backend identifier when an older quote
/// has no persisted lookup id and compensates a definitively unpaid attempt.
#[tokio::test]
async fn payment_attempted_without_lookup_id_recovers_unpaid_at_startup() {
    let backend: Arc<dyn MintPayment<Err = payment::Error> + Send + Sync> = Arc::new(
        NoEventPendingBackend::new(1, Some(MeltQuoteState::Unpaid)).with_stripped_quote_lookup_id(),
    );
    let mint = create_pending_test_mint(backend).await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    assert!(
        quote.request_lookup_id.is_none(),
        "test premise: quote persisted without a lookup id"
    );
    let melt_request = create_test_melt_request(&proofs, &quote);

    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = crate::mint::melt::melt_saga::MeltSaga::new(
        Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    drop(setup);

    let operation_id = mint
        .localstore()
        .get_incomplete_sagas(cdk_common::mint::OperationKind::Melt)
        .await
        .unwrap()
        .into_iter()
        .next()
        .expect("saga should exist")
        .operation_id;

    // Simulate a crash after the write-ahead PaymentAttempted marker but
    // before make_payment runs or a lookup id is persisted.
    {
        let mut tx = mint.localstore().begin_transaction().await.unwrap();
        let mut saga = tx
            .get_saga_for_update(&operation_id)
            .await
            .unwrap()
            .expect("saga should exist");
        tx.update_acquired_saga(
            &mut saga,
            cdk_common::mint::SagaStateEnum::Melt(
                cdk_common::mint::MeltSagaState::PaymentAttempted,
            ),
        )
        .await
        .unwrap();
        tx.commit().await.unwrap();
    }

    // Inputs are reserved (Pending) at the moment of the crash.
    let states = mint
        .localstore()
        .get_proofs_states(&input_ys)
        .await
        .unwrap();
    assert!(states
        .iter()
        .all(|s| *s == Some(cdk_common::State::Pending)));

    // Simulate the crash: run startup recovery.
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("recovery should succeed");

    // The backend was checked with the identifier derived from the quote and
    // definitively reported Unpaid, so recovery returns the reserved proofs.
    let states = mint
        .localstore()
        .get_proofs_states(&input_ys)
        .await
        .unwrap();
    assert!(states.iter().all(Option::is_none));
    let stored_quote = mint
        .localstore()
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(stored_quote.state, MeltQuoteState::Unpaid);
    assert!(mint
        .localstore()
        .get_melt_saga_by_quote_id(&quote.id)
        .await
        .unwrap()
        .is_none());
}