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#[derive(Clone)]
61pub struct ClientModuleEvent {
62 module_kind: Option<ModuleKind>,
63 kind: EventKind,
64 payload: serde_json::Value,
65 persistence: EventPersistence,
66}
67
68#[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 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 async fn fee_quote(
110 &self,
111 operation_id: OperationId,
112 request: FeeQuoteRequest,
113 ) -> Result<FeeQuote, TransactionSubmitError>;
114
115 async fn get_balance_for_unit(
118 &self,
119 unit: AmountUnit,
120 account: Account,
121 ) -> Result<Amount, ModuleLookupError>;
122
123 fn supports_account(&self, unit: AmountUnit, account: Account) -> bool;
126
127 async fn operation_account_dbtx(
130 &self,
131 dbtx: &mut DatabaseTransaction<'_>,
132 operation_id: OperationId,
133 ) -> Account;
134
135 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 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 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#[derive(Clone, Default)]
204pub struct FinalClientIface(Arc<std::sync::OnceLock<Weak<dyn ClientContextIface>>>);
205
206impl FinalClientIface {
207 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}
230pub 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
254pub struct ClientContextSelfRef<'s, M> {
257 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 #[allow(clippy::needless_lifetimes)] 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 pub fn global_api(&self) -> DynGlobalApi {
325 self.client.get().api_clone()
326 }
327
328 pub fn module_api(&self) -> DynModuleApi {
330 self.global_api().with_module(self.module_instance_id)
331 }
332
333 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 pub fn make_dyn_output(&self, output: <M::Common as ModuleCommon>::Output) -> DynOutput {
380 self.make_dyn(output)
381 }
382
383 pub fn make_dyn_input(&self, input: <M::Common as ModuleCommon>::Input) -> DynInput {
385 self.make_dyn(input)
386 }
387
388 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 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 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 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 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 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 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 outputs: Vec<OutPoint>,
562 ) -> Result<(), TransactionSubmitError> {
563 self.client
564 .get()
565 .await_primary_module_outputs(operation_id, outputs)
566 .await
567 }
568
569 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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#[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}
1087pub enum PrimaryModuleSupport {
1089 Any {
1091 priority: PrimaryModulePriority,
1092 accounts: AccountSupport,
1093 },
1094 Selected {
1096 priority: PrimaryModulePriority,
1097 units: BTreeSet<AmountUnit>,
1098 accounts: AccountSupport,
1099 },
1100 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1125pub enum AccountSupport {
1126 PrimaryOnly,
1129 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#[apply(async_trait_maybe_send!)]
1144pub trait ClientModule: Debug + MaybeSend + MaybeSync + 'static {
1145 type Init: ClientModuleInit;
1146
1147 type Common: ModuleCommon;
1149
1150 type Backup: ModuleBackup;
1153
1154 type ModuleStateMachineContext: Context;
1157
1158 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 async fn start(&self) {}
1181
1182 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 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 fn input_fee(
1227 &self,
1228 amount: &Amounts,
1229 input: &<Self::Common as ModuleCommon>::Input,
1230 ) -> Option<Amounts>;
1231
1232 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 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 fn supports_being_primary(&self) -> PrimaryModuleSupport {
1272 PrimaryModuleSupport::None
1273 }
1274
1275 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 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 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 async fn get_balance(
1391 &self,
1392 _dbtx: &mut DatabaseTransaction<'_>,
1393 _unit: AmountUnit,
1394 _account: Account,
1395 ) -> Amount {
1396 unimplemented!()
1397 }
1398
1399 async fn get_balances(&self, _dbtx: &mut DatabaseTransaction<'_>) -> Amounts {
1402 unimplemented!()
1403 }
1404
1405 async fn subscribe_balance_changes(&self) -> BoxStream<'static, ()> {
1408 unimplemented!()
1409 }
1410
1411 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#[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
1722pub use fedimint_core::{IdxRange, OutPointRange, OutPointRangeIter};
1724
1725pub type StateGenerator<S> = Arc<maybe_add_send_sync!(dyn Fn(OutPointRange) -> Vec<S> + 'static)>;