Skip to main content

fedimint_client_module/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::cast_possible_truncation)]
3#![allow(clippy::doc_markdown)]
4#![allow(clippy::explicit_deref_methods)]
5#![allow(clippy::missing_errors_doc)]
6#![allow(clippy::missing_panics_doc)]
7#![allow(clippy::module_name_repetitions)]
8#![allow(clippy::must_use_candidate)]
9#![allow(clippy::needless_lifetimes)]
10#![allow(clippy::return_self_not_must_use)]
11#![allow(clippy::too_many_lines)]
12#![allow(clippy::type_complexity)]
13
14use std::fmt::Debug;
15use std::ops::{self};
16use std::sync::Arc;
17
18use fedimint_api_client::api::{DynGlobalApi, DynModuleApi};
19use fedimint_core::config::ClientConfig;
20pub use fedimint_core::core::{
21    Account, IInput, IOutput, ModuleInstanceId, ModuleKind, OperationId,
22};
23use fedimint_core::db::Database;
24use fedimint_core::module::registry::ModuleDecoderRegistry;
25use fedimint_core::module::{ApiAuth, ApiVersion};
26use fedimint_core::task::{MaybeSend, MaybeSync};
27use fedimint_core::util::{BoxStream, NextOrPending};
28use fedimint_core::{
29    Amount, PeerId, TransactionId, apply, async_trait_maybe_send, dyn_newtype_define,
30    maybe_add_send_sync,
31};
32use fedimint_eventlog::{Event, EventKind, EventPersistence};
33use fedimint_logging::LOG_CLIENT;
34use futures::StreamExt;
35use module::OutPointRange;
36use serde::{Deserialize, Serialize};
37use tracing::debug;
38use transaction::{
39    ClientInputBundle, ClientInputSM, ClientOutput, ClientOutputSM, TxSubmissionStatesSM,
40};
41
42pub use crate::error::{
43    AddStateMachinesError, ApiVersionDiscoveryError, ClientModuleError, MetaFetchError,
44    ModuleLookupError, OperationAlreadyExistsError, OperationLookupError, OperationNotFoundError,
45    TransactionSubmitError,
46};
47pub use crate::module::{ClientModule, StateGenerator};
48use crate::sm::executor::ContextGen;
49use crate::sm::{ClientSMDatabaseTransaction, DynState, IState, State};
50use crate::transaction::{ClientInput, ClientOutputBundle, TxSubmissionStates};
51
52pub mod api;
53
54pub mod db;
55
56/// Error types shared between the client and its modules
57pub mod error;
58
59pub mod backup;
60/// Environment variables
61pub mod envs;
62pub mod meta;
63/// Module client interface definitions
64pub mod module;
65/// Operation log subsystem of the client
66pub mod oplog;
67/// Secret handling & derivation
68pub mod secret;
69/// Client state machine interfaces and executor implementation
70pub mod sm;
71/// Structs and interfaces to construct Fedimint transactions
72pub mod transaction;
73
74pub mod api_version_discovery;
75
76#[derive(Serialize, Deserialize)]
77pub struct TxCreatedEvent {
78    pub txid: TransactionId,
79    pub operation_id: OperationId,
80    /// Balance the primary module funded the transaction from and credits its
81    /// change to. Tagged here because not every transaction belongs to an
82    /// operation that emits an account-tagged module event: an internal
83    /// reissue runs under its own operation id and emits none. The later
84    /// tx-accepted and tx-rejected events share this event's txid, so they
85    /// need no tag of their own. Defaulted so entries written before accounts
86    /// existed still decode.
87    #[serde(default = "Account::primary")]
88    pub account: Account,
89}
90
91impl Event for TxCreatedEvent {
92    const MODULE: Option<ModuleKind> = None;
93    const KIND: EventKind = EventKind::from_static("tx-created");
94    const PERSISTENCE: EventPersistence = EventPersistence::Persistent;
95}
96
97#[derive(Serialize, Deserialize)]
98pub struct TxAcceptedEvent {
99    txid: TransactionId,
100    operation_id: OperationId,
101}
102
103impl Event for TxAcceptedEvent {
104    const MODULE: Option<ModuleKind> = None;
105    const KIND: EventKind = EventKind::from_static("tx-accepted");
106    const PERSISTENCE: EventPersistence = EventPersistence::Persistent;
107}
108
109#[derive(Serialize, Deserialize)]
110pub struct TxRejectedEvent {
111    txid: TransactionId,
112    error: String,
113    operation_id: OperationId,
114}
115impl Event for TxRejectedEvent {
116    const MODULE: Option<ModuleKind> = None;
117    const KIND: EventKind = EventKind::from_static("tx-rejected");
118    const PERSISTENCE: EventPersistence = EventPersistence::Persistent;
119}
120
121/// Diagnostic signal that a transaction submission is being re-attempted
122/// indefinitely without reaching consensus.
123///
124/// Emitted only on the retry iterations where `submit_transaction` returns a
125/// decodable, non-rejection outcome — i.e. a peer accepted the submission but
126/// the transaction has still not been accepted into (or rejected from)
127/// consensus. Repeated transport, API, or decoding errors instead take the
128/// retry error path and do not emit this event, so its absence does not imply
129/// the submission has stopped.
130///
131/// Cadence: first emitted after roughly 30 minutes of continuous re-submission
132/// within a single client run, then repeated about every 30 minutes while the
133/// condition persists. Elapsed time is measured per client run, so a restart
134/// resets it.
135///
136/// It is [`EventPersistence::Transient`], so it is broadcast to live
137/// subscribers (and transits the unordered event staging table) but is never
138/// written to the ordered event log.
139#[derive(Serialize, Deserialize)]
140pub struct TxSubmissionStalledEvent {
141    pub txid: TransactionId,
142    pub operation_id: OperationId,
143    /// Submission attempts so far in this client run.
144    pub attempt: u64,
145    /// Seconds elapsed in this client run since submission started.
146    pub elapsed_s: u64,
147}
148
149impl Event for TxSubmissionStalledEvent {
150    const MODULE: Option<ModuleKind> = None;
151    const KIND: EventKind = EventKind::from_static("tx-submission-stalled");
152    const PERSISTENCE: EventPersistence = EventPersistence::Transient;
153}
154
155#[derive(Serialize, Deserialize)]
156pub struct ModuleRecoveryStarted {
157    module_id: ModuleInstanceId,
158}
159
160impl ModuleRecoveryStarted {
161    pub fn new(module_id: ModuleInstanceId) -> Self {
162        Self { module_id }
163    }
164}
165
166impl Event for ModuleRecoveryStarted {
167    const MODULE: Option<ModuleKind> = None;
168    const KIND: EventKind = EventKind::from_static("module-recovery-started");
169    const PERSISTENCE: EventPersistence = EventPersistence::Persistent;
170}
171
172#[derive(Serialize, Deserialize)]
173pub struct ModuleRecoveryCompleted {
174    pub module_id: ModuleInstanceId,
175    /// The kind of the module that finished recovering.
176    ///
177    /// This lets consumers match on the module without cross-referencing
178    /// `module_id` against the federation config. `#[serde(default)]` keeps it
179    /// backwards-compatible with events persisted before it was added, which
180    /// deserialize as `None`.
181    #[serde(default)]
182    pub kind: Option<ModuleKind>,
183    /// The total amount recovered from this module, if the module tracks it.
184    ///
185    /// Modules like the mint know the exact value of the ecash notes they
186    /// reconstruct, while others (e.g. the wallet) only discover which
187    /// on-chain outputs belonged to the client and can't determine the
188    /// amount at recovery-completion time, in which case this is `None`.
189    ///
190    /// `#[serde(default)]` keeps this field backwards-compatible with events
191    /// persisted before it was added, which deserialize as `None`.
192    #[serde(default)]
193    pub amount: Option<Amount>,
194}
195
196impl Event for ModuleRecoveryCompleted {
197    const MODULE: Option<ModuleKind> = None;
198    const KIND: EventKind = EventKind::from_static("module-recovery-completed");
199    const PERSISTENCE: EventPersistence = EventPersistence::Persistent;
200}
201
202pub type InstancelessDynClientInput = ClientInput<Box<maybe_add_send_sync!(dyn IInput + 'static)>>;
203
204pub type InstancelessDynClientInputSM =
205    ClientInputSM<Box<maybe_add_send_sync!(dyn IState + 'static)>>;
206
207pub type InstancelessDynClientInputBundle = ClientInputBundle<
208    Box<maybe_add_send_sync!(dyn IInput + 'static)>,
209    Box<maybe_add_send_sync!(dyn IState + 'static)>,
210>;
211
212pub type InstancelessDynClientOutput =
213    ClientOutput<Box<maybe_add_send_sync!(dyn IOutput + 'static)>>;
214
215pub type InstancelessDynClientOutputSM =
216    ClientOutputSM<Box<maybe_add_send_sync!(dyn IState + 'static)>>;
217pub type InstancelessDynClientOutputBundle = ClientOutputBundle<
218    Box<maybe_add_send_sync!(dyn IOutput + 'static)>,
219    Box<maybe_add_send_sync!(dyn IState + 'static)>,
220>;
221
222pub type AddStateMachinesResult = Result<(), AddStateMachinesError>;
223
224#[apply(async_trait_maybe_send!)]
225pub trait IGlobalClientContext: Debug + MaybeSend + MaybeSync + 'static {
226    /// Returned a reference client's module API client, so that module-specific
227    /// calls can be made
228    fn module_api(&self) -> DynModuleApi;
229
230    async fn client_config(&self) -> ClientConfig;
231
232    /// Returns a reference to the client's federation API client. The provided
233    /// interface [`fedimint_api_client::api::IGlobalFederationApi`] typically
234    /// does not provide the necessary functionality, for this extension
235    /// traits like [`fedimint_api_client::api::IGlobalFederationApi`] have
236    /// to be used.
237    // TODO: Could be removed in favor of client() except for testing
238    fn api(&self) -> &DynGlobalApi;
239
240    fn decoders(&self) -> &ModuleDecoderRegistry;
241
242    /// The account the state machine's operation acts on: the balance the
243    /// primary module funds its transactions from and credits its change,
244    /// claims and refunds to. Read from the operation's record rather than
245    /// carried by the state machine, so no machine's persisted shape depends
246    /// on it.
247    async fn account(&self, dbtx: &mut ClientSMDatabaseTransaction<'_, '_>) -> Account;
248
249    /// This function is mostly meant for internal use, you are probably looking
250    /// for [`DynGlobalClientContext::claim_inputs`].
251    /// Returns transaction id of the funding transaction and an optional
252    /// `OutPoint` that represents change if change was added.
253    async fn claim_inputs_dyn(
254        &self,
255        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
256        inputs: InstancelessDynClientInputBundle,
257    ) -> Result<OutPointRange, TransactionSubmitError>;
258
259    /// This function is mostly meant for internal use, you are probably looking
260    /// for [`DynGlobalClientContext::fund_output`].
261    /// Returns transaction id of the funding transaction and an optional
262    /// `OutPoint` that represents change if change was added.
263    async fn fund_output_dyn(
264        &self,
265        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
266        outputs: InstancelessDynClientOutputBundle,
267    ) -> Result<OutPointRange, TransactionSubmitError>;
268
269    /// Adds a state machine to the executor.
270    async fn add_state_machine_dyn(
271        &self,
272        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
273        sm: Box<maybe_add_send_sync!(dyn IState)>,
274    ) -> AddStateMachinesResult;
275
276    async fn log_event_json(
277        &self,
278        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
279        kind: EventKind,
280        module: Option<(ModuleKind, ModuleInstanceId)>,
281        payload: serde_json::Value,
282        persist: EventPersistence,
283    );
284
285    /// Like [`Self::log_event_json`], but opens its own database transaction
286    /// instead of borrowing a [`ClientSMDatabaseTransaction`]. Meant for call
287    /// sites that run outside a state transition (e.g. the submission retry
288    /// loop) and therefore have no dbtx in scope. The implementation pairs the
289    /// event's `module` kind with its own module instance id, mirroring what
290    /// `log_event_json` derives from the transaction's `module_id()`.
291    async fn log_event_json_no_dbtx(
292        &self,
293        kind: EventKind,
294        module_kind: Option<ModuleKind>,
295        payload: serde_json::Value,
296        persist: EventPersistence,
297    );
298
299    async fn transaction_update_stream(&self) -> BoxStream<TxSubmissionStatesSM>;
300
301    /// Returns the core API version that the federation supports
302    async fn core_api_version(&self) -> ApiVersion;
303}
304
305#[apply(async_trait_maybe_send!)]
306impl IGlobalClientContext for () {
307    fn module_api(&self) -> DynModuleApi {
308        unimplemented!("fake implementation, only for tests");
309    }
310
311    async fn client_config(&self) -> ClientConfig {
312        unimplemented!("fake implementation, only for tests");
313    }
314
315    fn api(&self) -> &DynGlobalApi {
316        unimplemented!("fake implementation, only for tests");
317    }
318
319    fn decoders(&self) -> &ModuleDecoderRegistry {
320        unimplemented!("fake implementation, only for tests");
321    }
322
323    async fn account(&self, _dbtx: &mut ClientSMDatabaseTransaction<'_, '_>) -> Account {
324        unimplemented!("fake implementation, only for tests");
325    }
326
327    async fn claim_inputs_dyn(
328        &self,
329        _dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
330        _input: InstancelessDynClientInputBundle,
331    ) -> Result<OutPointRange, TransactionSubmitError> {
332        unimplemented!("fake implementation, only for tests");
333    }
334
335    async fn fund_output_dyn(
336        &self,
337        _dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
338        _outputs: InstancelessDynClientOutputBundle,
339    ) -> Result<OutPointRange, TransactionSubmitError> {
340        unimplemented!("fake implementation, only for tests");
341    }
342
343    async fn add_state_machine_dyn(
344        &self,
345        _dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
346        _sm: Box<maybe_add_send_sync!(dyn IState)>,
347    ) -> AddStateMachinesResult {
348        unimplemented!("fake implementation, only for tests");
349    }
350
351    async fn log_event_json(
352        &self,
353        _dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
354        _kind: EventKind,
355        _module: Option<(ModuleKind, ModuleInstanceId)>,
356        _payload: serde_json::Value,
357        _persist: EventPersistence,
358    ) {
359        unimplemented!("fake implementation, only for tests");
360    }
361
362    async fn log_event_json_no_dbtx(
363        &self,
364        _kind: EventKind,
365        _module_kind: Option<ModuleKind>,
366        _payload: serde_json::Value,
367        _persist: EventPersistence,
368    ) {
369        unimplemented!("fake implementation, only for tests");
370    }
371
372    async fn transaction_update_stream(&self) -> BoxStream<TxSubmissionStatesSM> {
373        unimplemented!("fake implementation, only for tests");
374    }
375
376    async fn core_api_version(&self) -> ApiVersion {
377        unimplemented!("fake implementation, only for tests");
378    }
379}
380
381dyn_newtype_define! {
382    /// Global state and functionality provided to all state machines running in the
383    /// client
384    #[derive(Clone)]
385    pub DynGlobalClientContext(Arc<IGlobalClientContext>)
386}
387
388impl DynGlobalClientContext {
389    pub fn new_fake() -> Self {
390        DynGlobalClientContext::from(())
391    }
392
393    pub async fn await_tx_accepted(&self, query_txid: TransactionId) -> Result<(), String> {
394        self.transaction_update_stream()
395            .await
396            .filter_map(|tx_update| {
397                std::future::ready(match tx_update.state {
398                    TxSubmissionStates::Accepted(txid) if txid == query_txid => Some(Ok(())),
399                    TxSubmissionStates::Rejected(txid, submit_error) if txid == query_txid => {
400                        Some(Err(submit_error))
401                    }
402                    _ => None,
403                })
404            })
405            .next_or_pending()
406            .await
407    }
408
409    /// The claim is credited to the operation's account, and any change the
410    /// primary module adds comes back to the same one.
411    pub async fn claim_inputs<I, S>(
412        &self,
413        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
414        inputs: ClientInputBundle<I, S>,
415    ) -> Result<OutPointRange, TransactionSubmitError>
416    where
417        I: IInput + MaybeSend + MaybeSync + 'static,
418        S: IState + MaybeSend + MaybeSync + 'static,
419    {
420        self.claim_inputs_dyn(dbtx, inputs.into_instanceless())
421            .await
422    }
423
424    /// Creates a transaction with the supplied output and funding added by the
425    /// primary module if possible. If the primary module does not have the
426    /// required funds this function fails.
427    ///
428    /// The transactions submission state machine as well as the state machines
429    /// for the funding inputs are generated automatically. The caller is
430    /// responsible for the output's state machines, should there be any
431    /// required.
432    /// The primary module funds the output from the operation's account.
433    pub async fn fund_output<O, S>(
434        &self,
435        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
436        outputs: ClientOutputBundle<O, S>,
437    ) -> Result<OutPointRange, TransactionSubmitError>
438    where
439        O: IOutput + MaybeSend + MaybeSync + 'static,
440        S: IState + MaybeSend + MaybeSync + 'static,
441    {
442        self.fund_output_dyn(dbtx, outputs.into_instanceless())
443            .await
444    }
445
446    /// Allows adding state machines from inside a transition to the executor.
447    /// The added state machine belongs to the same module instance as the state
448    /// machine from inside which it was spawned.
449    pub async fn add_state_machine<S>(
450        &self,
451        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
452        sm: S,
453    ) -> AddStateMachinesResult
454    where
455        S: State + MaybeSend + MaybeSync + 'static,
456    {
457        self.add_state_machine_dyn(dbtx, box_up_state(sm)).await
458    }
459
460    async fn log_event<E>(&self, dbtx: &mut ClientSMDatabaseTransaction<'_, '_>, event: E)
461    where
462        E: Event + Send,
463    {
464        self.log_event_json(
465            dbtx,
466            E::KIND,
467            E::MODULE.map(|m| (m, dbtx.module_id())),
468            serde_json::to_value(&event).expect("Payload serialization can't fail"),
469            <E as Event>::PERSISTENCE,
470        )
471        .await;
472    }
473
474    /// Log an event from outside a state transition, where no
475    /// [`ClientSMDatabaseTransaction`] is in scope. Opens its own database
476    /// transaction. Prefer [`Self::log_event`] whenever a dbtx is available so
477    /// the event commits atomically with the surrounding transition.
478    async fn log_event_no_dbtx<E>(&self, event: E)
479    where
480        E: Event + Send,
481    {
482        self.log_event_json_no_dbtx(
483            E::KIND,
484            E::MODULE,
485            serde_json::to_value(&event).expect("Payload serialization can't fail"),
486            <E as Event>::PERSISTENCE,
487        )
488        .await;
489    }
490}
491
492fn states_to_instanceless_dyn<S: IState + MaybeSend + MaybeSync + 'static>(
493    state_gen: StateGenerator<S>,
494) -> StateGenerator<Box<maybe_add_send_sync!(dyn IState + 'static)>> {
495    Arc::new(move |out_point_range| {
496        let states: Vec<S> = state_gen(out_point_range);
497        states
498            .into_iter()
499            .map(|state| box_up_state(state))
500            .collect()
501    })
502}
503
504/// Not sure why I couldn't just directly call `Box::new` ins
505/// [`states_to_instanceless_dyn`], but this fixed it.
506fn box_up_state(state: impl IState + 'static) -> Box<maybe_add_send_sync!(dyn IState + 'static)> {
507    Box::new(state)
508}
509
510impl<T> From<Arc<T>> for DynGlobalClientContext
511where
512    T: IGlobalClientContext,
513{
514    fn from(inner: Arc<T>) -> Self {
515        DynGlobalClientContext { inner }
516    }
517}
518
519fn states_add_instance(
520    module_instance_id: ModuleInstanceId,
521    state_gen: StateGenerator<Box<maybe_add_send_sync!(dyn IState + 'static)>>,
522) -> StateGenerator<DynState> {
523    Arc::new(move |out_point_range| {
524        let states = state_gen(out_point_range);
525        Iterator::collect(
526            states
527                .into_iter()
528                .map(|state| DynState::from_parts(module_instance_id, state)),
529        )
530    })
531}
532
533pub type ModuleGlobalContextGen = ContextGen;
534
535/// Resources particular to a module instance
536pub struct ClientModuleInstance<'m, M: ClientModule> {
537    /// Instance id of the module
538    pub id: ModuleInstanceId,
539    /// Module-specific DB
540    pub db: Database,
541    /// Module-specific API
542    pub api: DynModuleApi,
543
544    pub module: &'m M,
545}
546
547impl<'m, M: ClientModule> ClientModuleInstance<'m, M> {
548    /// Get a reference to the module
549    pub fn inner(&self) -> &'m M {
550        self.module
551    }
552}
553
554impl<M> ops::Deref for ClientModuleInstance<'_, M>
555where
556    M: ClientModule,
557{
558    type Target = M;
559
560    fn deref(&self) -> &Self::Target {
561        self.module
562    }
563}
564#[derive(Deserialize)]
565pub struct GetInviteCodeRequest {
566    pub peer: PeerId,
567}
568
569pub struct TransactionUpdates {
570    pub update_stream: BoxStream<'static, TxSubmissionStatesSM>,
571}
572
573impl TransactionUpdates {
574    /// Waits for the transaction to be accepted or rejected as part of the
575    /// operation to which the `TransactionUpdates` object is subscribed.
576    pub async fn await_tx_accepted(self, await_txid: TransactionId) -> Result<(), String> {
577        debug!(target: LOG_CLIENT, %await_txid, "Await tx accepted");
578        self.update_stream
579            .filter_map(|tx_update| {
580                std::future::ready(match tx_update.state {
581                    TxSubmissionStates::Accepted(txid) if txid == await_txid => Some(Ok(())),
582                    TxSubmissionStates::Rejected(txid, submit_error) if txid == await_txid => {
583                        Some(Err(submit_error))
584                    }
585                    _ => None,
586                })
587            })
588            .next_or_pending()
589            .await?;
590        debug!(target: LOG_CLIENT, %await_txid, "Tx accepted");
591        Ok(())
592    }
593}
594
595/// Admin (guardian) identification and authentication
596pub struct AdminCreds {
597    /// Guardian's own `peer_id`
598    pub peer_id: PeerId,
599    /// Authentication details
600    pub auth: ApiAuth,
601}