cdk 0.16.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Wallet Saga Pattern Implementation
//!
//! This module provides the type state pattern infrastructure for wallet operations.
//! It mirrors the mint's saga pattern to ensure consistency across the codebase.
//!
//! # Type State Pattern
//!
//! The type state pattern uses Rust's type system to enforce valid state transitions
//! at compile-time. Each operation state is a distinct type, and operations are only
//! available on the appropriate type.
//!
//! # Compensation Pattern
//!
//! When a saga step fails, compensating actions are executed in reverse order (LIFO)
//! to undo all completed steps and restore the database to its pre-saga state.

use std::collections::VecDeque;
use std::sync::Arc;

use async_trait::async_trait;
use cdk_common::database::{self, WalletDatabase};
use tracing::instrument;

use crate::nuts::{PublicKey, State};
use crate::Error;

/// Trait for compensating actions in the saga pattern.
/// Actions are executed in reverse order (LIFO) during rollback.
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub(crate) trait CompensatingAction: Send + Sync {
    /// Execute the compensating action
    async fn execute(&self) -> Result<(), Error>;

    /// Get the name of this compensating action for logging
    fn name(&self) -> &'static str;
}

/// Queue of compensating actions for saga rollback.
pub(crate) type Compensations = VecDeque<Box<dyn CompensatingAction>>;

/// Create a new empty compensations queue
pub(crate) fn new_compensations() -> Compensations {
    VecDeque::new()
}

/// Execute all compensating actions in LIFO order.
/// Errors are logged but execution continues.
pub(crate) async fn execute_compensations(compensations: &mut Compensations) -> Result<(), Error> {
    if compensations.is_empty() {
        return Ok(());
    }

    tracing::warn!("Running {} compensating actions", compensations.len());

    while let Some(compensation) = compensations.pop_front() {
        tracing::debug!("Running compensation: {}", compensation.name());
        if let Err(e) = compensation.execute().await {
            tracing::error!(
                "Compensation {} failed: {}. Continuing...",
                compensation.name(),
                e
            );
        }
    }

    Ok(())
}

/// Clear all compensating actions from the queue.
pub(crate) async fn clear_compensations(compensations: &mut Compensations) {
    compensations.clear();
}

/// Add a compensating action to the front of the queue (LIFO order).
pub(crate) async fn add_compensation(
    compensations: &mut Compensations,
    action: Box<dyn CompensatingAction>,
) {
    compensations.push_front(action);
}

// Shared Compensation Actions

/// Reverts proof reservation on saga failure.
/// Sets proofs back to Unspent and deletes the saga record.
pub(crate) struct RevertProofReservation {
    pub localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync>,
    pub proof_ys: Vec<PublicKey>,
    pub saga_id: uuid::Uuid,
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl CompensatingAction for RevertProofReservation {
    #[instrument(skip_all)]
    async fn execute(&self) -> Result<(), Error> {
        tracing::info!(
            "Compensation: Reverting {} proofs from Reserved to Unspent",
            self.proof_ys.len()
        );

        // Fetch current states to avoid reverting proofs that were already spent
        // (e.g. by a successful internal swap that occurred before a crash)
        let current_proofs = self
            .localstore
            .get_proofs_by_ys(self.proof_ys.clone())
            .await
            .map_err(Error::Database)?;

        let ys_to_revert: Vec<_> = current_proofs
            .into_iter()
            .filter(|p| p.state == State::Reserved || p.state == State::Pending)
            .map(|p| p.y)
            .collect();

        if !ys_to_revert.is_empty() {
            self.localstore
                .update_proofs_state(ys_to_revert, State::Unspent)
                .await
                .map_err(Error::Database)?;
        }

        if let Err(e) = self.localstore.delete_saga(&self.saga_id).await {
            tracing::warn!(
                "Compensation: Failed to delete saga {}: {}. Will be cleaned up on recovery.",
                self.saga_id,
                e
            );
            // Don't fail compensation if saga deletion fails - orphaned saga is harmless
        }

        Ok(())
    }

    fn name(&self) -> &'static str {
        "RevertProofReservation"
    }
}

/// Test utilities shared across wallet saga compensation tests.
#[cfg(test)]
pub mod test_utils {
    use std::str::FromStr;
    use std::sync::Arc;

    use cdk_common::database::WalletDatabase;
    use cdk_common::nuts::{CurrencyUnit, Id, Proof, State};
    use cdk_common::secret::Secret;
    use cdk_common::wallet::ProofInfo;
    use cdk_common::{Amount, SecretKey};

    /// Create an in-memory test database
    pub async fn create_test_db(
    ) -> Arc<dyn WalletDatabase<cdk_common::database::Error> + Send + Sync> {
        Arc::new(cdk_sqlite::wallet::memory::empty().await.unwrap())
    }

    /// Create a test keyset ID
    pub fn test_keyset_id() -> Id {
        Id::from_str("00916bbf7ef91a36").unwrap()
    }

    /// Create a test mint URL
    pub fn test_mint_url() -> cdk_common::mint_url::MintUrl {
        cdk_common::mint_url::MintUrl::from_str("https://test-mint.example.com").unwrap()
    }

    /// Create a test proof with the given keyset ID and amount
    pub fn test_proof(keyset_id: Id, amount: u64) -> Proof {
        Proof {
            amount: Amount::from(amount),
            keyset_id,
            secret: Secret::generate(),
            c: SecretKey::generate().public_key(),
            witness: None,
            dleq: None,
            p2pk_e: None,
        }
    }

    /// Create a test proof info with the given parameters
    pub fn test_proof_info(
        keyset_id: Id,
        amount: u64,
        mint_url: cdk_common::mint_url::MintUrl,
        state: State,
    ) -> ProofInfo {
        let proof = test_proof(keyset_id, amount);
        ProofInfo::new(proof, mint_url, state, CurrencyUnit::Sat).unwrap()
    }

    /// Create a test wallet saga for testing compensations
    pub fn test_simple_saga(
        mint_url: cdk_common::mint_url::MintUrl,
    ) -> cdk_common::wallet::WalletSaga {
        use cdk_common::wallet::{
            OperationData, SwapOperationData, SwapSagaState, WalletSaga, WalletSagaState,
        };
        use cdk_common::Amount;

        WalletSaga::new(
            uuid::Uuid::new_v4(),
            WalletSagaState::Swap(SwapSagaState::ProofsReserved),
            Amount::from(1000),
            mint_url,
            CurrencyUnit::Sat,
            OperationData::Swap(SwapOperationData {
                input_amount: Amount::from(1000),
                output_amount: Amount::from(990),
                counter_start: Some(0),
                counter_end: Some(10),
                blinded_messages: None,
            }),
        )
    }
}

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

    // =========================================================================
    // RevertProofReservation Tests
    // =========================================================================

    #[tokio::test]
    async fn test_revert_proof_reservation_is_idempotent() {
        let db = test_utils::create_test_db().await;
        let mint_url = test_utils::test_mint_url();
        let keyset_id = test_utils::test_keyset_id();

        let proof_info =
            test_utils::test_proof_info(keyset_id, 100, mint_url.clone(), State::Reserved);
        let proof_y = proof_info.y;
        db.update_proofs(vec![proof_info], vec![]).await.unwrap();

        let saga = test_utils::test_simple_saga(mint_url);
        let saga_id = saga.id;
        db.add_saga(saga).await.unwrap();

        let compensation = RevertProofReservation {
            localstore: db.clone(),
            proof_ys: vec![proof_y],
            saga_id,
        };

        // Execute twice - should succeed both times
        compensation.execute().await.unwrap();
        compensation.execute().await.unwrap();

        // Proof should be Unspent
        let proofs = db
            .get_proofs(None, None, Some(vec![State::Unspent]), None)
            .await
            .unwrap();
        assert_eq!(proofs.len(), 1);
    }

    #[tokio::test]
    async fn test_revert_proof_reservation_handles_missing_saga() {
        let db = test_utils::create_test_db().await;
        let mint_url = test_utils::test_mint_url();
        let keyset_id = test_utils::test_keyset_id();

        let proof_info =
            test_utils::test_proof_info(keyset_id, 100, mint_url.clone(), State::Reserved);
        let proof_y = proof_info.y;
        db.update_proofs(vec![proof_info], vec![]).await.unwrap();

        // Use a saga_id that doesn't exist
        let saga_id = uuid::Uuid::new_v4();

        let compensation = RevertProofReservation {
            localstore: db.clone(),
            proof_ys: vec![proof_y],
            saga_id,
        };

        // Should succeed even without saga
        compensation.execute().await.unwrap();

        // Proof should be Unspent
        let proofs = db
            .get_proofs(None, None, Some(vec![State::Unspent]), None)
            .await
            .unwrap();
        assert_eq!(proofs.len(), 1);
    }

    #[tokio::test]
    async fn test_revert_proof_reservation_only_affects_specified_proofs() {
        let db = test_utils::create_test_db().await;
        let mint_url = test_utils::test_mint_url();
        let keyset_id = test_utils::test_keyset_id();

        // Create two reserved proofs
        let proof_info_1 =
            test_utils::test_proof_info(keyset_id, 100, mint_url.clone(), State::Reserved);
        let proof_info_2 =
            test_utils::test_proof_info(keyset_id, 200, mint_url.clone(), State::Reserved);
        let proof_y_1 = proof_info_1.y;
        let proof_y_2 = proof_info_2.y;
        db.update_proofs(vec![proof_info_1, proof_info_2], vec![])
            .await
            .unwrap();

        let saga = test_utils::test_simple_saga(mint_url);
        let saga_id = saga.id;
        db.add_saga(saga).await.unwrap();

        // Only revert the first proof
        let compensation = RevertProofReservation {
            localstore: db.clone(),
            proof_ys: vec![proof_y_1],
            saga_id,
        };
        compensation.execute().await.unwrap();

        // First proof should be Unspent
        let unspent = db
            .get_proofs(None, None, Some(vec![State::Unspent]), None)
            .await
            .unwrap();
        assert_eq!(unspent.len(), 1);
        assert_eq!(unspent[0].y, proof_y_1);

        // Second proof should still be Reserved
        let reserved = db
            .get_proofs(None, None, Some(vec![State::Reserved]), None)
            .await
            .unwrap();
        assert_eq!(reserved.len(), 1);
        assert_eq!(reserved[0].y, proof_y_2);
    }

    /// A mock compensating action for testing that tracks execution order.
    struct MockCompensation {
        name: &'static str,
        execution_order: Arc<std::sync::Mutex<Vec<&'static str>>>,
        should_fail: bool,
    }

    impl MockCompensation {
        fn new(
            name: &'static str,
            execution_order: Arc<std::sync::Mutex<Vec<&'static str>>>,
        ) -> Self {
            Self {
                name,
                execution_order,
                should_fail: false,
            }
        }

        fn failing(
            name: &'static str,
            execution_order: Arc<std::sync::Mutex<Vec<&'static str>>>,
        ) -> Self {
            Self {
                name,
                execution_order,
                should_fail: true,
            }
        }
    }

    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    impl CompensatingAction for MockCompensation {
        async fn execute(&self) -> Result<(), Error> {
            self.execution_order.lock().unwrap().push(self.name);
            if self.should_fail {
                Err(Error::Custom("Intentional test failure".to_string()))
            } else {
                Ok(())
            }
        }

        fn name(&self) -> &'static str {
            self.name
        }
    }

    #[tokio::test]
    async fn test_compensations_lifo_order() {
        // Test that compensations execute in LIFO (most-recent-first) order
        let mut compensations = new_compensations();
        let execution_order = Arc::new(std::sync::Mutex::new(Vec::new()));

        // Add compensations in order: first, second, third
        add_compensation(
            &mut compensations,
            Box::new(MockCompensation::new("first", execution_order.clone())),
        )
        .await;
        add_compensation(
            &mut compensations,
            Box::new(MockCompensation::new("second", execution_order.clone())),
        )
        .await;
        add_compensation(
            &mut compensations,
            Box::new(MockCompensation::new("third", execution_order.clone())),
        )
        .await;

        // Execute compensations
        execute_compensations(&mut compensations).await.unwrap();

        // Verify LIFO order: third (most recent) should execute first
        let order = execution_order.lock().unwrap();
        assert_eq!(order.as_slice(), &["third", "second", "first"]);
    }

    #[tokio::test]
    async fn test_compensations_continues_on_error() {
        // Test that one failed compensation doesn't stop others from executing
        let mut compensations = new_compensations();
        let execution_order = Arc::new(std::sync::Mutex::new(Vec::new()));

        // Add: first (will succeed), second (will fail), third (will succeed)
        add_compensation(
            &mut compensations,
            Box::new(MockCompensation::new("first", execution_order.clone())),
        )
        .await;
        add_compensation(
            &mut compensations,
            Box::new(MockCompensation::failing(
                "second_fails",
                execution_order.clone(),
            )),
        )
        .await;
        add_compensation(
            &mut compensations,
            Box::new(MockCompensation::new("third", execution_order.clone())),
        )
        .await;

        // Execute compensations - should complete without error even though one failed
        let result = execute_compensations(&mut compensations).await;
        assert!(result.is_ok());

        // All three should have executed despite the middle one failing
        let order = execution_order.lock().unwrap();
        assert_eq!(order.as_slice(), &["third", "second_fails", "first"]);
    }

    #[tokio::test]
    async fn test_compensations_empty_queue() {
        // Test that empty queue operations work correctly
        let mut compensations = new_compensations();

        // Execute on empty queue should succeed
        let result = execute_compensations(&mut compensations).await;
        assert!(result.is_ok());

        // Clear on empty queue should succeed
        clear_compensations(&mut compensations).await;

        // Queue should still be empty
        assert!(compensations.is_empty());
    }

    #[tokio::test]
    async fn test_clear_compensations() {
        // Test that clear_compensations removes all actions
        let mut compensations = new_compensations();
        let execution_order = Arc::new(std::sync::Mutex::new(Vec::new()));

        // Add some compensations
        add_compensation(
            &mut compensations,
            Box::new(MockCompensation::new("first", execution_order.clone())),
        )
        .await;
        add_compensation(
            &mut compensations,
            Box::new(MockCompensation::new("second", execution_order.clone())),
        )
        .await;

        // Verify queue is not empty
        assert!(!compensations.is_empty());

        // Clear the queue
        clear_compensations(&mut compensations).await;

        // Verify queue is now empty
        assert!(compensations.is_empty());

        // Execute should do nothing
        execute_compensations(&mut compensations).await.unwrap();
        assert!(execution_order.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_new_compensations_creates_empty_queue() {
        // Test that new_compensations creates an empty queue
        let compensations = new_compensations();
        assert!(compensations.is_empty());
    }
}