fedimint_mint_client/
oob.rs

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
use std::sync::Arc;
use std::time::SystemTime;

use fedimint_client::module::OutPointRange;
use fedimint_client::sm::{ClientSMDatabaseTransaction, State, StateTransition};
use fedimint_client::transaction::{ClientInput, ClientInputBundle, ClientInputSM};
use fedimint_client::DynGlobalClientContext;
use fedimint_core::core::OperationId;
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::{runtime, Amount, TransactionId};
use fedimint_mint_common::MintInput;

use crate::input::{
    MintInputCommon, MintInputStateMachine, MintInputStateRefundedBundle, MintInputStates,
};
use crate::{MintClientContext, MintClientStateMachines, SpendableNote};

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub enum MintOOBStatesV0 {
    /// The e-cash has been taken out of the wallet and we are waiting for the
    /// recipient to reissue it or the user to trigger a refund.
    Created(MintOOBStatesCreated),
    /// The user has triggered a refund.
    UserRefund(MintOOBStatesUserRefund),
    /// The timeout of this out-of-band transaction was hit and we attempted to
    /// refund. This refund *failing* is the expected behavior since the
    /// recipient is supposed to have already reissued it.
    TimeoutRefund(MintOOBStatesTimeoutRefund),
}

#[cfg_attr(doc, aquamarine::aquamarine)]
/// State machine managing e-cash that has been taken out of the wallet for
/// out-of-band transmission.
///
/// ```mermaid
/// graph LR
///     Created -- User triggered refund --> RefundU["User Refund"]
///     Created -- Timeout triggered refund --> RefundT["Timeout Refund"]
/// ```
#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub enum MintOOBStates {
    /// The e-cash has been taken out of the wallet and we are waiting for the
    /// recipient to reissue it or the user to trigger a refund.
    CreatedMulti(MintOOBStatesCreatedMulti),
    /// The user has triggered a refund.
    UserRefundMulti(MintOOBStatesUserRefundMulti),
    /// The timeout of this out-of-band transaction was hit and we attempted to
    /// refund. This refund *failing* is the expected behavior since the
    /// recipient is supposed to have already reissued it.
    TimeoutRefund(MintOOBStatesTimeoutRefund),

    // States we want to drop eventually (that's why they are last)
    // -
    /// Obsoleted, legacy from [`MintOOBStatesV0`], like
    /// [`MintOOBStates::CreatedMulti`] but for a single note only.
    Created(MintOOBStatesCreated),
    /// Obsoleted, legacy from [`MintOOBStatesV0`], like
    /// [`MintOOBStates::UserRefundMulti`] but for single note only
    UserRefund(MintOOBStatesUserRefund),
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct MintOOBStateMachineV0 {
    pub(crate) operation_id: OperationId,
    pub(crate) state: MintOOBStatesV0,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct MintOOBStateMachine {
    pub(crate) operation_id: OperationId,
    pub(crate) state: MintOOBStates,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct MintOOBStatesCreated {
    pub(crate) amount: Amount,
    pub(crate) spendable_note: SpendableNote,
    pub(crate) timeout: SystemTime,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct MintOOBStatesCreatedMulti {
    pub(crate) spendable_notes: Vec<(Amount, SpendableNote)>,
    pub(crate) timeout: SystemTime,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct MintOOBStatesUserRefundMulti {
    /// The txid we are hoping succeeds refunding all notes in one go
    pub(crate) refund_txid: TransactionId,
    /// The notes we are going to refund individually if it doesn't
    pub(crate) spendable_notes: Vec<(Amount, SpendableNote)>,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct MintOOBStatesUserRefund {
    pub(crate) refund_txid: TransactionId,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct MintOOBStatesTimeoutRefund {
    pub(crate) refund_txid: TransactionId,
}

impl State for MintOOBStateMachine {
    type ModuleContext = MintClientContext;

    fn transitions(
        &self,
        context: &Self::ModuleContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<Self>> {
        match &self.state {
            MintOOBStates::Created(created) => {
                created.transitions(self.operation_id, context, global_context)
            }
            MintOOBStates::CreatedMulti(created) => {
                created.transitions(self.operation_id, context, global_context)
            }
            MintOOBStates::UserRefund(_)
            | MintOOBStates::TimeoutRefund(_)
            | MintOOBStates::UserRefundMulti(_) => {
                vec![]
            }
        }
    }

    fn operation_id(&self) -> OperationId {
        self.operation_id
    }
}

impl MintOOBStatesCreated {
    fn transitions(
        &self,
        operation_id: OperationId,
        context: &MintClientContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<MintOOBStateMachine>> {
        let user_cancel_gc = global_context.clone();
        let timeout_cancel_gc = global_context.clone();
        vec![
            StateTransition::new(
                context.await_cancel_oob_payment(operation_id),
                move |dbtx, (), state| {
                    Box::pin(transition_user_cancel(state, dbtx, user_cancel_gc.clone()))
                },
            ),
            StateTransition::new(
                await_timeout_cancel(self.timeout),
                move |dbtx, (), state| {
                    Box::pin(transition_timeout_cancel(
                        state,
                        dbtx,
                        timeout_cancel_gc.clone(),
                    ))
                },
            ),
        ]
    }
}

impl MintOOBStatesCreatedMulti {
    fn transitions(
        &self,
        operation_id: OperationId,
        context: &MintClientContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<MintOOBStateMachine>> {
        let user_cancel_gc = global_context.clone();
        let timeout_cancel_gc = global_context.clone();
        vec![
            StateTransition::new(
                context.await_cancel_oob_payment(operation_id),
                move |dbtx, (), state| {
                    Box::pin(transition_user_cancel_multi(
                        state,
                        dbtx,
                        user_cancel_gc.clone(),
                    ))
                },
            ),
            StateTransition::new(
                await_timeout_cancel(self.timeout),
                move |dbtx, (), state| {
                    Box::pin(transition_timeout_cancel_multi(
                        state,
                        dbtx,
                        timeout_cancel_gc.clone(),
                    ))
                },
            ),
        ]
    }
}

async fn transition_user_cancel(
    prev_state: MintOOBStateMachine,
    dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
    global_context: DynGlobalClientContext,
) -> MintOOBStateMachine {
    let (amount, spendable_note) = match prev_state.state {
        MintOOBStates::Created(created) => (created.amount, created.spendable_note),
        _ => panic!("Invalid previous state: {prev_state:?}"),
    };

    let refund_txid = try_cancel_oob_spend(
        dbtx,
        prev_state.operation_id,
        amount,
        spendable_note,
        global_context,
    )
    .await;
    MintOOBStateMachine {
        operation_id: prev_state.operation_id,
        state: MintOOBStates::UserRefund(MintOOBStatesUserRefund { refund_txid }),
    }
}

async fn transition_user_cancel_multi(
    prev_state: MintOOBStateMachine,
    dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
    global_context: DynGlobalClientContext,
) -> MintOOBStateMachine {
    let spendable_notes = match prev_state.state {
        MintOOBStates::CreatedMulti(created) => created.spendable_notes,
        _ => panic!("Invalid previous state: {prev_state:?}"),
    };

    let refund_txid = try_cancel_oob_spend_multi(
        dbtx,
        prev_state.operation_id,
        spendable_notes.clone(),
        global_context,
    )
    .await;
    MintOOBStateMachine {
        operation_id: prev_state.operation_id,
        state: MintOOBStates::UserRefundMulti(MintOOBStatesUserRefundMulti {
            refund_txid,
            spendable_notes,
        }),
    }
}

async fn await_timeout_cancel(deadline: SystemTime) {
    if let Ok(time_until_deadline) = deadline.duration_since(fedimint_core::time::now()) {
        runtime::sleep(time_until_deadline).await;
    }
}

async fn transition_timeout_cancel(
    prev_state: MintOOBStateMachine,
    dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
    global_context: DynGlobalClientContext,
) -> MintOOBStateMachine {
    let (amount, spendable_note) = match prev_state.state {
        MintOOBStates::Created(created) => (created.amount, created.spendable_note),
        _ => panic!("Invalid previous state: {prev_state:?}"),
    };

    let refund_txid = try_cancel_oob_spend(
        dbtx,
        prev_state.operation_id,
        amount,
        spendable_note,
        global_context,
    )
    .await;
    MintOOBStateMachine {
        operation_id: prev_state.operation_id,
        state: MintOOBStates::TimeoutRefund(MintOOBStatesTimeoutRefund { refund_txid }),
    }
}

async fn transition_timeout_cancel_multi(
    prev_state: MintOOBStateMachine,
    dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
    global_context: DynGlobalClientContext,
) -> MintOOBStateMachine {
    let spendable_notes = match prev_state.state {
        MintOOBStates::CreatedMulti(created) => created.spendable_notes,
        _ => panic!("Invalid previous state: {prev_state:?}"),
    };

    let refund_txid = try_cancel_oob_spend_multi(
        dbtx,
        prev_state.operation_id,
        spendable_notes,
        global_context,
    )
    .await;
    MintOOBStateMachine {
        operation_id: prev_state.operation_id,
        state: MintOOBStates::TimeoutRefund(MintOOBStatesTimeoutRefund { refund_txid }),
    }
}

async fn try_cancel_oob_spend(
    dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
    operation_id: OperationId,
    amount: Amount,
    spendable_note: SpendableNote,
    global_context: DynGlobalClientContext,
) -> TransactionId {
    try_cancel_oob_spend_multi(
        dbtx,
        operation_id,
        vec![(amount, spendable_note)],
        global_context,
    )
    .await
}

async fn try_cancel_oob_spend_multi(
    dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
    operation_id: OperationId,
    spendable_notes: Vec<(Amount, SpendableNote)>,
    global_context: DynGlobalClientContext,
) -> TransactionId {
    let inputs = spendable_notes
        .clone()
        .into_iter()
        .map(|(amount, spendable_note)| ClientInput {
            input: MintInput::new_v0(amount, spendable_note.note()),
            keys: vec![spendable_note.spend_key],
            amount,
        })
        .collect();

    let sm = ClientInputSM {
        state_machines: Arc::new(move |out_point_range: OutPointRange| {
            debug_assert_eq!(out_point_range.count(), spendable_notes.len());
            vec![MintClientStateMachines::Input(MintInputStateMachine {
                common: MintInputCommon {
                    operation_id,
                    out_point_range,
                },
                // When canceling OOB, we are reating the multi-refund input already here.
                // So  we can cut straight to
                // `MintInputStates::RefundedMulti` state. If the reund tx fails, it will
                // retry using per-note refund again.
                state: MintInputStates::RefundedBundle(MintInputStateRefundedBundle {
                    refund_txid: out_point_range.txid(),
                    spendable_notes: spendable_notes.clone(),
                }),
            })]
        }),
    };

    global_context
        .claim_inputs(dbtx, ClientInputBundle::new(inputs, vec![sm]))
        .await
        .expect("Cannot claim input, additional funding needed")
        .0
}