Skip to main content

fedimint_client_module/module/
mod.rs

1use core::fmt;
2use std::any::Any;
3use std::collections::BTreeSet;
4use std::fmt::Debug;
5use std::pin::Pin;
6use std::sync::{Arc, Weak};
7use std::{ffi, marker, ops};
8
9use bitcoin::secp256k1::PublicKey;
10use fedimint_api_client::api::{DynGlobalApi, DynModuleApi};
11use fedimint_core::config::ClientConfig;
12use fedimint_core::core::{
13    Account, Decoder, DynInput, DynOutput, IInput, IntoDynInstance, ModuleInstanceId, ModuleKind,
14    OperationId,
15};
16use fedimint_core::db::{
17    AutocommitError, Database, DatabaseTransaction, GlobalDBTxAccessToken, NonCommittable,
18};
19use fedimint_core::invite_code::InviteCode;
20use fedimint_core::module::registry::{ModuleDecoderRegistry, ModuleRegistry};
21use fedimint_core::module::{AmountUnit, Amounts, CommonModuleInit, ModuleCommon, ModuleInit};
22use fedimint_core::task::{MaybeSend, MaybeSync};
23use fedimint_core::util::{BoxStream, FmtCompact as _};
24use fedimint_core::{
25    Amount, OutPoint, PeerId, apply, async_trait_maybe_send, dyn_newtype_define, maybe_add_send,
26    maybe_add_send_sync,
27};
28use fedimint_eventlog::{
29    DBTransactionEventLogExt, Event, EventKind, EventLogId, EventPersistence, PersistedLogEntry,
30};
31use fedimint_logging::LOG_CLIENT;
32use futures::{Stream, StreamExt};
33use serde::Serialize;
34use serde::de::DeserializeOwned;
35use tracing::warn;
36
37use self::init::ClientModuleInit;
38use crate::error::{
39    ClientModuleError, ModuleLookupError, OperationAlreadyExistsError, OperationLookupError,
40    OperationNotFoundError, TransactionSubmitError,
41};
42use crate::module::recovery::{DynModuleBackup, ModuleBackup};
43use crate::oplog::{IOperationLog, OperationLogEntry, UpdateStreamOrOutcome};
44use crate::sm::executor::{ActiveStateKey, IExecutor, InactiveStateKey};
45use crate::sm::{self, ActiveStateMeta, Context, DynContext, DynState, InactiveStateMeta, State};
46use crate::transaction::{
47    ClientInputBundle, ClientOutputBundle, FeeQuote, FeeQuoteRequest, TransactionBuilder,
48};
49use crate::{AddStateMachinesResult, InstancelessDynClientInputBundle, TransactionUpdates, oplog};
50
51pub mod init;
52pub mod recovery;
53
54pub type ClientModuleRegistry = ModuleRegistry<DynClientModule>;
55
56/// A serialized module event prepared for atomic transaction submission.
57///
58/// Created with [`ClientContext::make_event`]. The submitting context supplies
59/// the module instance ID, just as it does for [`ClientContext::log_event`].
60#[derive(Clone)]
61pub struct ClientModuleEvent {
62    module_kind: Option<ModuleKind>,
63    kind: EventKind,
64    payload: serde_json::Value,
65    persistence: EventPersistence,
66}
67
68/// A fedimint-client interface exposed to client modules
69///
70/// To break the dependency of the client modules on the whole fedimint client
71/// and in particular the `fedimint-client` crate, the module gets access to an
72/// interface, that is implemented by the `Client`.
73///
74/// This allows lose coupling, less recompilation and better control and
75/// understanding of what functionality of the Client the modules get access to.
76#[apply(async_trait_maybe_send!)]
77pub trait ClientContextIface: MaybeSend + MaybeSync {
78    fn get_module(&self, instance: ModuleInstanceId) -> &maybe_add_send_sync!(dyn IClientModule);
79    fn api_clone(&self) -> DynGlobalApi;
80    fn decoders(&self) -> &ModuleDecoderRegistry;
81    async fn finalize_and_submit_transaction(
82        &self,
83        operation_id: OperationId,
84        operation_type: &str,
85        operation_meta_gen: Box<maybe_add_send_sync!(dyn Fn(OutPointRange) -> serde_json::Value)>,
86        tx_builder: TransactionBuilder,
87    ) -> Result<OutPointRange, TransactionSubmitError>;
88
89    async fn finalize_and_submit_transaction_dbtx(
90        &self,
91        dbtx: &mut DatabaseTransaction<'_>,
92        operation_id: OperationId,
93        operation_type: &str,
94        operation_meta_gen: Box<maybe_add_send_sync!(dyn Fn(OutPointRange) -> serde_json::Value)>,
95        tx_builder: TransactionBuilder,
96    ) -> Result<OutPointRange, TransactionSubmitError>;
97
98    // TODO: unify
99    async fn finalize_and_submit_transaction_inner(
100        &self,
101        dbtx: &mut DatabaseTransaction<'_>,
102        operation_id: OperationId,
103        tx_builder: TransactionBuilder,
104    ) -> Result<OutPointRange, TransactionSubmitError>;
105
106    /// Computes the fee finalizing and submitting a transaction with the
107    /// explicit items described by `request` would incur, without submitting
108    /// anything. See `Client::fee_quote`.
109    async fn fee_quote(
110        &self,
111        operation_id: OperationId,
112        request: FeeQuoteRequest,
113    ) -> Result<FeeQuote, TransactionSubmitError>;
114
115    /// The client's balance for `unit`, held by the primary module. See
116    /// `Client::get_balance_for_unit`.
117    async fn get_balance_for_unit(
118        &self,
119        unit: AmountUnit,
120        account: Account,
121    ) -> Result<Amount, ModuleLookupError>;
122
123    /// Whether the primary module for `unit` can hold a balance for
124    /// `account`. See `Client::supports_account`.
125    fn supports_account(&self, unit: AmountUnit, account: Account) -> bool;
126
127    /// The account `operation_id` acts on. See
128    /// `Client::operation_account_dbtx`.
129    async fn operation_account_dbtx(
130        &self,
131        dbtx: &mut DatabaseTransaction<'_>,
132        operation_id: OperationId,
133    ) -> Account;
134
135    /// See `Client::set_operation_account_dbtx`.
136    async fn set_operation_account_dbtx(
137        &self,
138        dbtx: &mut DatabaseTransaction<'_>,
139        operation_id: OperationId,
140        account: Account,
141    );
142
143    async fn transaction_updates(&self, operation_id: OperationId) -> TransactionUpdates;
144
145    async fn await_primary_module_outputs(
146        &self,
147        operation_id: OperationId,
148        // TODO: make `impl Iterator<Item = ...>`
149        outputs: Vec<OutPoint>,
150    ) -> Result<(), TransactionSubmitError>;
151
152    fn operation_log(&self) -> &dyn IOperationLog;
153
154    async fn has_active_states(&self, operation_id: OperationId) -> bool;
155
156    /// Waits until no state machine of the operation is running any more.
157    /// See `Client::await_no_active_states`.
158    async fn await_no_active_states(&self, operation_id: OperationId);
159
160    async fn operation_exists(&self, operation_id: OperationId) -> bool;
161
162    async fn config(&self) -> ClientConfig;
163
164    fn db(&self) -> &Database;
165
166    fn executor(&self) -> &(maybe_add_send_sync!(dyn IExecutor + 'static));
167
168    async fn invite_code(&self, peer: PeerId) -> Option<InviteCode>;
169
170    fn get_internal_payment_markers(&self) -> Result<(PublicKey, u64), bitcoin::secp256k1::Error>;
171
172    #[allow(clippy::too_many_arguments)]
173    async fn log_event_json(
174        &self,
175        dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
176        module_kind: Option<ModuleKind>,
177        module_id: ModuleInstanceId,
178        kind: EventKind,
179        payload: serde_json::Value,
180        persist: EventPersistence,
181    );
182
183    async fn read_operation_active_states<'dbtx>(
184        &self,
185        operation_id: OperationId,
186        module_id: ModuleInstanceId,
187        dbtx: &'dbtx mut DatabaseTransaction<'_>,
188    ) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (ActiveStateKey, ActiveStateMeta)> + 'dbtx)>>;
189
190    async fn read_operation_inactive_states<'dbtx>(
191        &self,
192        operation_id: OperationId,
193        module_id: ModuleInstanceId,
194        dbtx: &'dbtx mut DatabaseTransaction<'_>,
195    ) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (InactiveStateKey, InactiveStateMeta)> + 'dbtx)>>;
196}
197
198/// A final, fully initialized client
199///
200/// Client modules need to be able to access a `Client` they are a part
201/// of. To break the circular dependency, the final `Client` is passed
202/// after `Client` was built via a shared state.
203#[derive(Clone, Default)]
204pub struct FinalClientIface(Arc<std::sync::OnceLock<Weak<dyn ClientContextIface>>>);
205
206impl FinalClientIface {
207    /// Get a temporary strong reference to [`ClientContextIface`]
208    ///
209    /// Care must be taken to not let the user take ownership of this value,
210    /// and not store it elsewhere permanently either, as it could prevent
211    /// the cleanup of the Client.
212    pub(crate) fn get(&self) -> Arc<dyn ClientContextIface> {
213        self.0
214            .get()
215            .expect("client must be already set")
216            .upgrade()
217            .expect("client module context must not be use past client shutdown")
218    }
219
220    pub fn set(&self, client: Weak<dyn ClientContextIface>) {
221        self.0.set(client).expect("FinalLazyClient already set");
222    }
223}
224
225impl fmt::Debug for FinalClientIface {
226    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227        f.write_str("FinalClientIface")
228    }
229}
230/// A Client context for a [`ClientModule`] `M`
231///
232/// Client modules can interact with the whole
233/// client through this struct.
234pub struct ClientContext<M> {
235    client: FinalClientIface,
236    module_instance_id: ModuleInstanceId,
237    global_dbtx_access_token: GlobalDBTxAccessToken,
238    module_db: Database,
239    _marker: marker::PhantomData<M>,
240}
241
242impl<M> Clone for ClientContext<M> {
243    fn clone(&self) -> Self {
244        Self {
245            client: self.client.clone(),
246            module_db: self.module_db.clone(),
247            module_instance_id: self.module_instance_id,
248            _marker: marker::PhantomData,
249            global_dbtx_access_token: self.global_dbtx_access_token,
250        }
251    }
252}
253
254/// A reference back to itself that the module cacn get from the
255/// [`ClientContext`]
256pub struct ClientContextSelfRef<'s, M> {
257    // we are OK storing `ClientStrong` here, because of the `'s` preventing `Self` from being
258    // stored permanently somewhere
259    client: Arc<dyn ClientContextIface>,
260    module_instance_id: ModuleInstanceId,
261    _marker: marker::PhantomData<&'s M>,
262}
263
264impl<M> ops::Deref for ClientContextSelfRef<'_, M>
265where
266    M: ClientModule,
267{
268    type Target = M;
269
270    fn deref(&self) -> &Self::Target {
271        self.client
272            .get_module(self.module_instance_id)
273            .as_any()
274            .downcast_ref::<M>()
275            .unwrap_or_else(|| panic!("Module is not of type {}", std::any::type_name::<M>()))
276    }
277}
278
279impl<M> fmt::Debug for ClientContext<M> {
280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281        f.write_str("ClientContext")
282    }
283}
284
285impl<M> ClientContext<M>
286where
287    M: ClientModule,
288{
289    pub fn new(
290        client: FinalClientIface,
291        module_instance_id: ModuleInstanceId,
292        global_dbtx_access_token: GlobalDBTxAccessToken,
293        module_db: Database,
294    ) -> Self {
295        Self {
296            client,
297            module_instance_id,
298            global_dbtx_access_token,
299            module_db,
300            _marker: marker::PhantomData,
301        }
302    }
303
304    /// Get a reference back to client module from the [`Self`]
305    ///
306    /// It's often necessary for a client module to "move self"
307    /// by-value, especially due to async lifetimes issues.
308    /// Clients usually work with `&mut self`, which can't really
309    /// work in such context.
310    ///
311    /// Fortunately [`ClientContext`] is `Clone` and `Send, and
312    /// can be used to recover the reference to the module at later
313    /// time.
314    #[allow(clippy::needless_lifetimes)] // just for explicitiness
315    pub fn self_ref(&self) -> ClientContextSelfRef<'_, M> {
316        ClientContextSelfRef {
317            client: self.client.get(),
318            module_instance_id: self.module_instance_id,
319            _marker: marker::PhantomData,
320        }
321    }
322
323    /// Get a reference to a global Api handle
324    pub fn global_api(&self) -> DynGlobalApi {
325        self.client.get().api_clone()
326    }
327
328    /// Get a reference to a module Api handle
329    pub fn module_api(&self) -> DynModuleApi {
330        self.global_api().with_module(self.module_instance_id)
331    }
332
333    /// A set of all decoders of all modules of the client
334    pub fn decoders(&self) -> ModuleDecoderRegistry {
335        Clone::clone(self.client.get().decoders())
336    }
337
338    pub fn input_from_dyn<'i>(
339        &self,
340        input: &'i DynInput,
341    ) -> Option<&'i <M::Common as ModuleCommon>::Input> {
342        (input.module_instance_id() == self.module_instance_id).then(|| {
343            input
344                .as_any()
345                .downcast_ref::<<M::Common as ModuleCommon>::Input>()
346                .unwrap_or_else(|| {
347                    panic!("instance_id {} just checked", input.module_instance_id())
348                })
349        })
350    }
351
352    pub fn output_from_dyn<'o>(
353        &self,
354        output: &'o DynOutput,
355    ) -> Option<&'o <M::Common as ModuleCommon>::Output> {
356        (output.module_instance_id() == self.module_instance_id).then(|| {
357            output
358                .as_any()
359                .downcast_ref::<<M::Common as ModuleCommon>::Output>()
360                .unwrap_or_else(|| {
361                    panic!("instance_id {} just checked", output.module_instance_id())
362                })
363        })
364    }
365
366    pub fn map_dyn<'s, 'i, 'o, I>(
367        &'s self,
368        typed: impl IntoIterator<Item = I> + 'i,
369    ) -> impl Iterator<Item = <I as IntoDynInstance>::DynType> + 'o
370    where
371        I: IntoDynInstance,
372        'i: 'o,
373        's: 'o,
374    {
375        typed.into_iter().map(|i| self.make_dyn(i))
376    }
377
378    /// Turn a typed output into a dyn version
379    pub fn make_dyn_output(&self, output: <M::Common as ModuleCommon>::Output) -> DynOutput {
380        self.make_dyn(output)
381    }
382
383    /// Turn a typed input into a dyn version
384    pub fn make_dyn_input(&self, input: <M::Common as ModuleCommon>::Input) -> DynInput {
385        self.make_dyn(input)
386    }
387
388    /// Turn a `typed` into a dyn version
389    pub fn make_dyn<I>(&self, typed: I) -> <I as IntoDynInstance>::DynType
390    where
391        I: IntoDynInstance,
392    {
393        typed.into_dyn(self.module_instance_id)
394    }
395
396    /// Turn a typed [`ClientOutputBundle`] into a dyn version
397    pub fn make_client_outputs<O, S>(&self, output: ClientOutputBundle<O, S>) -> ClientOutputBundle
398    where
399        O: IntoDynInstance<DynType = DynOutput> + 'static,
400        S: IntoDynInstance<DynType = DynState> + 'static,
401    {
402        self.make_dyn(output)
403    }
404
405    /// Turn a typed [`ClientInputBundle`] into a dyn version
406    pub fn make_client_inputs<I, S>(&self, inputs: ClientInputBundle<I, S>) -> ClientInputBundle
407    where
408        I: IntoDynInstance<DynType = DynInput> + 'static,
409        S: IntoDynInstance<DynType = DynState> + 'static,
410    {
411        self.make_dyn(inputs)
412    }
413
414    pub fn make_dyn_state<S>(&self, sm: S) -> DynState
415    where
416        S: sm::IState + 'static,
417    {
418        DynState::from_typed(self.module_instance_id, sm)
419    }
420
421    pub async fn finalize_and_submit_transaction<F, Meta>(
422        &self,
423        operation_id: OperationId,
424        operation_type: &str,
425        operation_meta_gen: F,
426        tx_builder: TransactionBuilder,
427    ) -> Result<OutPointRange, TransactionSubmitError>
428    where
429        F: Fn(OutPointRange) -> Meta + Clone + MaybeSend + MaybeSync + 'static,
430        Meta: serde::Serialize + MaybeSend,
431    {
432        self.client
433            .get()
434            .finalize_and_submit_transaction(
435                operation_id,
436                operation_type,
437                Box::new(move |out_point_range| {
438                    serde_json::to_value(operation_meta_gen(out_point_range)).expect("Can't fail")
439                }),
440                tx_builder,
441            )
442            .await
443    }
444
445    /// Submits a new operation and logs its announcing events in one commit.
446    ///
447    /// Finalization errors roll back both the operation and the events. Commit
448    /// conflicts retry the entire transaction, including event logging.
449    pub async fn finalize_and_submit_transaction_with_events<F, Meta>(
450        &self,
451        operation_id: OperationId,
452        operation_type: &str,
453        operation_meta_gen: F,
454        tx_builder: TransactionBuilder,
455        events: Vec<ClientModuleEvent>,
456    ) -> Result<OutPointRange, TransactionSubmitError>
457    where
458        F: Fn(OutPointRange) -> Meta + Clone + MaybeSend + MaybeSync + 'static,
459        Meta: serde::Serialize + MaybeSend,
460    {
461        self.module_db()
462            .autocommit(
463                |dbtx, _| {
464                    let operation_meta_gen = operation_meta_gen.clone();
465                    let tx_builder = tx_builder.clone();
466                    let events = &events;
467                    Box::pin(async move {
468                        let range = self
469                            .finalize_and_submit_transaction_dbtx(
470                                dbtx,
471                                operation_id,
472                                operation_type,
473                                operation_meta_gen,
474                                tx_builder,
475                            )
476                            .await?;
477                        for event in events {
478                            self.log_serialized_event(dbtx, event.clone()).await;
479                        }
480                        Ok(range)
481                    })
482                },
483                Some(100),
484            )
485            .await
486            .map_err(|error| match error {
487                AutocommitError::ClosureError { error, .. } => error,
488                AutocommitError::CommitFailed { last_error, .. } => {
489                    TransactionSubmitError::Database(last_error)
490                }
491            })
492    }
493
494    pub async fn finalize_and_submit_transaction_dbtx<F, Meta>(
495        &self,
496        dbtx: &mut DatabaseTransaction<'_>,
497        operation_id: OperationId,
498        operation_type: &str,
499        operation_meta_gen: F,
500        tx_builder: TransactionBuilder,
501    ) -> Result<OutPointRange, TransactionSubmitError>
502    where
503        F: Fn(OutPointRange) -> Meta + MaybeSend + MaybeSync + 'static,
504        Meta: serde::Serialize + MaybeSend,
505    {
506        self.client
507            .get()
508            .finalize_and_submit_transaction_dbtx(
509                &mut dbtx.global_dbtx(self.global_dbtx_access_token),
510                operation_id,
511                operation_type,
512                Box::new(move |out_point_range| {
513                    serde_json::to_value(operation_meta_gen(out_point_range)).expect("Can't fail")
514                }),
515                tx_builder,
516            )
517            .await
518    }
519
520    /// Computes the fee that finalizing and submitting a transaction with the
521    /// explicit items described by `request` would incur, as a dry-run over the
522    /// client's current funds, without submitting anything. See
523    /// `Client::fee_quote`.
524    ///
525    /// Summarize the explicit inputs/outputs the operation would submit (their
526    /// gross amounts and federation fees) in `request`; the returned breakdown
527    /// adds the change the primary module's balancing would produce.
528    pub async fn fee_quote(
529        &self,
530        operation_id: OperationId,
531        request: FeeQuoteRequest,
532    ) -> Result<FeeQuote, TransactionSubmitError> {
533        self.client.get().fee_quote(operation_id, request).await
534    }
535
536    /// The account's Bitcoin balance, held by the primary module. See
537    /// `Client::get_balance_for_btc`.
538    pub async fn get_balance_for_btc(&self, account: Account) -> Result<Amount, ModuleLookupError> {
539        self.client
540            .get()
541            .get_balance_for_unit(AmountUnit::BITCOIN, account)
542            .await
543    }
544
545    /// Whether the primary module for `unit` can hold a balance for
546    /// `account`. A module handing out account-bound receive keys or addresses
547    /// checks this first, so that nothing is ever paid into an account the
548    /// primary module cannot fund a claim for.
549    pub fn supports_account(&self, unit: AmountUnit, account: Account) -> bool {
550        self.client.get().supports_account(unit, account)
551    }
552
553    pub async fn transaction_updates(&self, operation_id: OperationId) -> TransactionUpdates {
554        self.client.get().transaction_updates(operation_id).await
555    }
556
557    pub async fn await_primary_module_outputs(
558        &self,
559        operation_id: OperationId,
560        // TODO: make `impl Iterator<Item = ...>`
561        outputs: Vec<OutPoint>,
562    ) -> Result<(), TransactionSubmitError> {
563        self.client
564            .get()
565            .await_primary_module_outputs(operation_id, outputs)
566            .await
567    }
568
569    // TODO: unify with `Self::get_operation`
570    pub async fn get_operation(
571        &self,
572        operation_id: OperationId,
573    ) -> Result<oplog::OperationLogEntry, OperationLookupError> {
574        let operation = self
575            .client
576            .get()
577            .operation_log()
578            .get_operation(operation_id)
579            .await
580            .ok_or(OperationNotFoundError { operation_id })?;
581
582        if operation.operation_module_kind() != M::kind().as_str() {
583            return Err(OperationLookupError::WrongModuleKind {
584                operation_id,
585                expected: M::kind(),
586                found: operation.operation_module_kind().to_owned(),
587            });
588        }
589
590        Ok(operation)
591    }
592
593    /// Get global db.
594    ///
595    /// Only intended for internal use (private).
596    fn global_db(&self) -> fedimint_core::db::Database {
597        let db = Clone::clone(self.client.get().db());
598
599        db.ensure_global()
600            .expect("global_db must always return a global db");
601
602        db
603    }
604
605    pub fn module_db(&self) -> &Database {
606        self.module_db
607            .ensure_isolated()
608            .expect("module_db must always return isolated db");
609        &self.module_db
610    }
611
612    /// Read a portion of the client's event log, starting at `pos` (or the
613    /// beginning of the log if `None`) and returning up to `limit` entries.
614    pub async fn get_event_log(
615        &self,
616        pos: Option<EventLogId>,
617        limit: u64,
618    ) -> Vec<PersistedLogEntry> {
619        self.global_db()
620            .begin_transaction_nc()
621            .await
622            .get_event_log(pos, limit)
623            .await
624    }
625
626    pub async fn has_active_states(&self, op_id: OperationId) -> bool {
627        self.client.get().has_active_states(op_id).await
628    }
629
630    /// Waits until no state machine of the operation is running any more:
631    /// every transaction it submitted has been accepted or rejected, and
632    /// every input and output state machine those started, the primary
633    /// module's among them, has reached its final state.
634    ///
635    /// Unlike [`Self::await_primary_module_outputs`] this needs no outputs
636    /// named, and does not report whether they were issued. See
637    /// `Client::await_no_active_states`.
638    pub async fn await_no_active_states(&self, op_id: OperationId) {
639        self.client.get().await_no_active_states(op_id).await;
640    }
641
642    pub async fn operation_exists(&self, op_id: OperationId) -> bool {
643        self.client.get().operation_exists(op_id).await
644    }
645
646    pub async fn get_own_active_states(&self) -> Vec<(M::States, ActiveStateMeta)> {
647        self.client
648            .get()
649            .executor()
650            .get_active_states()
651            .await
652            .into_iter()
653            .filter(|s| s.0.module_instance_id() == self.module_instance_id)
654            .map(|s| {
655                (
656                    Clone::clone(
657                        s.0.as_any()
658                            .downcast_ref::<M::States>()
659                            .expect("incorrect output type passed to module plugin"),
660                    ),
661                    s.1,
662                )
663            })
664            .collect()
665    }
666
667    /// Returns this module's currently active state machines for the operation.
668    pub async fn get_own_operation_active_states(
669        &self,
670        operation_id: OperationId,
671    ) -> Vec<(M::States, ActiveStateMeta)> {
672        let db = self.global_db();
673        let mut dbtx = db.begin_transaction_nc().await;
674
675        self.client
676            .get()
677            .read_operation_active_states(operation_id, self.module_instance_id, &mut dbtx)
678            .await
679            .map(|(key, meta)| {
680                (
681                    Clone::clone(
682                        key.state
683                            .as_any()
684                            .downcast_ref::<M::States>()
685                            .expect("incorrect output type passed to module plugin"),
686                    ),
687                    meta,
688                )
689            })
690            .collect()
691            .await
692    }
693
694    /// Returns this module's previously active state machines for the
695    /// operation.
696    pub async fn get_own_operation_inactive_states(
697        &self,
698        operation_id: OperationId,
699    ) -> Vec<(M::States, InactiveStateMeta)> {
700        let db = self.global_db();
701        let mut dbtx = db.begin_transaction_nc().await;
702
703        self.client
704            .get()
705            .read_operation_inactive_states(operation_id, self.module_instance_id, &mut dbtx)
706            .await
707            .map(|(key, meta)| {
708                (
709                    Clone::clone(
710                        key.state
711                            .as_any()
712                            .downcast_ref::<M::States>()
713                            .expect("incorrect output type passed to module plugin"),
714                    ),
715                    meta,
716                )
717            })
718            .collect()
719            .await
720    }
721
722    pub async fn get_config(&self) -> ClientConfig {
723        self.client.get().config().await
724    }
725
726    /// Returns an invite code for the federation that points to an arbitrary
727    /// guardian server for fetching the config
728    pub async fn get_invite_code(&self) -> InviteCode {
729        let cfg = self.get_config().await.global;
730        self.client
731            .get()
732            .invite_code(
733                *cfg.api_endpoints
734                    .keys()
735                    .next()
736                    .expect("A federation always has at least one guardian"),
737            )
738            .await
739            .expect("The guardian we requested an invite code for exists")
740    }
741
742    pub fn get_internal_payment_markers(
743        &self,
744    ) -> Result<(PublicKey, u64), bitcoin::secp256k1::Error> {
745        self.client.get().get_internal_payment_markers()
746    }
747
748    /// This method starts n state machines with given operation id without a
749    /// corresponding transaction
750    pub async fn manual_operation_start(
751        &self,
752        operation_id: OperationId,
753        account: Account,
754        op_type: &str,
755        operation_meta: impl serde::Serialize + Debug,
756        sms: Vec<DynState>,
757    ) -> Result<(), TransactionSubmitError> {
758        let db = self.module_db();
759        let mut dbtx = db.begin_transaction().await;
760        {
761            let dbtx = &mut dbtx.global_dbtx(self.global_dbtx_access_token);
762
763            self.manual_operation_start_inner(
764                &mut dbtx.to_ref_nc(),
765                operation_id,
766                account,
767                op_type,
768                operation_meta,
769                sms,
770            )
771            .await?;
772        }
773
774        dbtx.commit_tx_result().await?;
775
776        Ok(())
777    }
778
779    pub async fn manual_operation_start_dbtx(
780        &self,
781        dbtx: &mut DatabaseTransaction<'_>,
782        operation_id: OperationId,
783        account: Account,
784        op_type: &str,
785        operation_meta: impl serde::Serialize + Debug,
786        sms: Vec<DynState>,
787    ) -> Result<(), OperationAlreadyExistsError> {
788        self.manual_operation_start_inner(
789            &mut dbtx.global_dbtx(self.global_dbtx_access_token),
790            operation_id,
791            account,
792            op_type,
793            operation_meta,
794            sms,
795        )
796        .await
797    }
798
799    /// See [`Self::manual_operation_start`], just inside a database
800    /// transaction.
801    async fn manual_operation_start_inner(
802        &self,
803        dbtx: &mut DatabaseTransaction<'_>,
804        operation_id: OperationId,
805        account: Account,
806        op_type: &str,
807        operation_meta: impl serde::Serialize + Debug,
808        sms: Vec<DynState>,
809    ) -> Result<(), OperationAlreadyExistsError> {
810        dbtx.ensure_global()
811            .expect("Must deal with global dbtx here");
812
813        if self
814            .client
815            .get()
816            .operation_log()
817            .get_operation_dbtx(&mut dbtx.to_ref_nc(), operation_id)
818            .await
819            .is_some()
820        {
821            return Err(OperationAlreadyExistsError { operation_id });
822        }
823
824        self.client
825            .get()
826            .operation_log()
827            .add_operation_log_entry_dbtx(
828                &mut dbtx.to_ref_nc(),
829                operation_id,
830                account,
831                op_type,
832                serde_json::to_value(operation_meta).expect("Can't fail"),
833            )
834            .await;
835
836        self.client
837            .get()
838            .executor()
839            .add_state_machines_dbtx(&mut dbtx.to_ref_nc(), sms)
840            .await
841            .expect("State machine is valid");
842
843        Ok(())
844    }
845
846    /// Resolve an operation to its cached outcome, or to a caching update
847    /// stream built by `stream_gen`.
848    ///
849    /// `is_terminal` reports whether an update is a final state of the
850    /// operation; only terminal updates are cached as the durable outcome (a
851    /// stream that ends early on a non-terminal update caches nothing). The
852    /// same predicate also validates outcomes READ from the cache: a cached
853    /// outcome that fails to deserialize into `U` (e.g. one written by an
854    /// incompatible earlier version) or that is non-terminal (one frozen by a
855    /// previous version that cached whatever update a stream ended on) is
856    /// discarded with a warning and the state is rebuilt from the update
857    /// stream — whose terminal end then overwrites the stale cache — instead
858    /// of short-circuiting subscribers to it or panicking.
859    pub fn outcome_or_updates<U, S>(
860        &self,
861        operation: &OperationLogEntry,
862        operation_id: OperationId,
863        is_terminal: impl Fn(&U) -> bool + MaybeSend + MaybeSync + 'static,
864        stream_gen: impl FnOnce() -> S + MaybeSend + 'static,
865    ) -> UpdateStreamOrOutcome<U>
866    where
867        U: Clone + Serialize + DeserializeOwned + Debug + MaybeSend + MaybeSync + 'static,
868        S: Stream<Item = U> + MaybeSend + 'static,
869    {
870        use futures::StreamExt;
871        match operation.try_outcome::<U>() {
872            Ok(Some(outcome)) if is_terminal(&outcome) => {
873                return UpdateStreamOrOutcome::Outcome(outcome);
874            }
875            Ok(Some(_non_terminal)) => {
876                warn!(
877                    target: LOG_CLIENT,
878                    "Cached operation outcome is not a terminal update (cached by a previous \
879                     version); rebuilding it from the update stream"
880                );
881            }
882            Ok(None) => {}
883            Err(err) => {
884                warn!(
885                    target: LOG_CLIENT,
886                    err = %err.fmt_compact(),
887                    "Cached operation outcome failed to deserialize; rebuilding it from the update stream"
888                );
889            }
890        }
891        let stream = self
892            .client
893            .get()
894            .operation_log()
895            .caching_operation_update_stream(
896                operation_id,
897                Box::new(move || {
898                    let stream_gen = stream_gen();
899                    Box::pin(
900                        stream_gen.map(move |item| serde_json::to_value(item).expect("Can't fail")),
901                    )
902                }),
903                Box::new(move |update| {
904                    // The update was serialized from a `U` moments ago in this
905                    // process, so deserialization only fails if `U` is not
906                    // round-trip-safe; treat that conservatively as non-terminal
907                    // (skip caching) rather than panicking inside the stream.
908                    serde_json::from_value::<U>(update.clone())
909                        .map(|update| is_terminal(&update))
910                        .unwrap_or(false)
911                }),
912            );
913        UpdateStreamOrOutcome::UpdateStream(Box::pin(
914            stream.map(|u| serde_json::from_value::<U>(u).expect("Can't fail")),
915        ))
916    }
917
918    /// The claim is credited to the operation's account, and any change the
919    /// primary module adds comes back to the same one.
920    pub async fn claim_inputs<I, S>(
921        &self,
922        dbtx: &mut DatabaseTransaction<'_>,
923        inputs: ClientInputBundle<I, S>,
924        operation_id: OperationId,
925    ) -> Result<OutPointRange, TransactionSubmitError>
926    where
927        I: IInput + MaybeSend + MaybeSync + 'static,
928        S: sm::IState + MaybeSend + MaybeSync + 'static,
929    {
930        self.claim_inputs_dyn(dbtx, inputs.into_instanceless(), operation_id)
931            .await
932    }
933
934    async fn claim_inputs_dyn(
935        &self,
936        dbtx: &mut DatabaseTransaction<'_>,
937        inputs: InstancelessDynClientInputBundle,
938        operation_id: OperationId,
939    ) -> Result<OutPointRange, TransactionSubmitError> {
940        let dbtx = &mut dbtx.global_dbtx(self.global_dbtx_access_token);
941
942        let account = self
943            .client
944            .get()
945            .operation_account_dbtx(&mut dbtx.to_ref_nc(), operation_id)
946            .await;
947        let tx_builder =
948            TransactionBuilder::new(account).with_inputs(inputs.into_dyn(self.module_instance_id));
949
950        self.client
951            .get()
952            .finalize_and_submit_transaction_inner(dbtx, operation_id, tx_builder)
953            .await
954    }
955
956    /// Records the account for an operation started without an operation log
957    /// entry, such as the state machines a recovery adds. See
958    /// `Client::set_operation_account_dbtx`.
959    pub async fn set_operation_account_dbtx(
960        &self,
961        dbtx: &mut DatabaseTransaction<'_>,
962        operation_id: OperationId,
963        account: Account,
964    ) {
965        self.client
966            .get()
967            .set_operation_account_dbtx(
968                &mut dbtx.global_dbtx(self.global_dbtx_access_token),
969                operation_id,
970                account,
971            )
972            .await;
973    }
974
975    pub async fn add_state_machines_dbtx(
976        &self,
977        dbtx: &mut DatabaseTransaction<'_>,
978        states: Vec<DynState>,
979    ) -> AddStateMachinesResult {
980        self.client
981            .get()
982            .executor()
983            .add_state_machines_dbtx(&mut dbtx.global_dbtx(self.global_dbtx_access_token), states)
984            .await
985    }
986
987    /// Reads an operation log entry within an ongoing database transaction.
988    ///
989    /// Unlike [`Self::get_operation`] this observes writes made earlier in
990    /// `dbtx`, which is what a caller needs to decide atomically whether it is
991    /// about to create an operation that already exists.
992    pub async fn get_operation_dbtx(
993        &self,
994        dbtx: &mut DatabaseTransaction<'_>,
995        operation_id: OperationId,
996    ) -> Option<oplog::OperationLogEntry> {
997        self.client
998            .get()
999            .operation_log()
1000            .get_operation_dbtx(
1001                &mut dbtx.global_dbtx(self.global_dbtx_access_token),
1002                operation_id,
1003            )
1004            .await
1005    }
1006
1007    pub async fn add_operation_log_entry_dbtx(
1008        &self,
1009        dbtx: &mut DatabaseTransaction<'_>,
1010        operation_id: OperationId,
1011        account: Account,
1012        operation_type: &str,
1013        operation_meta: impl serde::Serialize,
1014    ) {
1015        self.client
1016            .get()
1017            .operation_log()
1018            .add_operation_log_entry_dbtx(
1019                &mut dbtx.global_dbtx(self.global_dbtx_access_token),
1020                operation_id,
1021                account,
1022                operation_type,
1023                serde_json::to_value(operation_meta).expect("Can't fail"),
1024            )
1025            .await;
1026    }
1027
1028    /// Prepares an event for
1029    /// [`Self::finalize_and_submit_transaction_with_events`].
1030    pub fn make_event<E: Event>(&self, event: E) -> ClientModuleEvent {
1031        if <E as Event>::MODULE != Some(<M as ClientModule>::kind()) {
1032            warn!(
1033                target: LOG_CLIENT,
1034                module_kind = %<M as ClientModule>::kind(),
1035                event_module = ?<E as Event>::MODULE,
1036                "Client module logging events of different module than its own. This might become an error in the future."
1037            );
1038        }
1039        ClientModuleEvent {
1040            module_kind: E::MODULE,
1041            kind: E::KIND,
1042            payload: serde_json::to_value(event).expect("Can't fail"),
1043            persistence: E::PERSISTENCE,
1044        }
1045    }
1046
1047    pub async fn log_event<E, Cap>(&self, dbtx: &mut DatabaseTransaction<'_, Cap>, event: E)
1048    where
1049        E: Event + Send,
1050        Cap: Send,
1051    {
1052        self.log_serialized_event(dbtx, self.make_event(event))
1053            .await;
1054    }
1055
1056    async fn log_serialized_event<Cap: Send>(
1057        &self,
1058        dbtx: &mut DatabaseTransaction<'_, Cap>,
1059        event: ClientModuleEvent,
1060    ) {
1061        self.client
1062            .get()
1063            .log_event_json(
1064                &mut dbtx.global_dbtx(self.global_dbtx_access_token).to_ref_nc(),
1065                event.module_kind,
1066                self.module_instance_id,
1067                event.kind,
1068                event.payload,
1069                event.persistence,
1070            )
1071            .await;
1072    }
1073}
1074
1075/// Priority module priority (lower number is higher priority)
1076#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1077pub struct PrimaryModulePriority(u64);
1078
1079impl PrimaryModulePriority {
1080    pub const HIGH: Self = Self(100);
1081    pub const LOW: Self = Self(10000);
1082
1083    pub fn custom(prio: u64) -> Self {
1084        Self(prio)
1085    }
1086}
1087/// Which amount units this module supports being primary for
1088pub enum PrimaryModuleSupport {
1089    /// Potentially any unit
1090    Any {
1091        priority: PrimaryModulePriority,
1092        accounts: AccountSupport,
1093    },
1094    /// Some units supported by the module
1095    Selected {
1096        priority: PrimaryModulePriority,
1097        units: BTreeSet<AmountUnit>,
1098        accounts: AccountSupport,
1099    },
1100    /// None
1101    None,
1102}
1103
1104impl PrimaryModuleSupport {
1105    pub fn selected<const N: usize>(
1106        priority: PrimaryModulePriority,
1107        units: [AmountUnit; N],
1108        accounts: AccountSupport,
1109    ) -> Self {
1110        Self::Selected {
1111            priority,
1112            units: BTreeSet::from(units),
1113            accounts,
1114        }
1115    }
1116}
1117
1118/// Which of the client's accounts a primary module can hold a balance for.
1119///
1120/// Advertised rather than discovered: a module that gives out account-bound
1121/// receive keys or addresses has to know before anyone pays into them whether
1122/// the primary module will be able to fund the claim, since by the time
1123/// balancing fails the payer's money has already moved.
1124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1125pub enum AccountSupport {
1126    /// The module keeps a single balance and refuses to fund any other
1127    /// account.
1128    PrimaryOnly,
1129    /// Every [`Account`] has its own balance in the module.
1130    All,
1131}
1132
1133impl AccountSupport {
1134    pub fn supports(self, account: Account) -> bool {
1135        match self {
1136            Self::PrimaryOnly => account == Account::Primary,
1137            Self::All => true,
1138        }
1139    }
1140}
1141
1142/// Fedimint module client
1143#[apply(async_trait_maybe_send!)]
1144pub trait ClientModule: Debug + MaybeSend + MaybeSync + 'static {
1145    type Init: ClientModuleInit;
1146
1147    /// Common module types shared between client and server
1148    type Common: ModuleCommon;
1149
1150    /// Data stored in regular backups so that restoring doesn't have to start
1151    /// from epoch 0
1152    type Backup: ModuleBackup;
1153
1154    /// Data and API clients available to state machine transitions of this
1155    /// module
1156    type ModuleStateMachineContext: Context;
1157
1158    /// All possible states this client can submit to the executor
1159    type States: State<ModuleContext = Self::ModuleStateMachineContext>
1160        + IntoDynInstance<DynType = DynState>;
1161
1162    fn decoder() -> Decoder {
1163        let mut decoder_builder = Self::Common::decoder_builder();
1164        decoder_builder.with_decodable_type::<Self::States>();
1165        decoder_builder.with_decodable_type::<Self::Backup>();
1166        decoder_builder.build()
1167    }
1168
1169    fn kind() -> ModuleKind {
1170        <<<Self as ClientModule>::Init as ModuleInit>::Common as CommonModuleInit>::KIND
1171    }
1172
1173    fn context(&self) -> Self::ModuleStateMachineContext;
1174
1175    /// Initialize client.
1176    ///
1177    /// Called by the core client code on start, after [`ClientContext`] is
1178    /// fully initialized, so unlike during [`ClientModuleInit::init`],
1179    /// access to global client is allowed.
1180    async fn start(&self) {}
1181
1182    /// Runs a `fedimint-cli module` command, given as its arguments.
1183    ///
1184    /// # Errors
1185    ///
1186    /// The default body fails with [`ClientModuleError::Unsupported`], for a
1187    /// module that has no commands.
1188    async fn handle_cli_command(
1189        &self,
1190        _args: &[ffi::OsString],
1191    ) -> Result<serde_json::Value, ClientModuleError> {
1192        Err(ClientModuleError::Unsupported {
1193            kind: <Self as ClientModule>::kind(),
1194            operation: "handle_cli_command",
1195        })
1196    }
1197
1198    /// Serves a JSON request, such as one `fedimint-client-rpc` forwards.
1199    ///
1200    /// # Errors
1201    ///
1202    /// The stream yields the module's failures. The default body yields a
1203    /// single [`ClientModuleError::Unsupported`], for a module that serves no
1204    /// requests.
1205    async fn handle_rpc(
1206        &self,
1207        _method: String,
1208        _request: serde_json::Value,
1209    ) -> BoxStream<'_, Result<serde_json::Value, ClientModuleError>> {
1210        Box::pin(futures::stream::once(std::future::ready(Err(
1211            ClientModuleError::Unsupported {
1212                kind: <Self as ClientModule>::kind(),
1213                operation: "handle_rpc",
1214            },
1215        ))))
1216    }
1217
1218    /// Returns the fee the processing of this input requires.
1219    ///
1220    /// If the semantics of a given input aren't known this function returns
1221    /// `None`, this only happens if a future version of Fedimint introduces a
1222    /// new input variant. For clients this should only be the case when
1223    /// processing transactions created by other users, so the result of
1224    /// this function can be `unwrap`ped whenever dealing with inputs
1225    /// generated by ourselves.
1226    fn input_fee(
1227        &self,
1228        amount: &Amounts,
1229        input: &<Self::Common as ModuleCommon>::Input,
1230    ) -> Option<Amounts>;
1231
1232    /// Returns the fee the processing of this output requires.
1233    ///
1234    /// If the semantics of a given output aren't known this function returns
1235    /// `None`, this only happens if a future version of Fedimint introduces a
1236    /// new output variant. For clients this should only be the case when
1237    /// processing transactions created by other users, so the result of
1238    /// this function can be `unwrap`ped whenever dealing with inputs
1239    /// generated by ourselves.
1240    fn output_fee(
1241        &self,
1242        amount: &Amounts,
1243        output: &<Self::Common as ModuleCommon>::Output,
1244    ) -> Option<Amounts>;
1245
1246    fn supports_backup(&self) -> bool {
1247        false
1248    }
1249
1250    /// The module's part of a client backup.
1251    ///
1252    /// # Errors
1253    ///
1254    /// The default body fails with [`ClientModuleError::Unsupported`]; a
1255    /// module whose [`Self::supports_backup`] is `true` must override it.
1256    async fn backup(&self) -> Result<Self::Backup, ClientModuleError> {
1257        Err(ClientModuleError::Unsupported {
1258            kind: <Self as ClientModule>::kind(),
1259            operation: "backup",
1260        })
1261    }
1262
1263    /// Does this module support being a primary module
1264    ///
1265    /// If it does it must implement:
1266    ///
1267    /// * [`Self::create_final_inputs_and_outputs`]
1268    /// * [`Self::await_primary_module_output`]
1269    /// * [`Self::get_balance`]
1270    /// * [`Self::subscribe_balance_changes`]
1271    fn supports_being_primary(&self) -> PrimaryModuleSupport {
1272        PrimaryModuleSupport::None
1273    }
1274
1275    /// Creates all inputs and outputs necessary to balance the transaction.
1276    ///
1277    /// A returned input also contains:
1278    /// * A set of private keys belonging to the input for signing the
1279    ///   transaction
1280    /// * A closure that generates states belonging to the input. This closure
1281    ///   takes the transaction id of the transaction in which the input was
1282    ///   used and the input index as input since these cannot be known at time
1283    ///   of calling `create_funding_input` and have to be injected later.
1284    ///
1285    /// A returned output also contains:
1286    /// * A closure that generates states belonging to the output. This closure
1287    ///   takes the transaction id of the transaction in which the output was
1288    ///   used and the output index as input since these cannot be known at time
1289    ///   of calling `create_change_output` and have to be injected later.
1290    ///
1291    /// # Errors
1292    ///
1293    /// A module whose funds cannot cover the transaction must fail with
1294    /// [`ClientModuleError::InsufficientBalance`]: the client reports that as
1295    /// [`TransactionSubmitError::InsufficientFunds`], and any other failure as
1296    /// [`TransactionSubmitError::PrimaryModule`]. The default body fails with
1297    /// [`ClientModuleError::Unsupported`].
1298    async fn create_final_inputs_and_outputs(
1299        &self,
1300        _dbtx: &mut DatabaseTransaction<'_>,
1301        _operation_id: OperationId,
1302        _unit: AmountUnit,
1303        _input_amount: Amount,
1304        _output_amount: Amount,
1305        _account: Account,
1306    ) -> Result<
1307        (
1308            ClientInputBundle<<Self::Common as ModuleCommon>::Input, Self::States>,
1309            ClientOutputBundle<<Self::Common as ModuleCommon>::Output, Self::States>,
1310        ),
1311        ClientModuleError,
1312    > {
1313        Err(ClientModuleError::Unsupported {
1314            kind: <Self as ClientModule>::kind(),
1315            operation: "create_final_inputs_and_outputs",
1316        })
1317    }
1318
1319    /// Quote the inputs and change needed to balance these amounts.
1320    /// Implementations may avoid creating cryptographic outputs, but must use
1321    /// the same funding selection and change denominations as finalization.
1322    async fn quote_final_inputs_and_outputs(
1323        &self,
1324        dbtx: &mut DatabaseTransaction<'_>,
1325        operation_id: OperationId,
1326        unit: AmountUnit,
1327        input_amount: Amount,
1328        output_amount: Amount,
1329        account: Account,
1330    ) -> Result<FeeQuoteRequest, ClientModuleError> {
1331        let (inputs, outputs) = self
1332            .create_final_inputs_and_outputs(
1333                dbtx,
1334                operation_id,
1335                unit,
1336                input_amount,
1337                output_amount,
1338                account,
1339            )
1340            .await?;
1341        let mut quote = FeeQuoteRequest {
1342            input_amount: Amounts::ZERO,
1343            output_amount: Amounts::ZERO,
1344            input_fee: Amounts::ZERO,
1345            output_fee: Amounts::ZERO,
1346            account,
1347        };
1348        for input in inputs.inputs() {
1349            quote.input_amount.checked_add_mut(&input.amounts);
1350            quote.input_fee.checked_add_mut(
1351                &self
1352                    .input_fee(&input.amounts, &input.input)
1353                    .expect("Primary module must know its own change input fees"),
1354            );
1355        }
1356        for output in outputs.outputs() {
1357            quote.output_amount.checked_add_mut(&output.amounts);
1358            quote.output_fee.checked_add_mut(
1359                &self
1360                    .output_fee(&output.amounts, &output.output)
1361                    .expect("Primary module must know its own change output fees"),
1362            );
1363        }
1364        Ok(quote)
1365    }
1366
1367    /// Waits for the funds from an output created by
1368    /// [`Self::create_final_inputs_and_outputs`] to become available. This
1369    /// function returning typically implies a change in the output of
1370    /// [`Self::get_balance`].
1371    ///
1372    /// # Errors
1373    ///
1374    /// Fails if the output does not become available, for example because
1375    /// the federation rejected its transaction. The default body fails with
1376    /// [`ClientModuleError::Unsupported`].
1377    async fn await_primary_module_output(
1378        &self,
1379        _operation_id: OperationId,
1380        _out_point: OutPoint,
1381    ) -> Result<(), ClientModuleError> {
1382        Err(ClientModuleError::Unsupported {
1383            kind: <Self as ClientModule>::kind(),
1384            operation: "await_primary_module_output",
1385        })
1386    }
1387
1388    /// Returns the balance held by this module and available for funding
1389    /// transactions.
1390    async fn get_balance(
1391        &self,
1392        _dbtx: &mut DatabaseTransaction<'_>,
1393        _unit: AmountUnit,
1394        _account: Account,
1395    ) -> Amount {
1396        unimplemented!()
1397    }
1398
1399    /// Returns the balance held by this module and available for funding
1400    /// transactions.
1401    async fn get_balances(&self, _dbtx: &mut DatabaseTransaction<'_>) -> Amounts {
1402        unimplemented!()
1403    }
1404
1405    /// Returns a stream that will output the updated module balance each time
1406    /// it changes.
1407    async fn subscribe_balance_changes(&self) -> BoxStream<'static, ()> {
1408        unimplemented!()
1409    }
1410
1411    /// Leave the federation
1412    ///
1413    /// While technically there's nothing stopping the client from just
1414    /// abandoning Federation at any point by deleting all the related
1415    /// local data, it is useful to make sure it's safe beforehand.
1416    ///
1417    /// This call indicates the desire of the caller client code
1418    /// to orderly and safely leave the Federation by this module instance.
1419    /// The goal of the implementations is to fulfil that wish,
1420    /// giving prompt and informative feedback if it's not yet possible.
1421    ///
1422    /// The client module implementation should handle the request
1423    /// and return as fast as possible avoiding blocking for longer than
1424    /// necessary. This would usually involve some combination of:
1425    ///
1426    /// * recording the state of being in process of leaving the Federation to
1427    ///   prevent initiating new conditions that could delay its completion;
1428    /// * performing any fast to complete cleanup/exit logic;
1429    /// * initiating any time-consuming logic (e.g. canceling outstanding
1430    ///   contracts), as background jobs, tasks machines, etc.
1431    /// * checking for any conditions indicating it might not be safe to leave
1432    ///   at the moment.
1433    ///
1434    /// This function should return `Ok` only if from the perspective
1435    /// of this module instance, it is safe to delete client data and
1436    /// stop using it, with no further actions (like background jobs) required
1437    /// to complete.
1438    ///
1439    /// This function should return an error if it's not currently possible
1440    /// to safely (e.g. without losing funds) leave the Federation.
1441    /// It should avoid running indefinitely trying to complete any cleanup
1442    /// actions necessary to reach a clean state, preferring spawning new
1443    /// state machines and returning an informative error about cleanup
1444    /// still in progress.
1445    ///
1446    /// If any internal task needs to complete, any user action is required,
1447    /// or even external condition needs to be met this function
1448    /// should return a `Err`.
1449    ///
1450    /// Notably modules should not disable interaction that might be necessary
1451    /// for the user (possibly through other modules) to leave the Federation.
1452    /// In particular a Mint module should retain ability to create new notes,
1453    /// and LN module should retain ability to send funds out.
1454    ///
1455    /// Calling code must NOT assume that a module that once returned `Ok`,
1456    /// will not return `Err` at later point. E.g. a Mint module might have
1457    /// no outstanding balance at first, but other modules winding down
1458    /// might "cash-out" to Ecash.
1459    ///
1460    /// Before leaving the Federation and deleting any state the calling code
1461    /// must collect a full round of `Ok` from all the modules.
1462    ///
1463    /// Calling code should allow the user to override and ignore any
1464    /// outstanding errors, after sufficient amount of warnings. Ideally,
1465    /// this should be done on per-module basis, to avoid mistakes.
1466    ///
1467    /// # Errors
1468    ///
1469    /// The default body fails with [`ClientModuleError::Unsupported`], since a
1470    /// module that does not implement this cannot tell whether leaving is
1471    /// safe.
1472    async fn leave(&self, _dbtx: &mut DatabaseTransaction<'_>) -> Result<(), ClientModuleError> {
1473        Err(ClientModuleError::Unsupported {
1474            kind: <Self as ClientModule>::kind(),
1475            operation: "leave",
1476        })
1477    }
1478}
1479
1480/// Type-erased version of [`ClientModule`]
1481#[apply(async_trait_maybe_send!)]
1482pub trait IClientModule: Debug {
1483    fn as_any(&self) -> &(maybe_add_send_sync!(dyn std::any::Any));
1484
1485    fn decoder(&self) -> Decoder;
1486
1487    fn context(&self, instance: ModuleInstanceId) -> DynContext;
1488
1489    async fn start(&self);
1490
1491    async fn handle_cli_command(
1492        &self,
1493        args: &[ffi::OsString],
1494    ) -> Result<serde_json::Value, ClientModuleError>;
1495
1496    async fn handle_rpc(
1497        &self,
1498        method: String,
1499        request: serde_json::Value,
1500    ) -> BoxStream<'_, Result<serde_json::Value, ClientModuleError>>;
1501
1502    fn input_fee(&self, amount: &Amounts, input: &DynInput) -> Option<Amounts>;
1503
1504    fn output_fee(&self, amount: &Amounts, output: &DynOutput) -> Option<Amounts>;
1505
1506    fn supports_backup(&self) -> bool;
1507
1508    async fn backup(
1509        &self,
1510        module_instance_id: ModuleInstanceId,
1511    ) -> Result<DynModuleBackup, ClientModuleError>;
1512
1513    fn supports_being_primary(&self) -> PrimaryModuleSupport;
1514
1515    #[allow(clippy::too_many_arguments)]
1516    async fn create_final_inputs_and_outputs(
1517        &self,
1518        module_instance: ModuleInstanceId,
1519        dbtx: &mut DatabaseTransaction<'_>,
1520        operation_id: OperationId,
1521        unit: AmountUnit,
1522        input_amount: Amount,
1523        output_amount: Amount,
1524        account: Account,
1525    ) -> Result<(ClientInputBundle, ClientOutputBundle), ClientModuleError>;
1526
1527    #[allow(clippy::too_many_arguments)]
1528    async fn quote_final_inputs_and_outputs(
1529        &self,
1530        module_instance: ModuleInstanceId,
1531        dbtx: &mut DatabaseTransaction<'_>,
1532        operation_id: OperationId,
1533        unit: AmountUnit,
1534        input_amount: Amount,
1535        output_amount: Amount,
1536        account: Account,
1537    ) -> Result<FeeQuoteRequest, ClientModuleError>;
1538
1539    async fn await_primary_module_output(
1540        &self,
1541        operation_id: OperationId,
1542        out_point: OutPoint,
1543    ) -> Result<(), ClientModuleError>;
1544
1545    async fn get_balance(
1546        &self,
1547        module_instance: ModuleInstanceId,
1548        dbtx: &mut DatabaseTransaction<'_>,
1549        unit: AmountUnit,
1550        account: Account,
1551    ) -> Amount;
1552
1553    async fn subscribe_balance_changes(&self) -> BoxStream<'static, ()>;
1554}
1555
1556#[apply(async_trait_maybe_send!)]
1557impl<T> IClientModule for T
1558where
1559    T: ClientModule,
1560{
1561    fn as_any(&self) -> &(maybe_add_send_sync!(dyn Any)) {
1562        self
1563    }
1564
1565    fn decoder(&self) -> Decoder {
1566        T::decoder()
1567    }
1568
1569    fn context(&self, instance: ModuleInstanceId) -> DynContext {
1570        DynContext::from_typed(instance, <T as ClientModule>::context(self))
1571    }
1572
1573    async fn start(&self) {
1574        <T as ClientModule>::start(self).await;
1575    }
1576
1577    async fn handle_cli_command(
1578        &self,
1579        args: &[ffi::OsString],
1580    ) -> Result<serde_json::Value, ClientModuleError> {
1581        <T as ClientModule>::handle_cli_command(self, args).await
1582    }
1583
1584    async fn handle_rpc(
1585        &self,
1586        method: String,
1587        request: serde_json::Value,
1588    ) -> BoxStream<'_, Result<serde_json::Value, ClientModuleError>> {
1589        <T as ClientModule>::handle_rpc(self, method, request).await
1590    }
1591
1592    fn input_fee(&self, amount: &Amounts, input: &DynInput) -> Option<Amounts> {
1593        <T as ClientModule>::input_fee(
1594            self,
1595            amount,
1596            input
1597                .as_any()
1598                .downcast_ref()
1599                .expect("Dispatched to correct module"),
1600        )
1601    }
1602
1603    fn output_fee(&self, amount: &Amounts, output: &DynOutput) -> Option<Amounts> {
1604        <T as ClientModule>::output_fee(
1605            self,
1606            amount,
1607            output
1608                .as_any()
1609                .downcast_ref()
1610                .expect("Dispatched to correct module"),
1611        )
1612    }
1613
1614    fn supports_backup(&self) -> bool {
1615        <T as ClientModule>::supports_backup(self)
1616    }
1617
1618    async fn backup(
1619        &self,
1620        module_instance_id: ModuleInstanceId,
1621    ) -> Result<DynModuleBackup, ClientModuleError> {
1622        Ok(DynModuleBackup::from_typed(
1623            module_instance_id,
1624            <T as ClientModule>::backup(self).await?,
1625        ))
1626    }
1627
1628    fn supports_being_primary(&self) -> PrimaryModuleSupport {
1629        <T as ClientModule>::supports_being_primary(self)
1630    }
1631
1632    async fn create_final_inputs_and_outputs(
1633        &self,
1634        module_instance: ModuleInstanceId,
1635        dbtx: &mut DatabaseTransaction<'_>,
1636        operation_id: OperationId,
1637        unit: AmountUnit,
1638        input_amount: Amount,
1639        output_amount: Amount,
1640        account: Account,
1641    ) -> Result<(ClientInputBundle, ClientOutputBundle), ClientModuleError> {
1642        let (inputs, outputs) = <T as ClientModule>::create_final_inputs_and_outputs(
1643            self,
1644            &mut dbtx.to_ref_with_prefix_module_id(module_instance).0,
1645            operation_id,
1646            unit,
1647            input_amount,
1648            output_amount,
1649            account,
1650        )
1651        .await?;
1652
1653        let inputs = inputs.into_dyn(module_instance);
1654
1655        let outputs = outputs.into_dyn(module_instance);
1656
1657        Ok((inputs, outputs))
1658    }
1659
1660    async fn quote_final_inputs_and_outputs(
1661        &self,
1662        module_instance: ModuleInstanceId,
1663        dbtx: &mut DatabaseTransaction<'_>,
1664        operation_id: OperationId,
1665        unit: AmountUnit,
1666        input_amount: Amount,
1667        output_amount: Amount,
1668        account: Account,
1669    ) -> Result<FeeQuoteRequest, ClientModuleError> {
1670        <T as ClientModule>::quote_final_inputs_and_outputs(
1671            self,
1672            &mut dbtx.to_ref_with_prefix_module_id(module_instance).0,
1673            operation_id,
1674            unit,
1675            input_amount,
1676            output_amount,
1677            account,
1678        )
1679        .await
1680    }
1681
1682    async fn await_primary_module_output(
1683        &self,
1684        operation_id: OperationId,
1685        out_point: OutPoint,
1686    ) -> Result<(), ClientModuleError> {
1687        <T as ClientModule>::await_primary_module_output(self, operation_id, out_point).await
1688    }
1689
1690    async fn get_balance(
1691        &self,
1692        module_instance: ModuleInstanceId,
1693        dbtx: &mut DatabaseTransaction<'_>,
1694        unit: AmountUnit,
1695        account: Account,
1696    ) -> Amount {
1697        <T as ClientModule>::get_balance(
1698            self,
1699            &mut dbtx.to_ref_with_prefix_module_id(module_instance).0,
1700            unit,
1701            account,
1702        )
1703        .await
1704    }
1705
1706    async fn subscribe_balance_changes(&self) -> BoxStream<'static, ()> {
1707        <T as ClientModule>::subscribe_balance_changes(self).await
1708    }
1709}
1710
1711dyn_newtype_define!(
1712    #[derive(Clone)]
1713    pub DynClientModule(Arc<IClientModule>)
1714);
1715
1716impl AsRef<maybe_add_send_sync!(dyn IClientModule + 'static)> for DynClientModule {
1717    fn as_ref(&self) -> &maybe_add_send_sync!(dyn IClientModule + 'static) {
1718        self.inner.as_ref()
1719    }
1720}
1721
1722// Re-export types from fedimint_core
1723pub use fedimint_core::{IdxRange, OutPointRange, OutPointRangeIter};
1724
1725pub type StateGenerator<S> = Arc<maybe_add_send_sync!(dyn Fn(OutPointRange) -> Vec<S> + 'static)>;