cdk 0.18.0-rc.1

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
use cdk_common::wallet::{Transaction, TransactionDirection, TransactionId, TransactionStatus};
use cdk_common::Proofs;

use crate::{Error, Wallet};

impl Wallet {
    fn transaction_matches_wallet(&self, transaction: &Transaction) -> bool {
        transaction.matches_conditions(
            &Some(self.mint_url.clone()),
            &None,
            &Some(self.unit.clone()),
        )
    }

    /// List transactions
    pub async fn list_transactions(
        &self,
        direction: Option<TransactionDirection>,
    ) -> Result<Vec<Transaction>, Error> {
        let mut transactions = self
            .localstore
            .list_transactions(
                Some(self.mint_url.clone()),
                direction,
                Some(self.unit.clone()),
            )
            .await?;

        transactions.sort();

        Ok(transactions)
    }

    /// Get transaction by ID
    pub async fn get_transaction(&self, id: TransactionId) -> Result<Option<Transaction>, Error> {
        let transaction = self.localstore.get_transaction(id).await?;

        Ok(transaction.filter(|transaction| self.transaction_matches_wallet(transaction)))
    }

    /// Store a transaction without changing its original creation timestamp.
    pub(crate) async fn upsert_transaction(
        &self,
        mut transaction: Transaction,
    ) -> Result<(), Error> {
        if let Some(existing) = self.localstore.get_transaction(transaction.id()).await? {
            transaction.timestamp = existing.timestamp;
        }

        self.localstore.add_transaction(transaction).await?;
        Ok(())
    }

    /// Update the status of the transaction associated with a saga.
    ///
    /// Returns `true` when the requested status was applied to at least one
    /// matching transaction, or a matching transaction already had it.
    /// Returns `false` when no transaction matches the saga, or every match
    /// was already in a terminal state and the update was ignored.
    pub(crate) async fn update_transaction_status_by_saga_id(
        &self,
        saga_id: uuid::Uuid,
        status: TransactionStatus,
    ) -> Result<bool, Error> {
        let transaction_id = TransactionId::from_saga_id(saga_id);
        let transaction = self
            .localstore
            .get_transaction(transaction_id)
            .await?
            .filter(|transaction| self.transaction_matches_wallet(transaction));

        let transactions = match transaction {
            Some(transaction) => vec![transaction],
            None => self
                .localstore
                .list_transactions(Some(self.mint_url.clone()), None, Some(self.unit.clone()))
                .await?
                .into_iter()
                .filter(|transaction| transaction.saga_id == Some(saga_id))
                .collect(),
        };

        if transactions.is_empty() {
            return Ok(false);
        }

        let mut applied = false;
        for mut transaction in transactions {
            if transaction.status == status {
                applied = true;
                continue;
            }

            if transaction.status != TransactionStatus::Pending {
                tracing::warn!(
                    saga_id = %saga_id,
                    current_status = %transaction.status,
                    requested_status = %status,
                    "Ignoring transaction status change from terminal state"
                );
                continue;
            }

            transaction.status = status;
            self.localstore.add_transaction(transaction).await?;
            applied = true;
        }
        Ok(applied)
    }

    /// Mark a saga transaction as failed before compensating it.
    ///
    /// Persistence errors are propagated so compensation cannot delete the
    /// saga before its transaction reaches a durable terminal state.
    pub(crate) async fn mark_transaction_failed(&self, saga_id: uuid::Uuid) -> Result<(), Error> {
        self.update_transaction_status_by_saga_id(saga_id, TransactionStatus::Failed)
            .await?;
        Ok(())
    }

    /// Get proofs for a transaction by transaction ID
    ///
    /// This retrieves all proofs associated with a transaction by looking up
    /// the transaction's Y values and fetching the corresponding proofs.
    pub async fn get_proofs_for_transaction(&self, id: TransactionId) -> Result<Proofs, Error> {
        let transaction = self
            .get_transaction(id)
            .await?
            .ok_or(Error::TransactionNotFound)?;

        let mint_url = Some(self.mint_url.clone());
        let unit = Some(self.unit.clone());

        let proofs = self
            .localstore
            .get_proofs_by_ys(transaction.ys)
            .await?
            .into_iter()
            .filter(|proof_info| proof_info.matches_conditions(&mint_url, &unit, &None, &None))
            .map(|p| p.proof)
            .collect();

        Ok(proofs)
    }

    /// Revert a transaction by reclaiming unspent proofs.
    ///
    /// For transactions created by the saga pattern (with `saga_id` set), this
    /// function loads the associated send saga and calls `revoke()` on it, which
    /// properly handles the saga lifecycle including state transitions and cleanup.
    ///
    /// For legacy transactions (without `saga_id`), this function checks the proofs
    /// with the mint and marks any spent proofs accordingly. Unspent proofs are
    /// left in their current state for manual recovery.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The transaction is not found
    /// - The transaction is not outgoing
    /// - The saga is not in a revocable state (e.g., already completed)
    /// - The token has already been claimed by the recipient
    pub async fn revert_transaction(&self, id: TransactionId) -> Result<(), Error> {
        let tx = self
            .get_transaction(id)
            .await?
            .ok_or(Error::TransactionNotFound)?;

        if tx.direction != TransactionDirection::Outgoing {
            return Err(Error::InvalidTransactionDirection);
        }

        // Check if this is a saga-managed transaction
        if let Some(saga_id) = &tx.saga_id {
            // Use the existing revoke_send method which properly handles the saga
            // Discard the returned amount - we just care about success/failure
            let _ = self.revoke_send(*saga_id).await?;
            Ok(())
        } else {
            // Legacy transaction without saga - check proofs and mark spent ones
            // We don't attempt to swap for legacy transactions to avoid
            // interfering with any potential in-flight operations
            let pending_spent_proofs: Proofs = self
                .get_pending_spent_proofs()
                .await?
                .into_iter()
                .filter(|p| match p.y() {
                    Ok(y) => tx.ys.contains(&y),
                    Err(_) => false,
                })
                .collect();

            if pending_spent_proofs.is_empty() {
                return Ok(());
            }

            // Just check and mark spent - don't attempt swap for legacy transactions
            self.check_proofs_spent(pending_spent_proofs).await?;
            Ok(())
        }
    }
}

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

    use cdk_common::mint_url::MintUrl;
    use cdk_common::nuts::{CurrencyUnit, State};
    use cdk_common::wallet::{
        ProofInfo, Transaction, TransactionDirection, TransactionId, TransactionStatus,
    };
    use cdk_common::Amount;

    use crate::wallet::test_utils::{
        create_test_db, create_test_wallet, test_keyset_id, test_proof,
    };

    #[tokio::test]
    async fn get_proofs_for_transaction_does_not_leak_other_mints_proofs() {
        let db = create_test_db().await;
        let wallet = create_test_wallet(db.clone()).await;

        let mint_b =
            MintUrl::from_str("https://other-mint.example.com").expect("mint URL should be valid");
        let proof_b = test_proof(test_keyset_id(), 100);
        let proof_b_y = proof_b.y().expect("test proof should derive a Y value");
        let proof_info_b =
            ProofInfo::new(proof_b, mint_b.clone(), State::Unspent, CurrencyUnit::Sat)
                .expect("proof info should be valid");
        db.update_proofs(vec![proof_info_b], vec![])
            .await
            .expect("proof should be stored");

        let tx_b = Transaction {
            mint_url: mint_b,
            direction: TransactionDirection::Outgoing,
            amount: Amount::from(100_u64),
            fee: Amount::from(0_u64),
            unit: CurrencyUnit::Sat,
            ys: vec![proof_b_y],
            timestamp: 0,
            memo: None,
            metadata: HashMap::new(),
            quote_id: None,
            payment_request: None,
            payment_proof: None,
            payment_method: None,
            saga_id: None,
            status: TransactionStatus::Completed,
        };
        let tx_b_id = tx_b.id();
        db.add_transaction(tx_b)
            .await
            .expect("transaction should be stored");

        let returned = wallet.get_proofs_for_transaction(tx_b_id).await;

        assert!(
            matches!(returned, Err(crate::Error::TransactionNotFound)),
            "wallet returned proofs for another mint's transaction: {:?}",
            returned.map(|proofs| proofs.len())
        );
    }

    #[tokio::test]
    async fn terminal_transaction_status_cannot_be_overwritten() {
        let db = create_test_db().await;
        let wallet = create_test_wallet(db.clone()).await;
        let saga_id = uuid::Uuid::new_v4();

        let transaction = Transaction {
            mint_url: wallet.mint_url.clone(),
            direction: TransactionDirection::Incoming,
            amount: Amount::from(100_u64),
            fee: Amount::ZERO,
            unit: wallet.unit.clone(),
            ys: vec![],
            timestamp: 0,
            memo: None,
            metadata: HashMap::new(),
            quote_id: None,
            payment_request: None,
            payment_proof: None,
            payment_method: None,
            saga_id: Some(saga_id),
            status: TransactionStatus::Pending,
        };
        db.add_transaction(transaction)
            .await
            .expect("transaction should be stored");

        assert!(wallet
            .update_transaction_status_by_saga_id(saga_id, TransactionStatus::Completed)
            .await
            .expect("pending status should update"));
        assert!(!wallet
            .update_transaction_status_by_saga_id(saga_id, TransactionStatus::Failed)
            .await
            .expect("terminal status update should be ignored"));

        let transaction = db
            .get_transaction(TransactionId::from_saga_id(saga_id))
            .await
            .expect("transaction lookup should succeed")
            .expect("transaction should exist");
        assert_eq!(transaction.status, TransactionStatus::Completed);
    }

    fn saga_transaction(
        wallet: &crate::Wallet,
        saga_id: uuid::Uuid,
        status: TransactionStatus,
        batch_quote_id: Option<&str>,
    ) -> Transaction {
        let mut metadata = HashMap::new();
        if let Some(quote_id) = batch_quote_id {
            metadata.insert("batch_quote_id".to_string(), quote_id.to_string());
        }

        Transaction {
            mint_url: wallet.mint_url.clone(),
            direction: TransactionDirection::Incoming,
            amount: Amount::from(100_u64),
            fee: Amount::ZERO,
            unit: wallet.unit.clone(),
            ys: vec![],
            timestamp: 0,
            memo: None,
            metadata,
            quote_id: None,
            payment_request: None,
            payment_proof: None,
            payment_method: None,
            saga_id: Some(saga_id),
            status,
        }
    }

    #[tokio::test]
    async fn status_update_returns_false_for_unknown_saga() {
        let db = create_test_db().await;
        let wallet = create_test_wallet(db.clone()).await;

        assert!(!wallet
            .update_transaction_status_by_saga_id(
                uuid::Uuid::new_v4(),
                TransactionStatus::Completed
            )
            .await
            .expect("update for unknown saga should succeed"));
    }

    #[tokio::test]
    async fn batch_quote_transactions_are_updated_via_saga_fallback() {
        let db = create_test_db().await;
        let wallet = create_test_wallet(db.clone()).await;
        let saga_id = uuid::Uuid::new_v4();

        // Batch-quote transactions derive their ID from the saga ID and quote
        // ID, so the direct `from_saga_id` lookup misses and the saga-ID
        // fallback scan must find them.
        for quote_id in ["quote-a", "quote-b"] {
            let transaction =
                saga_transaction(&wallet, saga_id, TransactionStatus::Pending, Some(quote_id));
            assert_ne!(
                transaction.id(),
                TransactionId::from_saga_id(saga_id),
                "batch quote transaction must not use the plain saga ID"
            );
            db.add_transaction(transaction)
                .await
                .expect("transaction should be stored");
        }

        assert!(wallet
            .update_transaction_status_by_saga_id(saga_id, TransactionStatus::Completed)
            .await
            .expect("batch quote transactions should update"));

        for quote_id in ["quote-a", "quote-b"] {
            let transaction = db
                .get_transaction(TransactionId::from_batch_quote(saga_id, quote_id))
                .await
                .expect("transaction lookup should succeed")
                .expect("transaction should exist");
            assert_eq!(transaction.status, TransactionStatus::Completed);
        }
    }

    #[tokio::test]
    async fn mixed_terminal_and_pending_transactions_update_only_pending() {
        let db = create_test_db().await;
        let wallet = create_test_wallet(db.clone()).await;
        let saga_id = uuid::Uuid::new_v4();

        db.add_transaction(saga_transaction(
            &wallet,
            saga_id,
            TransactionStatus::Completed,
            Some("quote-done"),
        ))
        .await
        .expect("transaction should be stored");
        db.add_transaction(saga_transaction(
            &wallet,
            saga_id,
            TransactionStatus::Pending,
            Some("quote-pending"),
        ))
        .await
        .expect("transaction should be stored");

        assert!(wallet
            .update_transaction_status_by_saga_id(saga_id, TransactionStatus::Failed)
            .await
            .expect("pending transaction should update"));

        let terminal = db
            .get_transaction(TransactionId::from_batch_quote(saga_id, "quote-done"))
            .await
            .expect("transaction lookup should succeed")
            .expect("transaction should exist");
        assert_eq!(
            terminal.status,
            TransactionStatus::Completed,
            "terminal transaction must not be overwritten"
        );

        let pending = db
            .get_transaction(TransactionId::from_batch_quote(saga_id, "quote-pending"))
            .await
            .expect("transaction lookup should succeed")
            .expect("transaction should exist");
        assert_eq!(pending.status, TransactionStatus::Failed);
    }

    #[tokio::test]
    async fn status_update_returns_false_when_all_matches_are_terminal() {
        let db = create_test_db().await;
        let wallet = create_test_wallet(db.clone()).await;
        let saga_id = uuid::Uuid::new_v4();

        for quote_id in ["quote-a", "quote-b"] {
            db.add_transaction(saga_transaction(
                &wallet,
                saga_id,
                TransactionStatus::Completed,
                Some(quote_id),
            ))
            .await
            .expect("transaction should be stored");
        }

        assert!(!wallet
            .update_transaction_status_by_saga_id(saga_id, TransactionStatus::Failed)
            .await
            .expect("terminal status updates should be ignored"));
    }

    #[tokio::test]
    async fn status_update_to_current_status_reports_applied() {
        let db = create_test_db().await;
        let wallet = create_test_wallet(db.clone()).await;
        let saga_id = uuid::Uuid::new_v4();

        db.add_transaction(saga_transaction(
            &wallet,
            saga_id,
            TransactionStatus::Completed,
            None,
        ))
        .await
        .expect("transaction should be stored");

        assert!(wallet
            .update_transaction_status_by_saga_id(saga_id, TransactionStatus::Completed)
            .await
            .expect("matching status should report applied"));

        let transaction = db
            .get_transaction(TransactionId::from_saga_id(saga_id))
            .await
            .expect("transaction lookup should succeed")
            .expect("transaction should exist");
        assert_eq!(transaction.status, TransactionStatus::Completed);
    }
}