fedimint_client/sm/
state.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
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
use std::any::Any;
use std::fmt::Debug;
use std::future::Future;
use std::hash;
use std::io::{Error, Read, Write};
use std::pin::Pin;
use std::sync::Arc;

use fedimint_core::core::{IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
use fedimint_core::encoding::{Decodable, DecodeError, DynEncodable, Encodable};
use fedimint_core::module::registry::ModuleDecoderRegistry;
use fedimint_core::task::{MaybeSend, MaybeSync};
use fedimint_core::util::BoxFuture;
use fedimint_core::{maybe_add_send, maybe_add_send_sync, module_plugin_dyn_newtype_define};

use crate::sm::ClientSMDatabaseTransaction;
use crate::DynGlobalClientContext;

/// Implementors act as state machines that can be executed
pub trait State:
    Debug
    + Clone
    + Eq
    + PartialEq
    + std::hash::Hash
    + Encodable
    + Decodable
    + MaybeSend
    + MaybeSync
    + 'static
{
    /// Additional resources made available in this module's state transitions
    type ModuleContext: Context;

    /// All possible transitions from the current state to other states. See
    /// [`StateTransition`] for details.
    fn transitions(
        &self,
        context: &Self::ModuleContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<Self>>;

    // TODO: move out of this interface into wrapper struct (see OperationState)
    /// Operation this state machine belongs to. See [`OperationId`] for
    /// details.
    fn operation_id(&self) -> OperationId;
}

/// Object-safe version of [`State`]
pub trait IState: Debug + DynEncodable + MaybeSend + MaybeSync {
    fn as_any(&self) -> &(maybe_add_send_sync!(dyn Any));

    /// All possible transitions from the state
    fn transitions(
        &self,
        context: &DynContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<DynState>>;

    /// Operation this state machine belongs to. See [`OperationId`] for
    /// details.
    fn operation_id(&self) -> OperationId;

    /// Clone state
    fn clone(&self, module_instance_id: ModuleInstanceId) -> DynState;

    fn erased_eq_no_instance_id(&self, other: &DynState) -> bool;

    fn erased_hash_no_instance_id(&self, hasher: &mut dyn std::hash::Hasher);
}

/// Something that can be a [`DynContext`] for a state machine
///
/// General purpose code should use [`DynContext`] instead
pub trait IContext: Debug {
    fn as_any(&self) -> &(maybe_add_send_sync!(dyn Any));
    fn module_kind(&self) -> Option<ModuleKind>;
}

module_plugin_dyn_newtype_define! {
    /// A shared context for a module client state machine
    #[derive(Clone)]
    pub DynContext(Arc<IContext>)
}

/// Additional data made available to state machines of a module (e.g. API
/// clients)
pub trait Context: std::fmt::Debug + MaybeSend + MaybeSync + 'static {
    const KIND: Option<ModuleKind>;
}

/// Type-erased version of [`Context`]
impl<T> IContext for T
where
    T: Context + 'static + MaybeSend + MaybeSync,
{
    fn as_any(&self) -> &(maybe_add_send_sync!(dyn Any)) {
        self
    }

    fn module_kind(&self) -> Option<ModuleKind> {
        T::KIND
    }
}

type TriggerFuture = Pin<Box<maybe_add_send!(dyn Future<Output = serde_json::Value> + 'static)>>;

// TODO: remove Arc, maybe make it a fn pointer?
pub(super) type StateTransitionFunction<S> = Arc<
    maybe_add_send_sync!(
        dyn for<'a> Fn(
            &'a mut ClientSMDatabaseTransaction<'_, '_>,
            serde_json::Value,
            S,
        ) -> BoxFuture<'a, S>
    ),
>;

/// Represents one or multiple possible state transitions triggered in a common
/// way
pub struct StateTransition<S> {
    /// Future that will block until a state transition is possible.
    ///
    /// **The trigger future must be idempotent since it might be re-run if the
    /// client is restarted.**
    ///
    /// To wait for a possible state transition it can query external APIs,
    /// subscribe to events emitted by other state machines, etc.
    /// Optionally, it can also return some data that will be given to the
    /// state transition function, see the `transition` docs for details.
    pub trigger: TriggerFuture,
    /// State transition function that, using the output of the `trigger`,
    /// performs the appropriate state transition.
    ///
    /// **This function shall not block on network IO or similar things as all
    /// actual state transitions are run serially.**
    ///
    /// Since the this function can return different output states depending on
    /// the `Value` returned by the `trigger` future it can be used to model
    /// multiple possible state transition at once. E.g. instead of having
    /// two state transitions querying the same API endpoint and each waiting
    /// for a specific value to be returned to trigger their respective state
    /// transition we can have one `trigger` future querying the API and
    /// depending on the return value run different state transitions,
    /// saving network requests.
    pub transition: StateTransitionFunction<S>,
}

impl<S> StateTransition<S> {
    /// Creates a new `StateTransition` where the `trigger` future returns a
    /// value of type `V` that is then given to the `transition` function.
    pub fn new<V, Trigger, TransitionFn>(
        trigger: Trigger,
        transition: TransitionFn,
    ) -> StateTransition<S>
    where
        S: MaybeSend + MaybeSync + Clone + 'static,
        V: serde::Serialize + serde::de::DeserializeOwned + Send,
        Trigger: Future<Output = V> + MaybeSend + 'static,
        TransitionFn: for<'a> Fn(&'a mut ClientSMDatabaseTransaction<'_, '_>, V, S) -> BoxFuture<'a, S>
            + MaybeSend
            + MaybeSync
            + Clone
            + 'static,
    {
        StateTransition {
            trigger: Box::pin(async {
                let val = trigger.await;
                serde_json::to_value(val).expect("Value could not be serialized")
            }),
            transition: Arc::new(move |dbtx, val, state| {
                let transition = transition.clone();
                Box::pin(async move {
                    let typed_val: V = serde_json::from_value(val)
                        .expect("Deserialize trigger return value failed");
                    transition(dbtx, typed_val, state.clone()).await
                })
            }),
        }
    }
}

impl<T> IState for T
where
    T: State,
{
    fn as_any(&self) -> &(maybe_add_send_sync!(dyn Any)) {
        self
    }

    fn transitions(
        &self,
        context: &DynContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<DynState>> {
        <T as State>::transitions(
            self,
            context.as_any().downcast_ref().expect("Wrong module"),
            global_context,
        )
        .into_iter()
        .map(|st| StateTransition {
            trigger: st.trigger,
            transition: Arc::new(
                move |dbtx: &mut ClientSMDatabaseTransaction<'_, '_>, val, state: DynState| {
                    let transition = st.transition.clone();
                    Box::pin(async move {
                        let new_state = transition(
                            dbtx,
                            val,
                            state
                                .as_any()
                                .downcast_ref::<T>()
                                .expect("Wrong module")
                                .clone(),
                        )
                        .await;
                        DynState::from_typed(state.module_instance_id(), new_state)
                    })
                },
            ),
        })
        .collect()
    }

    fn operation_id(&self) -> OperationId {
        <T as State>::operation_id(self)
    }

    fn clone(&self, module_instance_id: ModuleInstanceId) -> DynState {
        DynState::from_typed(module_instance_id, <T as Clone>::clone(self))
    }

    fn erased_eq_no_instance_id(&self, other: &DynState) -> bool {
        let other: &T = other
            .as_any()
            .downcast_ref()
            .expect("Type is ensured in previous step");

        self == other
    }

    fn erased_hash_no_instance_id(&self, mut hasher: &mut dyn std::hash::Hasher) {
        self.hash(&mut hasher);
    }
}

/// A type-erased state of a state machine belonging to a module instance, see
/// [`State`]
pub struct DynState(
    Box<maybe_add_send_sync!(dyn IState + 'static)>,
    ModuleInstanceId,
);

impl IState for DynState {
    fn as_any(&self) -> &(maybe_add_send_sync!(dyn Any)) {
        (**self).as_any()
    }

    fn transitions(
        &self,
        context: &DynContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<DynState>> {
        (**self).transitions(context, global_context)
    }

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

    fn clone(&self, module_instance_id: ModuleInstanceId) -> DynState {
        (**self).clone(module_instance_id)
    }

    fn erased_eq_no_instance_id(&self, other: &DynState) -> bool {
        (**self).erased_eq_no_instance_id(other)
    }

    fn erased_hash_no_instance_id(&self, hasher: &mut dyn std::hash::Hasher) {
        (**self).erased_hash_no_instance_id(hasher);
    }
}

impl IntoDynInstance for DynState {
    type DynType = DynState;

    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
        assert_eq!(instance_id, self.1);
        self
    }
}

impl std::ops::Deref for DynState {
    type Target = maybe_add_send_sync!(dyn IState + 'static);

    fn deref(&self) -> &<Self as std::ops::Deref>::Target {
        &*self.0
    }
}

impl hash::Hash for DynState {
    fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
        self.1.hash(hasher);
        self.0.erased_hash_no_instance_id(hasher);
    }
}

impl DynState {
    pub fn module_instance_id(&self) -> ModuleInstanceId {
        self.1
    }

    pub fn from_typed<I>(module_instance_id: ModuleInstanceId, typed: I) -> Self
    where
        I: IState + 'static,
    {
        Self(Box::new(typed), module_instance_id)
    }

    pub fn from_parts(
        module_instance_id: ::fedimint_core::core::ModuleInstanceId,
        dynbox: Box<maybe_add_send_sync!(dyn IState + 'static)>,
    ) -> Self {
        Self(dynbox, module_instance_id)
    }
}

impl std::fmt::Debug for DynState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(&self.0, f)
    }
}

impl std::ops::DerefMut for DynState {
    fn deref_mut(&mut self) -> &mut <Self as std::ops::Deref>::Target {
        &mut *self.0
    }
}

impl Clone for DynState {
    fn clone(&self) -> Self {
        self.0.clone(self.1)
    }
}

impl PartialEq for DynState {
    fn eq(&self, other: &Self) -> bool {
        if self.1 != other.1 {
            return false;
        }
        self.erased_eq_no_instance_id(other)
    }
}
impl Eq for DynState {}

impl Encodable for DynState {
    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, std::io::Error> {
        self.1.consensus_encode(writer)?;
        self.0.consensus_encode_dyn(writer)
    }
}
impl Decodable for DynState {
    fn consensus_decode<R: std::io::Read>(
        reader: &mut R,
        decoders: &::fedimint_core::module::registry::ModuleDecoderRegistry,
    ) -> Result<Self, fedimint_core::encoding::DecodeError> {
        let module_id = fedimint_core::core::ModuleInstanceId::consensus_decode(reader, decoders)?;
        decoders
            .get_expect(module_id)
            .decode_partial(reader, module_id, decoders)
    }
}

impl DynState {
    /// `true` if this state allows no further transitions
    pub fn is_terminal(
        &self,
        context: &DynContext,
        global_context: &DynGlobalClientContext,
    ) -> bool {
        self.transitions(context, global_context).is_empty()
    }
}

#[derive(Debug)]
pub struct OperationState<S> {
    pub operation_id: OperationId,
    pub state: S,
}

/// Wrapper for states that don't want to carry around their operation id. `S`
/// is allowed to panic when `operation_id` is called.
impl<S> State for OperationState<S>
where
    S: State,
{
    type ModuleContext = S::ModuleContext;

    fn transitions(
        &self,
        context: &Self::ModuleContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<Self>> {
        let transitions: Vec<StateTransition<OperationState<S>>> = self
            .state
            .transitions(context, global_context)
            .into_iter()
            .map(
                |StateTransition {
                     trigger,
                     transition,
                 }| {
                    let op_transition: StateTransitionFunction<Self> =
                        Arc::new(move |dbtx, value, op_state| {
                            let transition = transition.clone();
                            Box::pin(async move {
                                let state = transition(dbtx, value, op_state.state).await;
                                OperationState {
                                    operation_id: op_state.operation_id,
                                    state,
                                }
                            })
                        });

                    StateTransition {
                        trigger,
                        transition: op_transition,
                    }
                },
            )
            .collect();
        transitions
    }

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

// TODO: can we get rid of `GC`? Maybe make it an associated type of `State`
// instead?
impl<S> IntoDynInstance for OperationState<S>
where
    S: State,
{
    type DynType = DynState;

    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
        DynState::from_typed(instance_id, self)
    }
}

impl<S> Encodable for OperationState<S>
where
    S: State,
{
    fn consensus_encode<W: Write>(&self, writer: &mut W) -> Result<usize, Error> {
        let mut len = 0;
        len += self.operation_id.consensus_encode(writer)?;
        len += self.state.consensus_encode(writer)?;
        Ok(len)
    }
}

impl<S> Decodable for OperationState<S>
where
    S: State,
{
    fn consensus_decode<R: Read>(
        read: &mut R,
        modules: &ModuleDecoderRegistry,
    ) -> Result<Self, DecodeError> {
        let operation_id = OperationId::consensus_decode(read, modules)?;
        let state = S::consensus_decode(read, modules)?;

        Ok(OperationState {
            operation_id,
            state,
        })
    }
}

// TODO: derive after getting rid of `GC` type arg
impl<S> PartialEq for OperationState<S>
where
    S: State,
{
    fn eq(&self, other: &Self) -> bool {
        self.operation_id.eq(&other.operation_id) && self.state.eq(&other.state)
    }
}

impl<S> Eq for OperationState<S> where S: State {}

impl<S> hash::Hash for OperationState<S>
where
    S: hash::Hash,
{
    fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
        self.operation_id.hash(hasher);
        self.state.hash(hasher);
    }
}

impl<S> Clone for OperationState<S>
where
    S: State,
{
    fn clone(&self) -> Self {
        OperationState {
            operation_id: self.operation_id,
            state: self.state.clone(),
        }
    }
}