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
56pub mod error;
58
59pub mod backup;
60pub mod envs;
62pub mod meta;
63pub mod module;
65pub mod oplog;
67pub mod secret;
69pub mod sm;
71pub 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 #[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#[derive(Serialize, Deserialize)]
140pub struct TxSubmissionStalledEvent {
141 pub txid: TransactionId,
142 pub operation_id: OperationId,
143 pub attempt: u64,
145 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 #[serde(default)]
182 pub kind: Option<ModuleKind>,
183 #[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 fn module_api(&self) -> DynModuleApi;
229
230 async fn client_config(&self) -> ClientConfig;
231
232 fn api(&self) -> &DynGlobalApi;
239
240 fn decoders(&self) -> &ModuleDecoderRegistry;
241
242 async fn account(&self, dbtx: &mut ClientSMDatabaseTransaction<'_, '_>) -> Account;
248
249 async fn claim_inputs_dyn(
254 &self,
255 dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
256 inputs: InstancelessDynClientInputBundle,
257 ) -> Result<OutPointRange, TransactionSubmitError>;
258
259 async fn fund_output_dyn(
264 &self,
265 dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
266 outputs: InstancelessDynClientOutputBundle,
267 ) -> Result<OutPointRange, TransactionSubmitError>;
268
269 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 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 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 #[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 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 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 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 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
504fn 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
535pub struct ClientModuleInstance<'m, M: ClientModule> {
537 pub id: ModuleInstanceId,
539 pub db: Database,
541 pub api: DynModuleApi,
543
544 pub module: &'m M,
545}
546
547impl<'m, M: ClientModule> ClientModuleInstance<'m, M> {
548 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 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
595pub struct AdminCreds {
597 pub peer_id: PeerId,
599 pub auth: ApiAuth,
601}