1use std::collections::{BTreeMap, HashSet};
2use std::convert::Infallible;
3use std::fmt::{self, Formatter};
4use std::future::{Future, pending};
5use std::ops::Range;
6use std::pin::Pin;
7use std::sync::Arc;
8use std::time::{Duration, SystemTime, UNIX_EPOCH};
9
10use async_stream::try_stream;
11use bitcoin::key::Secp256k1;
12use bitcoin::key::rand::thread_rng;
13use bitcoin::secp256k1::{self, PublicKey};
14use fedimint_api_client::api::global_api::with_request_hook::ApiRequestHook;
15use fedimint_api_client::api::{
16 ApiVersionSet, DynGlobalApi, FederationApiExt as _, FederationError, FederationResult,
17 IGlobalFederationApi,
18};
19use fedimint_bitcoind::DynBitcoindRpc;
20use fedimint_client_module::module::recovery::RecoveryProgress;
21use fedimint_client_module::module::{
22 ClientContextIface, ClientModule, ClientModuleRegistry, DynClientModule, FinalClientIface,
23 IClientModule, IdxRange, OutPointRange, PrimaryModulePriority, PrimaryModuleSupport,
24};
25use fedimint_client_module::oplog::IOperationLog;
26use fedimint_client_module::secret::{PlainRootSecretStrategy, RootSecretStrategy as _};
27use fedimint_client_module::sm::executor::{ActiveStateKey, IExecutor, InactiveStateKey};
28use fedimint_client_module::sm::{ActiveStateMeta, DynState, InactiveStateMeta};
29use fedimint_client_module::transaction::{
30 FeeQuote, FeeQuoteRequest, TRANSACTION_SUBMISSION_MODULE_INSTANCE, TransactionBuilder,
31 TxSubmissionStates, TxSubmissionStatesSM,
32};
33use fedimint_client_module::{
34 AddStateMachinesResult, ClientModuleInstance, GetInviteCodeRequest, ModuleGlobalContextGen,
35 ModuleRecoveryCompleted, TransactionUpdates, TxCreatedEvent,
36};
37use fedimint_connectors::{ConnectorRegistry, PeerStatus};
38use fedimint_core::config::{
39 ClientConfig, FederationId, GlobalClientConfig, JsonClientConfig, ModuleInitRegistry,
40};
41use fedimint_core::core::{
42 Account, DynInput, DynOutput, ModuleInstanceId, ModuleKind, OperationId,
43};
44use fedimint_core::db::{
45 AutocommitError, Database, DatabaseRecord, DatabaseTransaction, DbMigrationError,
46 IDatabaseTransactionOpsCore as _, IDatabaseTransactionOpsCoreTyped as _, NonCommittable,
47};
48use fedimint_core::encoding::{Decodable, Encodable};
49use fedimint_core::endpoint_constants::{CLIENT_CONFIG_ENDPOINT, VERSION_ENDPOINT};
50use fedimint_core::envs::is_running_in_test_env;
51use fedimint_core::invite_code::InviteCode;
52use fedimint_core::module::registry::{ModuleDecoderRegistry, ModuleRegistry};
53use fedimint_core::module::{
54 AmountUnit, Amounts, ApiRequestErased, ApiVersion, MultiApiVersion,
55 SupportedApiVersionsSummary, SupportedCoreApiVersions, SupportedModuleApiVersions,
56};
57use fedimint_core::net::api_announcement::SignedApiAnnouncement;
58use fedimint_core::peer_availability::{MergedPeerAvailability, merge_peer_availability};
59use fedimint_core::runtime::sleep;
60use fedimint_core::task::{
61 Elapsed, MaybeSend, MaybeSync, ShuttingDownError, TaskGroup, TaskHandle,
62};
63use fedimint_core::transaction::Transaction;
64use fedimint_core::util::backoff_util::custom_backoff;
65use fedimint_core::util::{BoxStream, FmtCompact as _, SafeUrl, backoff_util, retry};
66use fedimint_core::{
67 Amount, ChainId, NumPeers, OutPoint, PeerId, apply, async_trait_maybe_send, maybe_add_send,
68 maybe_add_send_sync, runtime,
69};
70use fedimint_derive_secret::DerivableSecret;
71use fedimint_eventlog::{
72 DBTransactionEventLogExt as _, DynEventLogTrimableTracker, Event, EventHandlerError, EventKind,
73 EventLogEntry, EventLogId, EventLogTrackerError, EventLogTrimableId, EventLogTrimableTracker,
74 EventPersistence, PersistedLogEntry,
75};
76use fedimint_logging::{LOG_CLIENT, LOG_CLIENT_NET_API, LOG_CLIENT_RECOVERY};
77use futures::stream::FuturesUnordered;
78use futures::{Stream, StreamExt as _};
79use global_ctx::ModuleGlobalClientContext;
80use serde::{Deserialize, Serialize};
81use tokio::sync::{broadcast, oneshot, watch};
82use tokio_stream::wrappers::WatchStream;
83use tracing::{Span, debug, info, warn};
84
85use crate::ClientBuilder;
86use crate::api_announcements::{ApiAnnouncementPrefix, get_api_urls};
87use crate::backup::Metadata;
88use crate::client::event_log::DefaultApplicationEventLogKey;
89use crate::db::{
90 ApiSecretKey, CachedApiVersionSet, CachedApiVersionSetKey, ChainIdKey,
91 ChronologicalOperationLogKey, ClientConfigKey, ClientMetadataKey, ClientModuleRecovery,
92 ClientModuleRecoveryState, EncodedClientSecretKey, OperationAccountKey, OperationLogKey,
93 PeerLastApiVersionsSummary, PeerLastApiVersionsSummaryKey, PendingClientConfigKey,
94 TransactionFeesKey, apply_migrations_core_client_dbtx, verify_client_db_integrity_dbtx,
95};
96use crate::error::{
97 ApiVersionDiscoveryError, ClientModuleError, ClientSecretError, GlobalRpcError,
98 ModuleLookupError, OperationAlreadyExistsError, OperationNotFoundError, RecoveryError,
99 TransactionSubmitError,
100};
101use crate::meta::MetaService;
102use crate::module_init::{ClientModuleInitRegistry, DynClientModuleInit, IClientModuleInit};
103use crate::oplog::OperationLog;
104use crate::sm::executor::{
105 ActiveModuleOperationStateKeyPrefix, ActiveOperationStateKeyPrefix, Executor,
106 InactiveModuleOperationStateKeyPrefix, InactiveOperationStateKeyPrefix,
107};
108
109pub(crate) mod builder;
110pub(crate) mod event_log;
111pub(crate) mod global_ctx;
112pub(crate) mod handle;
113
114#[cfg(test)]
115mod tests;
116
117const SUPPORTED_CORE_API_VERSIONS: &[fedimint_core::module::ApiVersion] =
121 &[ApiVersion { major: 0, minor: 0 }];
122
123struct FinalizedTransaction {
124 transaction: Transaction,
125 states: Vec<DynState>,
126 change_range: Range<u64>,
127 fees: Amounts,
128}
129
130#[derive(Default)]
132pub(crate) struct PrimaryModuleCandidates {
133 specific: BTreeMap<AmountUnit, Vec<ModuleInstanceId>>,
135 wildcard: Vec<ModuleInstanceId>,
137}
138
139pub(crate) type ModuleRecoveryFuture =
142 Pin<Box<maybe_add_send!(dyn Future<Output = Result<Option<Amount>, ClientModuleError>>)>>;
143
144#[derive(Clone, Debug)]
169pub(crate) enum RecoveryStatus {
170 InProgress(RecoveryProgress),
174 Failed {
178 last_progress: RecoveryProgress,
179 error: Arc<ClientModuleError>,
180 },
181}
182
183impl RecoveryStatus {
184 pub(crate) fn is_successfully_done(&self) -> bool {
189 match self {
190 Self::InProgress(progress) => progress.is_done(),
191 Self::Failed { .. } => false,
192 }
193 }
194
195 pub(crate) fn progress(&self) -> RecoveryProgress {
198 match self {
199 Self::InProgress(progress)
200 | Self::Failed {
201 last_progress: progress,
202 ..
203 } => *progress,
204 }
205 }
206}
207
208pub struct Client {
222 final_client: FinalClientIface,
223 config: tokio::sync::RwLock<ClientConfig>,
224 api_secret: Option<String>,
225 decoders: ModuleDecoderRegistry,
226 connectors: ConnectorRegistry,
227 db: Database,
228 federation_id: FederationId,
229 federation_config_meta: BTreeMap<String, String>,
230 primary_modules: BTreeMap<PrimaryModulePriority, PrimaryModuleCandidates>,
231 pub(crate) modules: ClientModuleRegistry,
232 module_inits: ClientModuleInitRegistry,
233 executor: Executor,
234 pub(crate) api: DynGlobalApi,
235 root_secret: DerivableSecret,
236 operation_log: OperationLog,
237 secp_ctx: Secp256k1<secp256k1::All>,
238 meta_service: Arc<MetaService>,
239
240 task_group: TaskGroup,
241
242 client_span: Span,
246
247 client_recovery_status_receiver: watch::Receiver<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
260
261 log_ordering_wakeup_tx: watch::Sender<()>,
264 log_event_added_rx: watch::Receiver<()>,
266 log_event_added_transient_tx: broadcast::Sender<EventLogEntry>,
267 request_hook: ApiRequestHook,
268 iroh_enable_dht: bool,
269 iroh_enable_next: bool,
270 #[allow(dead_code)]
275 user_bitcoind_rpc: Option<DynBitcoindRpc>,
276 pub(crate) user_bitcoind_rpc_no_chain_id:
281 Option<fedimint_client_module::module::init::BitcoindRpcNoChainIdFactory>,
282}
283
284#[derive(Debug, Serialize, Deserialize)]
285struct ListOperationsParams {
286 limit: Option<usize>,
287 last_seen: Option<ChronologicalOperationLogKey>,
288}
289
290pub const DEFAULT_EVENT_LOG_PAGE_SIZE: u64 = 100;
291pub const MAX_EVENT_LOG_PAGE_SIZE: u64 = 10_000;
292
293#[derive(Debug, Clone, Serialize, Deserialize)]
294struct GetEventLogRequest {
295 pos: Option<EventLogId>,
296 limit: Option<u64>,
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize)]
300pub struct GetOperationIdRequest {
301 operation_id: OperationId,
302}
303
304#[derive(Debug, Clone, Serialize, Deserialize)]
308pub struct BalanceRequest {
309 #[serde(default = "AmountUnit::bitcoin")]
310 unit: AmountUnit,
311 #[serde(default = "Account::primary")]
312 account: Account,
313}
314
315impl Default for BalanceRequest {
319 fn default() -> Self {
320 Self {
321 unit: AmountUnit::bitcoin(),
322 account: Account::primary(),
323 }
324 }
325}
326
327impl Client {
328 pub async fn builder() -> ClientBuilder {
333 ClientBuilder::new()
334 }
335
336 pub fn api(&self) -> &(dyn IGlobalFederationApi + 'static) {
337 self.api.as_ref()
338 }
339
340 pub fn api_clone(&self) -> DynGlobalApi {
341 self.api.clone()
342 }
343
344 pub fn connection_status_stream(&self) -> impl Stream<Item = BTreeMap<PeerId, PeerStatus>> {
347 self.api.connection_status_stream()
348 }
349
350 pub fn federation_reconnect(&self) {
358 let peers: Vec<PeerId> = self.api.all_peers().iter().copied().collect();
359
360 for peer_id in peers {
361 let api = self.api.clone();
362 self.spawn_cancellable(format!("federation-reconnect-once-{peer_id}"), async move {
363 if let Err(e) = api.get_peer_connection(peer_id).await {
364 debug!(
365 target: LOG_CLIENT_NET_API,
366 %peer_id,
367 err = %e.fmt_compact(),
368 "Failed to connect to peer"
369 );
370 }
371 });
372 }
373 }
374
375 pub fn spawn_federation_reconnect(&self) {
397 let peers: Vec<PeerId> = self.api.all_peers().iter().copied().collect();
398
399 for peer_id in peers {
400 let api = self.api.clone();
401 self.spawn_cancellable(format!("federation-reconnect-{peer_id}"), async move {
402 loop {
403 match api.get_peer_connection(peer_id).await {
404 Ok(conn) => {
405 conn.await_disconnection().await;
406 }
407 Err(e) => {
408 debug!(
411 target: LOG_CLIENT_NET_API,
412 %peer_id,
413 err = %e.fmt_compact(),
414 "Failed to connect to peer, will retry"
415 );
416 }
417 }
418 }
419 });
420 }
421 }
422
423 pub fn task_group(&self) -> &TaskGroup {
425 &self.task_group
426 }
427
428 pub(crate) fn make_client_span(federation_id: FederationId) -> Span {
435 tracing::info_span!(
436 target: LOG_CLIENT,
437 parent: None,
438 "client",
439 fed_id = %federation_id.to_prefix(),
440 )
441 }
442
443 pub(crate) fn spawn_cancellable<R>(
446 &self,
447 name: impl Into<String>,
448 future: impl Future<Output = R> + MaybeSend + 'static,
449 ) -> oneshot::Receiver<Result<R, ShuttingDownError>>
450 where
451 R: MaybeSend + 'static,
452 {
453 self.task_group
454 .spawn_cancellable_with_span(self.client_span.clone(), name, future)
455 }
456
457 pub(crate) fn spawn<Fut, R>(
461 &self,
462 name: impl Into<String>,
463 f: impl FnOnce(TaskHandle) -> Fut + MaybeSend + 'static,
464 ) -> oneshot::Receiver<R>
465 where
466 Fut: Future<Output = R> + MaybeSend + 'static,
467 R: MaybeSend + 'static,
468 {
469 self.task_group
470 .spawn_with_span(self.client_span.clone(), name, f)
471 }
472
473 pub fn get_metrics() -> Result<String, fedimint_metrics::prometheus::Error> {
478 fedimint_metrics::get_metrics()
479 }
480
481 #[doc(hidden)]
483 pub fn executor(&self) -> &Executor {
484 &self.executor
485 }
486
487 pub async fn get_config_from_db(db: &Database) -> Option<ClientConfig> {
488 let mut dbtx = db.begin_transaction_nc().await;
489 dbtx.get_value(&ClientConfigKey).await
490 }
491
492 pub async fn get_pending_config_from_db(db: &Database) -> Option<ClientConfig> {
493 let mut dbtx = db.begin_transaction_nc().await;
494 dbtx.get_value(&PendingClientConfigKey).await
495 }
496
497 pub async fn get_api_secret_from_db(db: &Database) -> Option<String> {
498 let mut dbtx = db.begin_transaction_nc().await;
499 dbtx.get_value(&ApiSecretKey).await
500 }
501
502 pub async fn store_encodable_client_secret<T: Encodable>(
503 db: &Database,
504 secret: T,
505 ) -> Result<(), ClientSecretError> {
506 let mut dbtx = db.begin_transaction().await;
507
508 if dbtx.get_value(&EncodedClientSecretKey).await.is_some() {
510 return Err(ClientSecretError::AlreadyExists);
511 }
512
513 let encoded_secret = T::consensus_encode_to_vec(&secret);
514 dbtx.insert_entry(&EncodedClientSecretKey, &encoded_secret)
515 .await;
516 dbtx.commit_tx().await;
517 Ok(())
518 }
519
520 pub async fn load_decodable_client_secret<T: Decodable>(
521 db: &Database,
522 ) -> Result<T, ClientSecretError> {
523 let Some(secret) = Self::load_decodable_client_secret_opt(db).await? else {
524 return Err(ClientSecretError::NotPresent);
525 };
526
527 Ok(secret)
528 }
529
530 pub async fn load_decodable_client_secret_opt<T: Decodable>(
531 db: &Database,
532 ) -> Result<Option<T>, ClientSecretError> {
533 let mut dbtx = db.begin_transaction_nc().await;
534
535 let client_secret = dbtx.get_value(&EncodedClientSecretKey).await;
536
537 Ok(match client_secret {
538 Some(client_secret) => Some(T::consensus_decode_whole(
539 &client_secret,
540 &ModuleRegistry::default(),
541 )?),
542 None => None,
543 })
544 }
545
546 pub async fn load_or_generate_client_secret(db: &Database) -> [u8; 64] {
547 match Self::load_decodable_client_secret::<[u8; 64]>(db).await {
548 Ok(secret) => secret,
549 _ => {
550 let secret = PlainRootSecretStrategy::random(&mut thread_rng());
551 Self::store_encodable_client_secret(db, secret)
552 .await
553 .expect("Storing client secret must work");
554 secret
555 }
556 }
557 }
558
559 pub async fn is_initialized(db: &Database) -> bool {
560 let mut dbtx = db.begin_transaction_nc().await;
561 dbtx.raw_get_bytes(&[ClientConfigKey::DB_PREFIX])
562 .await
563 .expect("Unrecoverable error occurred while reading and entry from the database")
564 .is_some()
565 }
566
567 pub fn start_executor(self: &Arc<Self>) {
568 self.client_span.in_scope(|| {
569 debug!(
570 target: LOG_CLIENT,
571 "Starting fedimint client executor",
572 );
573 });
574 self.executor
575 .start_executor(self.context_gen(), self.client_span.clone());
576 }
577
578 pub fn federation_id(&self) -> FederationId {
579 self.federation_id
580 }
581
582 fn context_gen(self: &Arc<Self>) -> ModuleGlobalContextGen {
583 let client_inner = Arc::downgrade(self);
584 Arc::new(move |module_instance, operation| {
585 ModuleGlobalClientContext {
586 client: client_inner
587 .clone()
588 .upgrade()
589 .expect("ModuleGlobalContextGen called after client was dropped"),
590 module_instance_id: module_instance,
591 operation,
592 }
593 .into()
594 })
595 }
596
597 pub async fn config(&self) -> ClientConfig {
598 self.config.read().await.clone()
599 }
600
601 pub fn api_secret(&self) -> &Option<String> {
603 &self.api_secret
604 }
605
606 pub async fn core_api_version(&self) -> ApiVersion {
612 self.db
615 .begin_transaction_nc()
616 .await
617 .get_value(&CachedApiVersionSetKey)
618 .await
619 .map(|cached: CachedApiVersionSet| cached.0.core)
620 .unwrap_or(ApiVersion { major: 0, minor: 0 })
621 }
622
623 pub async fn chain_id(&self) -> Result<ChainId, FederationError> {
630 if let Some(chain_id) = self
632 .db
633 .begin_transaction_nc()
634 .await
635 .get_value(&ChainIdKey)
636 .await
637 {
638 return Ok(chain_id);
639 }
640
641 let chain_id = self.api.chain_id().await?;
643
644 let mut dbtx = self.db.begin_transaction().await;
646 dbtx.insert_entry(&ChainIdKey, &chain_id).await;
647 dbtx.commit_tx().await;
648
649 Ok(chain_id)
650 }
651
652 pub fn decoders(&self) -> &ModuleDecoderRegistry {
653 &self.decoders
654 }
655
656 fn get_module(&self, instance: ModuleInstanceId) -> &maybe_add_send_sync!(dyn IClientModule) {
658 self.try_get_module(instance)
659 .expect("Module instance not found")
660 }
661
662 fn try_get_module(
663 &self,
664 instance: ModuleInstanceId,
665 ) -> Option<&maybe_add_send_sync!(dyn IClientModule)> {
666 Some(self.modules.get(instance)?.as_ref())
667 }
668
669 pub fn has_module(&self, instance: ModuleInstanceId) -> bool {
670 self.modules.get(instance).is_some()
671 }
672
673 fn transaction_builder_get_balance(
679 &self,
680 builder: &TransactionBuilder,
681 ) -> Result<(Amounts, Amounts), TransactionSubmitError> {
682 let inputs = builder.inputs().map(|input| {
683 let module = self.get_module(input.input.module_instance_id());
684
685 let item_fees = module.input_fee(&input.amounts, &input.input).expect(
686 "We only build transactions with input versions that are supported by the module",
687 );
688
689 (&input.amounts, item_fees)
690 });
691
692 let outputs = builder.outputs().map(|output| {
693 let module = self.get_module(output.output.module_instance_id());
694
695 let item_fees = module.output_fee(&output.amounts, &output.output).expect(
696 "We only build transactions with output versions that are supported by the module",
697 );
698
699 (&output.amounts, item_fees)
700 });
701
702 accumulate_transaction_balance(inputs, outputs)
703 }
704}
705
706fn accumulate_transaction_balance<'a>(
709 inputs: impl IntoIterator<Item = (&'a Amounts, Amounts)>,
710 outputs: impl IntoIterator<Item = (&'a Amounts, Amounts)>,
711) -> Result<(Amounts, Amounts), TransactionSubmitError> {
712 let mut in_amounts = Amounts::ZERO;
713 let mut out_amounts = Amounts::ZERO;
714 let mut fee_amounts = Amounts::ZERO;
715
716 for (amount, item_fees) in inputs {
717 in_amounts
718 .checked_add_mut(amount)
719 .ok_or(TransactionSubmitError::AmountOverflow)?;
720 fee_amounts
721 .checked_add_mut(&item_fees)
722 .ok_or(TransactionSubmitError::AmountOverflow)?;
723 }
724
725 for (amount, item_fees) in outputs {
726 out_amounts
727 .checked_add_mut(amount)
728 .ok_or(TransactionSubmitError::AmountOverflow)?;
729 fee_amounts
730 .checked_add_mut(&item_fees)
731 .ok_or(TransactionSubmitError::AmountOverflow)?;
732 }
733
734 out_amounts
735 .checked_add_mut(&fee_amounts)
736 .ok_or(TransactionSubmitError::AmountOverflow)?;
737 Ok((in_amounts, out_amounts))
738}
739
740impl Client {
741 pub fn get_internal_payment_markers(
742 &self,
743 ) -> Result<(PublicKey, u64), bitcoin::secp256k1::Error> {
744 Ok((self.federation_id().to_fake_ln_pub_key(&self.secp_ctx)?, 0))
745 }
746
747 pub fn get_config_meta(&self, key: &str) -> Option<String> {
749 self.federation_config_meta.get(key).cloned()
750 }
751
752 pub(crate) fn root_secret(&self) -> DerivableSecret {
753 self.root_secret.clone()
754 }
755
756 pub async fn add_state_machines(
757 &self,
758 dbtx: &mut DatabaseTransaction<'_>,
759 states: Vec<DynState>,
760 ) -> AddStateMachinesResult {
761 self.executor.add_state_machines_dbtx(dbtx, states).await
762 }
763
764 pub async fn get_active_operations(&self) -> HashSet<OperationId> {
766 let active_states = self.executor.get_active_states().await;
767 let mut active_operations = HashSet::with_capacity(active_states.len());
768 let mut dbtx = self.db().begin_transaction_nc().await;
769 for (state, _) in active_states {
770 let operation_id = state.operation_id();
771 if dbtx
772 .get_value(&OperationLogKey { operation_id })
773 .await
774 .is_some()
775 {
776 active_operations.insert(operation_id);
777 }
778 }
779 active_operations
780 }
781
782 pub fn operation_log(&self) -> &OperationLog {
783 &self.operation_log
784 }
785
786 pub fn meta_service(&self) -> &Arc<MetaService> {
788 &self.meta_service
789 }
790
791 pub async fn get_meta_expiration_timestamp(&self) -> Option<SystemTime> {
793 let meta_service = self.meta_service();
794 let ts = meta_service
795 .get_field::<u64>(self.db(), "federation_expiry_timestamp")
796 .await
797 .and_then(|v| v.value)?;
798 Some(UNIX_EPOCH + Duration::from_secs(ts))
799 }
800
801 async fn finalize_transaction(
803 &self,
804 dbtx: &mut DatabaseTransaction<'_>,
805 operation_id: OperationId,
806 mut partial_transaction: TransactionBuilder,
807 ) -> Result<FinalizedTransaction, TransactionSubmitError> {
808 let (in_amounts, out_amounts) =
809 self.transaction_builder_get_balance(&partial_transaction)?;
810
811 let mut added_inputs_bundles = vec![];
812 let mut added_outputs_bundles = vec![];
813
814 for unit in in_amounts.units().union(&out_amounts.units()) {
825 let input_amount = in_amounts.get(unit).copied().unwrap_or_default();
826 let output_amount = out_amounts.get(unit).copied().unwrap_or_default();
827 if input_amount == output_amount {
828 continue;
829 }
830
831 let Some((module_id, module)) = self.primary_module_for_unit(*unit) else {
832 return Err(TransactionSubmitError::NoPrimaryModule { unit: *unit });
833 };
834
835 let account = partial_transaction.account();
836
837 if !Self::module_supports_account(module, account) {
838 return Err(TransactionSubmitError::AccountNotSupported {
839 unit: *unit,
840 account,
841 });
842 }
843
844 let (added_input_bundle, added_output_bundle) = module
845 .create_final_inputs_and_outputs(
846 module_id,
847 dbtx,
848 operation_id,
849 *unit,
850 input_amount,
851 output_amount,
852 account,
853 )
854 .await?;
855
856 added_inputs_bundles.push(added_input_bundle);
857 added_outputs_bundles.push(added_output_bundle);
858 }
859
860 let change_range = Range {
864 start: partial_transaction.outputs().count() as u64,
865 end: (partial_transaction.outputs().count() as u64
866 + added_outputs_bundles
867 .iter()
868 .map(|output| output.outputs().len() as u64)
869 .sum::<u64>()),
870 };
871
872 for added_inputs in added_inputs_bundles {
873 partial_transaction = partial_transaction.with_inputs(added_inputs);
874 }
875
876 for added_outputs in added_outputs_bundles {
877 partial_transaction = partial_transaction.with_outputs(added_outputs);
878 }
879
880 let (input_amounts, output_amounts) =
881 self.transaction_builder_get_balance(&partial_transaction)?;
882
883 for (unit, output_amount) in output_amounts {
884 let input_amount = input_amounts.get(&unit).copied().unwrap_or_default();
885
886 assert!(input_amount >= output_amount, "Transaction is underfunded");
887 }
888
889 let fees = {
893 let mut input_total = Amounts::ZERO;
894 for input in partial_transaction.inputs() {
895 input_total
896 .checked_add_mut(&input.amounts)
897 .expect("Own transaction amounts don't overflow");
898 }
899 let mut output_total = Amounts::ZERO;
900 for output in partial_transaction.outputs() {
901 output_total
902 .checked_add_mut(&output.amounts)
903 .expect("Own transaction amounts don't overflow");
904 }
905 input_total
906 .checked_sub(&output_total)
907 .expect("Inputs >= outputs for own transactions")
908 };
909
910 let (transaction, states) = partial_transaction.build(&self.secp_ctx, thread_rng());
911
912 Ok(FinalizedTransaction {
913 transaction,
914 states,
915 change_range,
916 fees,
917 })
918 }
919
920 pub async fn fee_quote(
941 &self,
942 operation_id: OperationId,
943 request: FeeQuoteRequest,
944 ) -> Result<FeeQuote, TransactionSubmitError> {
945 let FeeQuoteRequest {
946 input_amount,
947 output_amount,
948 input_fee,
949 output_fee,
950 account,
951 } = request;
952
953 let mut gross_input = input_amount.clone();
957 let mut gross_output = output_amount.clone();
958 let mut input_fees = input_fee.clone();
959 let mut output_fees = output_fee.clone();
960
961 let balance_input = input_amount;
967 let balance_output = output_amount
968 .checked_add(&input_fee)
969 .and_then(|amounts| amounts.checked_add(&output_fee))
970 .expect("explicit amounts and fees cannot overflow an Amounts");
971
972 let mut dbtx = self.db.begin_transaction_nc().await;
976
977 for unit in balance_input.units().union(&balance_output.units()) {
980 let balance_input_amount = balance_input.get(unit).copied().unwrap_or_default();
981 let balance_output_amount = balance_output.get(unit).copied().unwrap_or_default();
982 if balance_input_amount == balance_output_amount {
983 continue;
984 }
985
986 let Some((module_id, module)) = self.primary_module_for_unit(*unit) else {
987 return Err(TransactionSubmitError::NoPrimaryModule { unit: *unit });
988 };
989
990 if !Self::module_supports_account(module, account) {
991 return Err(TransactionSubmitError::AccountNotSupported {
992 unit: *unit,
993 account,
994 });
995 }
996
997 let change = module
998 .quote_final_inputs_and_outputs(
999 module_id,
1000 &mut dbtx.to_ref_nc(),
1001 operation_id,
1002 *unit,
1003 balance_input_amount,
1004 balance_output_amount,
1005 account,
1006 )
1007 .await?;
1008
1009 gross_input.checked_add_mut(&change.input_amount);
1010 gross_output.checked_add_mut(&change.output_amount);
1011 input_fees.checked_add_mut(&change.input_fee);
1012 output_fees.checked_add_mut(&change.output_fee);
1013 }
1014
1015 dbtx.ignore_uncommitted();
1018
1019 let mut dust = Amounts::ZERO;
1024 for unit in gross_input.units().union(&gross_output.units()) {
1025 let total = gross_input
1026 .get(unit)
1027 .copied()
1028 .unwrap_or_default()
1029 .saturating_sub(gross_output.get(unit).copied().unwrap_or_default());
1030 let fees = input_fees.get(unit).copied().unwrap_or_default()
1031 + output_fees.get(unit).copied().unwrap_or_default();
1032 dust = dust
1033 .checked_add_unit(total.saturating_sub(fees), *unit)
1034 .expect("dust cannot overflow an Amounts");
1035 }
1036
1037 Ok(FeeQuote {
1038 input: input_fees,
1039 output: output_fees,
1040 dust,
1041 })
1042 }
1043
1044 pub async fn finalize_and_submit_transaction<F, M>(
1080 &self,
1081 operation_id: OperationId,
1082 operation_type: &str,
1083 operation_meta_gen: F,
1084 tx_builder: TransactionBuilder,
1085 ) -> Result<OutPointRange, TransactionSubmitError>
1086 where
1087 F: Fn(OutPointRange) -> M + Clone + MaybeSend + MaybeSync,
1088 M: serde::Serialize + MaybeSend,
1089 {
1090 let operation_type = operation_type.to_owned();
1091
1092 let autocommit_res = self
1093 .db
1094 .autocommit(
1095 |dbtx, _| {
1096 let operation_type = operation_type.clone();
1097 let tx_builder = tx_builder.clone();
1098 let operation_meta_gen = operation_meta_gen.clone();
1099 Box::pin(async move {
1100 self.finalize_and_submit_transaction_dbtx(
1101 dbtx,
1102 operation_id,
1103 &operation_type,
1104 operation_meta_gen,
1105 tx_builder,
1106 )
1107 .await
1108 })
1109 },
1110 Some(100), )
1112 .await;
1113
1114 match autocommit_res {
1115 Ok(txid) => Ok(txid),
1116 Err(AutocommitError::ClosureError { error, .. }) => Err(error),
1117 Err(AutocommitError::CommitFailed { last_error, .. }) => {
1118 Err(TransactionSubmitError::Database(last_error))
1119 }
1120 }
1121 }
1122
1123 pub async fn finalize_and_submit_transaction_dbtx<F, M>(
1132 &self,
1133 dbtx: &mut DatabaseTransaction<'_>,
1134 operation_id: OperationId,
1135 operation_type: &str,
1136 operation_meta_gen: F,
1137 tx_builder: TransactionBuilder,
1138 ) -> Result<OutPointRange, TransactionSubmitError>
1139 where
1140 F: FnOnce(OutPointRange) -> M + MaybeSend,
1141 M: serde::Serialize + MaybeSend,
1142 {
1143 if Client::operation_exists_dbtx(dbtx, operation_id).await {
1144 return Err(OperationAlreadyExistsError { operation_id }.into());
1145 }
1146
1147 let account = tx_builder.account();
1148
1149 let out_point_range = self
1150 .finalize_and_submit_transaction_inner(dbtx, operation_id, tx_builder)
1151 .await?;
1152
1153 self.operation_log()
1154 .add_operation_log_entry_dbtx(
1155 dbtx,
1156 operation_id,
1157 account,
1158 operation_type,
1159 operation_meta_gen(out_point_range),
1160 )
1161 .await;
1162
1163 Ok(out_point_range)
1164 }
1165
1166 async fn finalize_and_submit_transaction_inner(
1167 &self,
1168 dbtx: &mut DatabaseTransaction<'_>,
1169 operation_id: OperationId,
1170 tx_builder: TransactionBuilder,
1171 ) -> Result<OutPointRange, TransactionSubmitError> {
1172 let account = tx_builder.account();
1173 let FinalizedTransaction {
1174 transaction,
1175 mut states,
1176 change_range,
1177 fees,
1178 } = self
1179 .finalize_transaction(&mut dbtx.to_ref_nc(), operation_id, tx_builder)
1180 .await?;
1181
1182 if transaction.consensus_encode_to_vec().len() > Transaction::MAX_TX_SIZE {
1183 let inputs = transaction
1184 .inputs
1185 .iter()
1186 .map(DynInput::module_instance_id)
1187 .collect::<Vec<_>>();
1188 let outputs = transaction
1189 .outputs
1190 .iter()
1191 .map(DynOutput::module_instance_id)
1192 .collect::<Vec<_>>();
1193 warn!(
1194 target: LOG_CLIENT_NET_API,
1195 size=%transaction.consensus_encode_to_vec().len(),
1196 ?inputs,
1197 ?outputs,
1198 "Transaction too large",
1199 );
1200 debug!(target: LOG_CLIENT_NET_API, ?transaction, "transaction details");
1201 return Err(TransactionSubmitError::TransactionTooLarge {
1202 size: transaction.consensus_encode_to_vec().len(),
1203 max: Transaction::MAX_TX_SIZE,
1204 });
1205 }
1206
1207 let txid = transaction.tx_hash();
1208
1209 debug!(
1210 target: LOG_CLIENT_NET_API,
1211 %txid,
1212 operation_id = %operation_id.fmt_short(),
1213 ?transaction,
1214 "Finalized and submitting transaction",
1215 );
1216
1217 let tx_submission_sm = DynState::from_typed(
1218 TRANSACTION_SUBMISSION_MODULE_INSTANCE,
1219 TxSubmissionStatesSM {
1220 operation_id,
1221 state: TxSubmissionStates::Created(transaction),
1222 },
1223 );
1224 states.push(tx_submission_sm);
1225
1226 self.executor.add_state_machines_dbtx(dbtx, states).await?;
1227
1228 dbtx.insert_new_entry(&TransactionFeesKey(txid), &fees)
1229 .await;
1230
1231 self.log_event_dbtx(
1232 dbtx,
1233 None,
1234 TxCreatedEvent {
1235 txid,
1236 operation_id,
1237 account,
1238 },
1239 )
1240 .await;
1241
1242 Ok(OutPointRange::new(txid, IdxRange::from(change_range)))
1243 }
1244
1245 async fn transaction_update_stream(
1246 &self,
1247 operation_id: OperationId,
1248 ) -> BoxStream<'static, TxSubmissionStatesSM> {
1249 self.executor
1250 .notifier()
1251 .module_notifier::<TxSubmissionStatesSM>(
1252 TRANSACTION_SUBMISSION_MODULE_INSTANCE,
1253 self.final_client.clone(),
1254 )
1255 .subscribe(operation_id)
1256 .await
1257 }
1258
1259 pub async fn operation_exists(&self, operation_id: OperationId) -> bool {
1260 let mut dbtx = self.db().begin_transaction_nc().await;
1261
1262 Client::operation_exists_dbtx(&mut dbtx, operation_id).await
1263 }
1264
1265 pub async fn operation_account_dbtx(
1268 dbtx: &mut DatabaseTransaction<'_>,
1269 operation_id: OperationId,
1270 ) -> Account {
1271 dbtx.get_value(&OperationAccountKey(operation_id))
1272 .await
1273 .unwrap_or(Account::Primary)
1274 }
1275
1276 pub async fn set_operation_account_dbtx(
1286 dbtx: &mut DatabaseTransaction<'_>,
1287 operation_id: OperationId,
1288 account: Account,
1289 ) {
1290 let key = OperationAccountKey(operation_id);
1291
1292 if let Some(existing) = dbtx.get_value(&key).await {
1293 assert_eq!(
1294 existing,
1295 account,
1296 "operation {} is bound to {existing} and cannot be rebound to {account}",
1297 operation_id.fmt_full()
1298 );
1299
1300 return;
1301 }
1302
1303 if account != Account::Primary {
1304 dbtx.insert_entry(&key, &account).await;
1305 }
1306 }
1307
1308 pub async fn operation_exists_dbtx(
1309 dbtx: &mut DatabaseTransaction<'_>,
1310 operation_id: OperationId,
1311 ) -> bool {
1312 let active_state_exists = dbtx
1313 .find_by_prefix(&ActiveOperationStateKeyPrefix { operation_id })
1314 .await
1315 .next()
1316 .await
1317 .is_some();
1318
1319 let inactive_state_exists = dbtx
1320 .find_by_prefix(&InactiveOperationStateKeyPrefix { operation_id })
1321 .await
1322 .next()
1323 .await
1324 .is_some();
1325
1326 active_state_exists || inactive_state_exists
1327 }
1328
1329 pub async fn has_active_states(&self, operation_id: OperationId) -> bool {
1331 self.executor.has_active_states(operation_id).await
1332 }
1333
1334 pub async fn await_no_active_states(&self, operation_id: OperationId) {
1354 self.executor.await_no_active_states(operation_id).await;
1355 }
1356
1357 pub async fn get_operation_fees(
1376 &self,
1377 operation_id: OperationId,
1378 ) -> Result<Option<Amounts>, OperationNotFoundError> {
1379 if !self.operation_exists(operation_id).await {
1380 return Err(OperationNotFoundError { operation_id });
1381 }
1382
1383 let (active_states, inactive_states) =
1384 self.executor().get_operation_states(operation_id).await;
1385
1386 let states = active_states
1387 .into_iter()
1388 .map(|(state, _)| state)
1389 .chain(inactive_states.into_iter().map(|(state, _)| state));
1390
1391 let accepted_transactions = states
1392 .filter_map(|state| {
1393 let tx_state = state.as_any().downcast_ref::<TxSubmissionStatesSM>()?;
1394
1395 match &tx_state.state {
1396 TxSubmissionStates::Accepted(transaction_id) => Some(*transaction_id),
1397 _ => None,
1398 }
1399 })
1400 .collect::<HashSet<_>>();
1401
1402 let mut dbtx = self.db.begin_transaction_nc().await;
1404 let mut total_fees = Amounts::ZERO;
1405 for txid in &accepted_transactions {
1406 let Some(fees) = dbtx.get_value(&TransactionFeesKey(*txid)).await else {
1407 return Ok(None);
1408 };
1409 total_fees = total_fees
1410 .checked_add(&fees)
1411 .expect("Fee amounts don't overflow in practice");
1412 }
1413
1414 Ok(Some(total_fees))
1415 }
1416
1417 pub async fn await_primary_bitcoin_module_output(
1420 &self,
1421 operation_id: OperationId,
1422 out_point: OutPoint,
1423 ) -> Result<(), TransactionSubmitError> {
1424 self.primary_module_for_unit(AmountUnit::BITCOIN)
1425 .ok_or(TransactionSubmitError::NoPrimaryModule {
1426 unit: AmountUnit::BITCOIN,
1427 })?
1428 .1
1429 .await_primary_module_output(operation_id, out_point)
1430 .await
1431 .map_err(TransactionSubmitError::PrimaryModule)
1432 }
1433
1434 pub fn get_first_module<M: ClientModule>(
1436 &'_ self,
1437 ) -> Result<ClientModuleInstance<'_, M>, ModuleLookupError> {
1438 let module_kind = M::kind();
1439 let id = self.get_first_instance(&module_kind).ok_or_else(|| {
1440 ModuleLookupError::NoModuleOfKind {
1441 kind: module_kind.clone(),
1442 }
1443 })?;
1444 let module: &M = self
1445 .try_get_module(id)
1446 .ok_or(ModuleLookupError::UnknownInstance { instance_id: id })?
1447 .as_any()
1448 .downcast_ref::<M>()
1449 .ok_or(ModuleLookupError::WrongModuleType {
1450 instance_id: id,
1451 expected: std::any::type_name::<M>(),
1452 })?;
1453 let (db, _) = self.db().with_prefix_module_id(id);
1454 Ok(ClientModuleInstance {
1455 id,
1456 db,
1457 api: self.api().with_module(id),
1458 module,
1459 })
1460 }
1461
1462 pub fn get_module_client_dyn(
1463 &self,
1464 instance_id: ModuleInstanceId,
1465 ) -> Result<&maybe_add_send_sync!(dyn IClientModule), ModuleLookupError> {
1466 self.try_get_module(instance_id)
1467 .ok_or(ModuleLookupError::UnknownInstance { instance_id })
1468 }
1469
1470 pub fn db(&self) -> &Database {
1471 &self.db
1472 }
1473
1474 pub fn endpoints(&self) -> &ConnectorRegistry {
1475 &self.connectors
1476 }
1477
1478 pub async fn transaction_updates(&self, operation_id: OperationId) -> TransactionUpdates {
1481 TransactionUpdates {
1482 update_stream: self.transaction_update_stream(operation_id).await,
1483 }
1484 }
1485
1486 pub fn get_first_instance(&self, module_kind: &ModuleKind) -> Option<ModuleInstanceId> {
1488 self.modules
1489 .iter_modules()
1490 .find(|(_, kind, _module)| *kind == module_kind)
1491 .map(|(instance_id, _, _)| instance_id)
1492 }
1493
1494 pub async fn await_primary_bitcoin_module_outputs(
1497 &self,
1498 operation_id: OperationId,
1499 outputs: Vec<OutPoint>,
1500 ) -> Result<(), TransactionSubmitError> {
1501 for out_point in outputs {
1502 self.await_primary_bitcoin_module_output(operation_id, out_point)
1503 .await?;
1504 }
1505
1506 Ok(())
1507 }
1508
1509 pub async fn get_config_json(&self) -> JsonClientConfig {
1515 self.config().await.to_json()
1516 }
1517
1518 #[doc(hidden)]
1521 pub async fn get_balance_for_btc(&self, account: Account) -> Result<Amount, ModuleLookupError> {
1524 self.get_balance_for_unit(AmountUnit::BITCOIN, account)
1525 .await
1526 }
1527
1528 pub async fn get_balance_for_unit(
1529 &self,
1530 unit: AmountUnit,
1531 account: Account,
1532 ) -> Result<Amount, ModuleLookupError> {
1533 let (id, module) = self
1534 .primary_module_for_unit(unit)
1535 .ok_or(ModuleLookupError::NoPrimaryModule { unit })?;
1536
1537 if !Self::module_supports_account(module, account) {
1538 return Ok(Amount::ZERO);
1539 }
1540 Ok(module
1541 .get_balance(
1542 id,
1543 &mut self.db().begin_transaction_nc().await,
1544 unit,
1545 account,
1546 )
1547 .await)
1548 }
1549
1550 pub async fn subscribe_balance_changes(
1553 &self,
1554 unit: AmountUnit,
1555 account: Account,
1556 ) -> BoxStream<'static, Amount> {
1557 let primary_module_things =
1558 if let Some((primary_module_id, primary_module)) = self.primary_module_for_unit(unit) {
1559 let balance_changes = primary_module.subscribe_balance_changes().await;
1560 let initial_balance = self
1561 .get_balance_for_unit(unit, account)
1562 .await
1563 .expect("Primary is present");
1564
1565 Some((
1566 primary_module_id,
1567 primary_module.clone(),
1568 balance_changes,
1569 initial_balance,
1570 ))
1571 } else {
1572 None
1573 };
1574 let db = self.db().clone();
1575
1576 Box::pin(async_stream::stream! {
1577 let Some((primary_module_id, primary_module, mut balance_changes, initial_balance)) = primary_module_things else {
1578 pending().await
1581 };
1582
1583
1584 yield initial_balance;
1585 let mut prev_balance = initial_balance;
1586 while let Some(()) = balance_changes.next().await {
1587 let mut dbtx = db.begin_transaction_nc().await;
1588 let balance = primary_module
1589 .get_balance(primary_module_id, &mut dbtx, unit, account)
1590 .await;
1591
1592 if balance != prev_balance {
1594 prev_balance = balance;
1595 yield balance;
1596 }
1597 }
1598 })
1599 }
1600
1601 async fn make_api_version_request(
1606 delay: Duration,
1607 peer_id: PeerId,
1608 api: &DynGlobalApi,
1609 ) -> (
1610 PeerId,
1611 Result<SupportedApiVersionsSummary, fedimint_connectors::error::ServerError>,
1612 ) {
1613 runtime::sleep(delay).await;
1614 (
1615 peer_id,
1616 api.request_single_peer::<SupportedApiVersionsSummary>(
1617 VERSION_ENDPOINT.to_owned(),
1618 ApiRequestErased::default(),
1619 peer_id,
1620 )
1621 .await,
1622 )
1623 }
1624
1625 fn create_api_version_backoff() -> impl Iterator<Item = Duration> {
1631 custom_backoff(Duration::from_millis(200), Duration::from_secs(600), None)
1632 }
1633
1634 pub async fn fetch_common_api_versions_from_all_peers(
1637 num_peers: NumPeers,
1638 api: DynGlobalApi,
1639 db: Database,
1640 num_responses_sender: watch::Sender<usize>,
1641 ) {
1642 let mut backoff = Self::create_api_version_backoff();
1643
1644 let mut requests = FuturesUnordered::new();
1647
1648 for peer_id in num_peers.peer_ids() {
1649 requests.push(Self::make_api_version_request(
1650 Duration::ZERO,
1651 peer_id,
1652 &api,
1653 ));
1654 }
1655
1656 let mut num_responses = 0;
1657
1658 while let Some((peer_id, response)) = requests.next().await {
1659 let retry = match response {
1660 Err(err) => {
1661 let has_previous_response = db
1662 .begin_transaction_nc()
1663 .await
1664 .get_value(&PeerLastApiVersionsSummaryKey(peer_id))
1665 .await
1666 .is_some();
1667 debug!(
1668 target: LOG_CLIENT,
1669 %peer_id,
1670 err = %err.fmt_compact(),
1671 %has_previous_response,
1672 "Failed to refresh API versions of a peer"
1673 );
1674
1675 !has_previous_response
1676 }
1677 Ok(o) => {
1678 let mut dbtx = db.begin_transaction().await;
1681 dbtx.insert_entry(
1682 &PeerLastApiVersionsSummaryKey(peer_id),
1683 &PeerLastApiVersionsSummary(o),
1684 )
1685 .await;
1686 dbtx.commit_tx().await;
1687 false
1688 }
1689 };
1690
1691 if retry {
1692 requests.push(Self::make_api_version_request(
1693 backoff.next().expect("Keeps retrying"),
1694 peer_id,
1695 &api,
1696 ));
1697 } else {
1698 num_responses += 1;
1699 num_responses_sender.send_replace(num_responses);
1700 }
1701 }
1702 }
1703
1704 pub async fn fetch_peers_api_versions_from_threshold_of_peers(
1708 num_peers: NumPeers,
1709 api: DynGlobalApi,
1710 ) -> BTreeMap<PeerId, SupportedApiVersionsSummary> {
1711 let mut backoff = Self::create_api_version_backoff();
1712
1713 let mut requests = FuturesUnordered::new();
1716
1717 for peer_id in num_peers.peer_ids() {
1718 requests.push(Self::make_api_version_request(
1719 Duration::ZERO,
1720 peer_id,
1721 &api,
1722 ));
1723 }
1724
1725 let mut successful_responses = BTreeMap::new();
1726
1727 while successful_responses.len() < num_peers.threshold()
1728 && let Some((peer_id, response)) = requests.next().await
1729 {
1730 let retry = match response {
1731 Err(err) => {
1732 debug!(
1733 target: LOG_CLIENT,
1734 %peer_id,
1735 err = %err.fmt_compact(),
1736 "Failed to fetch API versions from peer"
1737 );
1738 true
1739 }
1740 Ok(response) => {
1741 successful_responses.insert(peer_id, response);
1742 false
1743 }
1744 };
1745
1746 if retry {
1747 requests.push(Self::make_api_version_request(
1748 backoff.next().expect("Keeps retrying"),
1749 peer_id,
1750 &api,
1751 ));
1752 }
1753 }
1754
1755 successful_responses
1756 }
1757
1758 pub async fn fetch_common_api_versions(
1760 config: &ClientConfig,
1761 api: &DynGlobalApi,
1762 ) -> BTreeMap<PeerId, SupportedApiVersionsSummary> {
1763 debug!(
1764 target: LOG_CLIENT,
1765 "Fetching common api versions"
1766 );
1767
1768 let num_peers = NumPeers::from(config.global.api_endpoints.len());
1769
1770 Self::fetch_peers_api_versions_from_threshold_of_peers(num_peers, api.clone()).await
1771 }
1772
1773 pub async fn write_api_version_cache(
1777 dbtx: &mut DatabaseTransaction<'_>,
1778 api_version_set: ApiVersionSet,
1779 ) {
1780 debug!(
1781 target: LOG_CLIENT,
1782 value = ?api_version_set,
1783 "Writing API version set to cache"
1784 );
1785
1786 dbtx.insert_entry(
1787 &CachedApiVersionSetKey,
1788 &CachedApiVersionSet(api_version_set),
1789 )
1790 .await;
1791 }
1792
1793 pub async fn store_prefetched_api_versions(
1798 db: &Database,
1799 config: &ClientConfig,
1800 client_module_init: &ClientModuleInitRegistry,
1801 peer_api_versions: &BTreeMap<PeerId, SupportedApiVersionsSummary>,
1802 ) {
1803 debug!(
1804 target: LOG_CLIENT,
1805 "Storing {} prefetched peer API version responses and calculating common version set",
1806 peer_api_versions.len()
1807 );
1808
1809 let mut dbtx = db.begin_transaction().await;
1810 let client_supported_versions =
1812 Self::supported_api_versions_summary_static(config, client_module_init);
1813 match fedimint_client_module::api_version_discovery::discover_common_api_versions_set(
1814 &client_supported_versions,
1815 peer_api_versions,
1816 ) {
1817 Ok(common_api_versions) => {
1818 Self::write_api_version_cache(&mut dbtx.to_ref_nc(), common_api_versions).await;
1820 debug!(target: LOG_CLIENT, "Calculated and stored common API version set");
1821 }
1822 Err(err) => {
1823 debug!(target: LOG_CLIENT, err = %err.fmt_compact(), "Failed to calculate common API versions from prefetched data");
1824 }
1825 }
1826
1827 for (peer_id, peer_api_versions) in peer_api_versions {
1829 dbtx.insert_entry(
1830 &PeerLastApiVersionsSummaryKey(*peer_id),
1831 &PeerLastApiVersionsSummary(peer_api_versions.clone()),
1832 )
1833 .await;
1834 }
1835 dbtx.commit_tx().await;
1836 debug!(target: LOG_CLIENT, "Stored individual peer API version responses");
1837 }
1838
1839 pub fn supported_api_versions_summary_static(
1841 config: &ClientConfig,
1842 client_module_init: &ClientModuleInitRegistry,
1843 ) -> SupportedApiVersionsSummary {
1844 SupportedApiVersionsSummary {
1845 core: SupportedCoreApiVersions {
1846 core_consensus: config.global.consensus_version,
1847 api: MultiApiVersion::try_from_iter(SUPPORTED_CORE_API_VERSIONS.to_owned())
1848 .expect("must not have conflicting versions"),
1849 },
1850 modules: config
1851 .modules
1852 .iter()
1853 .filter_map(|(&module_instance_id, module_config)| {
1854 client_module_init
1855 .get(module_config.kind())
1856 .map(|module_init| {
1857 (
1858 module_instance_id,
1859 SupportedModuleApiVersions {
1860 core_consensus: config.global.consensus_version,
1861 module_consensus: module_config.version,
1862 api: module_init.supported_api_versions(),
1863 },
1864 )
1865 })
1866 })
1867 .collect(),
1868 }
1869 }
1870
1871 pub async fn load_and_refresh_common_api_version(
1872 &self,
1873 ) -> Result<ApiVersionSet, ApiVersionDiscoveryError> {
1874 Self::load_and_refresh_common_api_version_static(
1875 &self.config().await,
1876 &self.module_inits,
1877 self.connectors.clone(),
1878 &self.api,
1879 &self.db,
1880 &self.task_group,
1881 &self.client_span,
1882 )
1883 .await
1884 }
1885
1886 pub async fn refresh_api_versions(&self) -> Result<ApiVersionSet, ApiVersionDiscoveryError> {
1892 Self::refresh_common_api_version_static(
1893 &self.config().await,
1894 &self.module_inits,
1895 &self.api,
1896 &self.db,
1897 self.task_group.clone(),
1898 &self.client_span,
1899 true,
1900 )
1901 .await
1902 }
1903
1904 pub(crate) async fn load_and_refresh_common_api_version_static(
1910 config: &ClientConfig,
1911 module_init: &ClientModuleInitRegistry,
1912 connectors: ConnectorRegistry,
1913 api: &DynGlobalApi,
1914 db: &Database,
1915 task_group: &TaskGroup,
1916 client_span: &Span,
1917 ) -> Result<ApiVersionSet, ApiVersionDiscoveryError> {
1918 if let Some(v) = db
1919 .begin_transaction_nc()
1920 .await
1921 .get_value(&CachedApiVersionSetKey)
1922 .await
1923 {
1924 client_span.in_scope(|| {
1925 debug!(
1926 target: LOG_CLIENT,
1927 "Found existing cached common api versions"
1928 );
1929 });
1930 let config = config.clone();
1931 let client_module_init = module_init.clone();
1932 let api = api.clone();
1933 let db = db.clone();
1934 let task_group = task_group.clone();
1935 let client_span_owned = client_span.clone();
1936 task_group.clone().spawn_cancellable_with_span(
1939 client_span.clone(),
1940 "refresh_common_api_version_static",
1941 async move {
1942 connectors.wait_for_initialized_connections().await;
1943
1944 if let Err(error) = Self::refresh_common_api_version_static(
1945 &config,
1946 &client_module_init,
1947 &api,
1948 &db,
1949 task_group,
1950 &client_span_owned,
1951 false,
1952 )
1953 .await
1954 {
1955 warn!(
1956 target: LOG_CLIENT,
1957 err = %error.fmt_compact(), "Failed to discover common api versions"
1958 );
1959 }
1960 },
1961 );
1962
1963 return Ok(v.0);
1964 }
1965
1966 info!(
1967 target: LOG_CLIENT,
1968 "Fetching initial API versions "
1969 );
1970 Self::refresh_common_api_version_static(
1971 config,
1972 module_init,
1973 api,
1974 db,
1975 task_group.clone(),
1976 client_span,
1977 true,
1978 )
1979 .await
1980 }
1981
1982 async fn refresh_common_api_version_static(
1983 config: &ClientConfig,
1984 client_module_init: &ClientModuleInitRegistry,
1985 api: &DynGlobalApi,
1986 db: &Database,
1987 task_group: TaskGroup,
1988 client_span: &Span,
1989 block_until_ok: bool,
1990 ) -> Result<ApiVersionSet, ApiVersionDiscoveryError> {
1991 debug!(
1992 target: LOG_CLIENT,
1993 "Refreshing common api versions"
1994 );
1995
1996 let (num_responses_sender, mut num_responses_receiver) = tokio::sync::watch::channel(0);
1997 let num_peers = NumPeers::from(config.global.api_endpoints.len());
1998
1999 task_group.spawn_cancellable_with_span(
2000 client_span.clone(),
2001 "refresh peers api versions",
2002 Client::fetch_common_api_versions_from_all_peers(
2003 num_peers,
2004 api.clone(),
2005 db.clone(),
2006 num_responses_sender,
2007 ),
2008 );
2009
2010 let common_api_versions = loop {
2011 let _: Result<_, Elapsed> = runtime::timeout(
2019 Duration::from_secs(30),
2020 num_responses_receiver.wait_for(|num| num_peers.threshold() <= *num),
2021 )
2022 .await;
2023
2024 let peer_api_version_sets = Self::load_peers_last_api_versions(db, num_peers).await;
2025
2026 match fedimint_client_module::api_version_discovery::discover_common_api_versions_set(
2027 &Self::supported_api_versions_summary_static(config, client_module_init),
2028 &peer_api_version_sets,
2029 ) {
2030 Ok(o) => break o,
2031 Err(err) if block_until_ok => {
2032 warn!(
2033 target: LOG_CLIENT,
2034 err = %err.fmt_compact(),
2035 "Failed to discover API version to use. Retrying..."
2036 );
2037 continue;
2038 }
2039 Err(e) => return Err(e),
2040 }
2041 };
2042
2043 debug!(
2044 target: LOG_CLIENT,
2045 value = ?common_api_versions,
2046 "Updating the cached common api versions"
2047 );
2048 let mut dbtx = db.begin_transaction().await;
2049 let _ = dbtx
2050 .insert_entry(
2051 &CachedApiVersionSetKey,
2052 &CachedApiVersionSet(common_api_versions.clone()),
2053 )
2054 .await;
2055
2056 dbtx.commit_tx().await;
2057
2058 Ok(common_api_versions)
2059 }
2060
2061 pub async fn get_metadata(&self) -> Metadata {
2063 self.db
2064 .begin_transaction_nc()
2065 .await
2066 .get_value(&ClientMetadataKey)
2067 .await
2068 .unwrap_or_else(|| {
2069 warn!(
2070 target: LOG_CLIENT,
2071 "Missing existing metadata. This key should have been set on Client init"
2072 );
2073 Metadata::empty()
2074 })
2075 }
2076
2077 pub async fn set_metadata(&self, metadata: &Metadata) {
2079 self.db
2080 .autocommit::<_, _, Infallible>(
2081 |dbtx, _| {
2082 Box::pin(async {
2083 Self::set_metadata_dbtx(dbtx, metadata).await;
2084 Ok(())
2085 })
2086 },
2087 None,
2088 )
2089 .await
2090 .expect("Failed to autocommit metadata");
2091 }
2092
2093 pub fn has_pending_recoveries(&self) -> bool {
2094 !self
2095 .client_recovery_status_receiver
2096 .borrow()
2097 .values()
2098 .all(RecoveryStatus::is_successfully_done)
2099 }
2100
2101 pub fn all_modules_usable(&self) -> bool {
2112 self.client_recovery_status_receiver
2113 .borrow()
2114 .keys()
2115 .all(|module_instance_id| self.modules.get(*module_instance_id).is_some())
2116 }
2117
2118 pub async fn wait_for_all_recoveries(&self) -> Result<(), RecoveryError> {
2132 Self::wait_for_recoveries(
2133 self.client_recovery_status_receiver.clone(),
2134 |_module_instance_id| true,
2135 )
2136 .await
2137 }
2138
2139 async fn wait_for_recoveries(
2148 mut status_receiver: watch::Receiver<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
2149 module_filter: impl Fn(ModuleInstanceId) -> bool,
2150 ) -> Result<(), RecoveryError> {
2151 let failure = status_receiver
2152 .wait_for(|statuses| {
2153 let matching = || {
2154 statuses
2155 .iter()
2156 .filter(|(module_instance_id, _status)| module_filter(**module_instance_id))
2157 .map(|(_module_instance_id, status)| status)
2158 };
2159
2160 matching().any(|status| matches!(status, RecoveryStatus::Failed { .. }))
2164 || matching().all(RecoveryStatus::is_successfully_done)
2165 })
2166 .await
2167 .map_err(|_closed| RecoveryError::ClientStopped)?
2168 .iter()
2171 .find_map(|(module_instance_id, status)| match status {
2172 RecoveryStatus::Failed { error, .. } if module_filter(*module_instance_id) => {
2173 Some((*module_instance_id, error.clone()))
2174 }
2175 _ => None,
2176 });
2177
2178 match failure {
2179 Some((module_instance_id, source)) => Err(RecoveryError::Failed {
2180 module_instance_id,
2181 source,
2182 }),
2183 None => Ok(()),
2184 }
2185 }
2186
2187 pub fn subscribe_to_recovery_progress(
2197 &self,
2198 ) -> impl Stream<Item = (ModuleInstanceId, RecoveryProgress)> + use<> {
2199 WatchStream::new(self.client_recovery_status_receiver.clone()).flat_map(|statuses| {
2200 futures::stream::iter(
2201 statuses
2202 .into_iter()
2203 .map(|(module_instance_id, status)| (module_instance_id, status.progress())),
2204 )
2205 })
2206 }
2207
2208 pub async fn wait_for_module_kind_recovery(
2217 &self,
2218 module_kind: ModuleKind,
2219 ) -> Result<(), RecoveryError> {
2220 let config = self.config().await;
2221 Self::wait_for_recoveries(
2222 self.client_recovery_status_receiver.clone(),
2223 move |module_instance_id| {
2224 config
2225 .modules
2226 .get(&module_instance_id)
2227 .is_some_and(|module| module.kind == module_kind)
2228 },
2229 )
2230 .await
2231 }
2232
2233 pub async fn wait_for_all_active_state_machines(&self) {
2234 loop {
2235 if self.executor.get_active_states().await.is_empty() {
2236 break;
2237 }
2238 sleep(Duration::from_millis(100)).await;
2239 }
2240 }
2241
2242 pub async fn set_metadata_dbtx(dbtx: &mut DatabaseTransaction<'_>, metadata: &Metadata) {
2244 dbtx.insert_new_entry(&ClientMetadataKey, metadata).await;
2245 }
2246
2247 fn spawn_module_recoveries_task(
2248 &self,
2249 recovery_sender: watch::Sender<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
2250 module_recoveries: BTreeMap<ModuleInstanceId, ModuleRecoveryFuture>,
2251 module_recovery_progress_receivers: BTreeMap<
2252 ModuleInstanceId,
2253 watch::Receiver<RecoveryProgress>,
2254 >,
2255 module_kinds: BTreeMap<ModuleInstanceId, ModuleKind>,
2258 ) {
2259 let db = self.db.clone();
2260 let log_ordering_wakeup_tx = self.log_ordering_wakeup_tx.clone();
2261 self.spawn("module recoveries", |_task_handle| async {
2266 Self::run_module_recoveries_task(
2267 db,
2268 log_ordering_wakeup_tx,
2269 recovery_sender,
2270 module_recoveries,
2271 module_recovery_progress_receivers,
2272 module_kinds,
2273 )
2274 .await;
2275 });
2276 }
2277
2278 async fn run_module_recoveries_task(
2279 db: Database,
2280 log_ordering_wakeup_tx: watch::Sender<()>,
2281 recovery_sender: watch::Sender<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
2282 module_recoveries: BTreeMap<ModuleInstanceId, ModuleRecoveryFuture>,
2283 module_recovery_progress_receivers: BTreeMap<
2284 ModuleInstanceId,
2285 watch::Receiver<RecoveryProgress>,
2286 >,
2287 module_kinds: BTreeMap<ModuleInstanceId, ModuleKind>,
2288 ) {
2289 debug!(target: LOG_CLIENT_RECOVERY, num_modules=%module_recovery_progress_receivers.len(), "Staring module recoveries");
2290
2291 enum RecoveryUpdate {
2295 Progress(RecoveryProgress),
2296 Completed(Option<Amount>),
2297 }
2298
2299 let mut completed_stream = Vec::new();
2300 let progress_stream = futures::stream::FuturesUnordered::new();
2301
2302 for (module_instance_id, f) in module_recoveries {
2303 let recovery_sender = recovery_sender.clone();
2304 completed_stream.push(futures::stream::once(Box::pin(async move {
2305 match f.await {
2306 Ok(amount) => (module_instance_id, RecoveryUpdate::Completed(amount)),
2307 Err(err) => {
2308 warn!(
2309 target: LOG_CLIENT,
2310 err = %err.fmt_compact(), module_instance_id, "Module recovery failed"
2311 );
2312 let error = Arc::new(err);
2313 recovery_sender.send_modify(|statuses| {
2320 let last_progress = statuses
2321 .get(&module_instance_id)
2322 .expect("existing status must be present")
2323 .progress();
2324 statuses.insert(
2325 module_instance_id,
2326 RecoveryStatus::Failed {
2327 last_progress,
2328 error,
2329 },
2330 );
2331 });
2332 futures::future::pending::<()>().await;
2342 unreachable!()
2343 }
2344 }
2345 })));
2346 }
2347
2348 for (module_instance_id, rx) in module_recovery_progress_receivers {
2349 progress_stream.push(
2350 tokio_stream::wrappers::WatchStream::new(rx)
2351 .fuse()
2352 .map(move |progress| (module_instance_id, RecoveryUpdate::Progress(progress))),
2353 );
2354 }
2355
2356 let mut futures = futures::stream::select(
2357 futures::stream::select_all(progress_stream),
2358 futures::stream::select_all(completed_stream),
2359 );
2360
2361 while let Some((module_instance_id, update)) = futures.next().await {
2362 let prev_status = recovery_sender
2366 .borrow()
2367 .get(&module_instance_id)
2368 .expect("existing status must be present")
2369 .clone();
2370
2371 if matches!(prev_status, RecoveryStatus::Failed { .. }) {
2381 debug!(
2382 target: LOG_CLIENT_RECOVERY,
2383 module_instance_id,
2384 "Ignoring a recovery update of a module whose recovery already failed"
2385 );
2386 continue;
2387 }
2388
2389 let prev_progress = prev_status.progress();
2390
2391 if let RecoveryUpdate::Progress(progress) = &update {
2397 if progress.is_done() {
2398 warn!(
2399 target: LOG_CLIENT_RECOVERY,
2400 module_instance_id,
2401 "Module bypassed the sanctioned recovery progress reporting API and reported a completed recovery progress. Ignoring"
2402 );
2403 continue;
2404 }
2405
2406 if progress.is_none() && !prev_progress.is_none() && !prev_progress.is_done() {
2413 warn!(
2414 target: LOG_CLIENT_RECOVERY,
2415 module_instance_id,
2416 "Module bypassed the sanctioned recovery progress reporting API and reported a none recovery progress, regressing its previous one. Ignoring"
2417 );
2418 continue;
2419 }
2420 }
2421
2422 let mut dbtx = db.begin_transaction().await;
2423
2424 let (progress, recovered_amount) = if prev_progress.is_done() {
2430 (prev_progress, None)
2432 } else {
2433 match update {
2434 RecoveryUpdate::Progress(progress) => (progress, None),
2435 RecoveryUpdate::Completed(amount) => (prev_progress.to_complete(), amount),
2436 }
2437 };
2438
2439 if !prev_progress.is_done() && progress.is_done() {
2440 info!(
2441 target: LOG_CLIENT,
2442 module_instance_id,
2443 progress = format!("{}/{}", progress.complete, progress.total),
2444 amount = ?recovered_amount,
2445 "Recovery complete"
2446 );
2447 dbtx.log_event(
2448 log_ordering_wakeup_tx.clone(),
2449 None,
2450 ModuleRecoveryCompleted {
2451 module_id: module_instance_id,
2452 kind: module_kinds.get(&module_instance_id).cloned(),
2453 amount: recovered_amount,
2454 },
2455 )
2456 .await;
2457 } else {
2458 info!(
2459 target: LOG_CLIENT,
2460 module_instance_id,
2461 kind = ?module_kinds.get(&module_instance_id),
2462 progress = format!("{}/{}", progress.complete, progress.total),
2463 "Recovery progress"
2464 );
2465 }
2466
2467 dbtx.insert_entry(
2468 &ClientModuleRecovery { module_instance_id },
2469 &ClientModuleRecoveryState { progress },
2470 )
2471 .await;
2472 dbtx.commit_tx().await;
2473
2474 recovery_sender.send_modify(|statuses| {
2475 statuses.insert(module_instance_id, RecoveryStatus::InProgress(progress));
2476 });
2477 }
2478 debug!(target: LOG_CLIENT_RECOVERY, "Recovery executor stopped");
2479 }
2480
2481 async fn load_peers_last_api_versions(
2482 db: &Database,
2483 num_peers: NumPeers,
2484 ) -> BTreeMap<PeerId, SupportedApiVersionsSummary> {
2485 let mut peer_api_version_sets = BTreeMap::new();
2486
2487 let mut dbtx = db.begin_transaction_nc().await;
2488 for peer_id in num_peers.peer_ids() {
2489 if let Some(v) = dbtx
2490 .get_value(&PeerLastApiVersionsSummaryKey(peer_id))
2491 .await
2492 {
2493 peer_api_version_sets.insert(peer_id, v.0);
2494 }
2495 }
2496 drop(dbtx);
2497 peer_api_version_sets
2498 }
2499
2500 pub async fn get_peer_url_announcements(&self) -> BTreeMap<PeerId, SignedApiAnnouncement> {
2503 self.db()
2504 .begin_transaction_nc()
2505 .await
2506 .find_by_prefix(&ApiAnnouncementPrefix)
2507 .await
2508 .map(|(announcement_key, announcement)| (announcement_key.0, announcement))
2509 .collect()
2510 .await
2511 }
2512
2513 pub async fn get_guardian_metadata(
2515 &self,
2516 ) -> BTreeMap<PeerId, fedimint_core::net::guardian_metadata::SignedGuardianMetadata> {
2517 self.db()
2518 .begin_transaction_nc()
2519 .await
2520 .find_by_prefix(&crate::guardian_metadata::GuardianMetadataPrefix)
2521 .await
2522 .map(|(key, metadata)| (key.0, metadata))
2523 .collect()
2524 .await
2525 }
2526
2527 pub async fn peer_availability(&self) -> MergedPeerAvailability {
2531 let reports =
2532 futures::future::join_all(self.api.all_peers().iter().map(|peer| async move {
2533 let report =
2534 runtime::timeout(Duration::from_secs(10), self.api.peer_availability(*peer))
2535 .await;
2536 (*peer, report)
2537 }))
2538 .await
2539 .into_iter()
2540 .filter_map(|(peer, report)| Some((peer, report.ok()?.ok()?)))
2541 .collect();
2542
2543 merge_peer_availability(
2544 &reports,
2545 fedimint_core::NumPeersExt::to_num_peers(self.api.all_peers()),
2546 )
2547 }
2548
2549 pub async fn get_peer_urls(&self) -> BTreeMap<PeerId, SafeUrl> {
2551 get_api_urls(&self.db, &self.config().await, self.iroh_enable_next).await
2552 }
2553
2554 pub async fn invite_code(&self, peer: PeerId) -> Option<InviteCode> {
2557 self.get_peer_urls()
2558 .await
2559 .into_iter()
2560 .find_map(|(peer_id, url)| (peer == peer_id).then_some(url))
2561 .map(|peer_url| {
2562 InviteCode::new(
2563 peer_url.clone(),
2564 peer,
2565 self.federation_id(),
2566 self.api_secret.clone(),
2567 )
2568 })
2569 }
2570
2571 pub async fn get_guardian_public_keys_blocking(
2575 &self,
2576 ) -> BTreeMap<PeerId, fedimint_core::secp256k1::PublicKey> {
2577 self.db
2578 .autocommit(
2579 |dbtx, _| {
2580 Box::pin(async move {
2581 let config = self.config().await;
2582
2583 let guardian_pub_keys = self
2584 .get_or_backfill_broadcast_public_keys(dbtx, config)
2585 .await;
2586
2587 Result::<_, ()>::Ok(guardian_pub_keys)
2588 })
2589 },
2590 None,
2591 )
2592 .await
2593 .expect("Will retry forever")
2594 }
2595
2596 async fn get_or_backfill_broadcast_public_keys(
2597 &self,
2598 dbtx: &mut DatabaseTransaction<'_>,
2599 config: ClientConfig,
2600 ) -> BTreeMap<PeerId, PublicKey> {
2601 match config.global.broadcast_public_keys {
2602 Some(guardian_pub_keys) => guardian_pub_keys,
2603 _ => {
2604 let (guardian_pub_keys, new_config) = self.fetch_and_update_config(config).await;
2605
2606 dbtx.insert_entry(&ClientConfigKey, &new_config).await;
2607 *(self.config.write().await) = new_config;
2608 guardian_pub_keys
2609 }
2610 }
2611 }
2612
2613 pub async fn fetch_session_count(&self) -> FederationResult<u64> {
2614 self.api.session_count().await
2615 }
2616
2617 async fn fetch_and_update_config(
2618 &self,
2619 config: ClientConfig,
2620 ) -> (BTreeMap<PeerId, PublicKey>, ClientConfig) {
2621 let fetched_config = retry(
2622 "Fetching guardian public keys",
2623 backoff_util::background_backoff(),
2624 || async {
2625 self.api
2626 .request_current_consensus::<ClientConfig>(
2627 CLIENT_CONFIG_ENDPOINT.to_owned(),
2628 ApiRequestErased::default(),
2629 )
2630 .await
2631 },
2632 )
2633 .await
2634 .expect("Will never return on error");
2635
2636 let Some(guardian_pub_keys) = fetched_config.global.broadcast_public_keys else {
2637 warn!(
2638 target: LOG_CLIENT,
2639 "Guardian public keys not found in fetched config, server not updated to 0.4 yet"
2640 );
2641 pending::<()>().await;
2642 unreachable!("Pending will never return");
2643 };
2644
2645 let new_config = ClientConfig {
2646 global: GlobalClientConfig {
2647 broadcast_public_keys: Some(guardian_pub_keys.clone()),
2648 ..config.global
2649 },
2650 modules: config.modules,
2651 };
2652 (guardian_pub_keys, new_config)
2653 }
2654
2655 pub fn handle_global_rpc(
2662 &self,
2663 method: String,
2664 params: serde_json::Value,
2665 ) -> BoxStream<'_, Result<serde_json::Value, GlobalRpcError>> {
2666 Box::pin(try_stream! {
2667 match method.as_str() {
2668 "get_balance" => {
2669 let req: BalanceRequest = if params.is_null() {
2671 BalanceRequest::default()
2672 } else {
2673 serde_json::from_value(params)?
2674 };
2675 let balance = self
2676 .get_balance_for_unit(req.unit, req.account)
2677 .await
2678 .unwrap_or_default();
2679 yield serde_json::to_value(balance)?;
2680 }
2681 "subscribe_balance_changes" => {
2682 let req: BalanceRequest = serde_json::from_value(params)?;
2683 let mut stream = self.subscribe_balance_changes(req.unit, req.account).await;
2684 while let Some(balance) = stream.next().await {
2685 yield serde_json::to_value(balance)?;
2686 }
2687 }
2688 "get_config" => {
2689 let config = self.config().await;
2690 yield serde_json::to_value(config)?;
2691 }
2692 "get_federation_id" => {
2693 let federation_id = self.federation_id();
2694 yield serde_json::to_value(federation_id)?;
2695 }
2696 "get_invite_code" => {
2697 let req: GetInviteCodeRequest = serde_json::from_value(params)?;
2698 let invite_code = self.invite_code(req.peer).await;
2699 yield serde_json::to_value(invite_code)?;
2700 }
2701 "get_operation" => {
2702 let req: GetOperationIdRequest = serde_json::from_value(params)?;
2703 let operation = self.operation_log().get_operation(req.operation_id).await;
2704 yield serde_json::to_value(operation)?;
2705 }
2706 "list_operations" => {
2707 let req: ListOperationsParams = serde_json::from_value(params)?;
2708 let limit = if req.limit.is_none() && req.last_seen.is_none() {
2709 usize::MAX
2710 } else {
2711 req.limit.unwrap_or(usize::MAX)
2712 };
2713 let operations = self.operation_log()
2714 .paginate_operations_rev(limit, req.last_seen)
2715 .await;
2716 yield serde_json::to_value(operations)?;
2717 }
2718 "get_event_log" => {
2719 let req: GetEventLogRequest = serde_json::from_value(params)?;
2720 let limit = req
2721 .limit
2722 .unwrap_or(DEFAULT_EVENT_LOG_PAGE_SIZE)
2723 .min(MAX_EVENT_LOG_PAGE_SIZE);
2724 let events = self.get_event_log(req.pos, limit).await;
2725 yield serde_json::to_value(events)?;
2726 }
2727 "session_count" => {
2728 let count = self.fetch_session_count().await?;
2729 yield serde_json::to_value(count)?;
2730 }
2731 "has_pending_recoveries" => {
2732 let has_pending = self.has_pending_recoveries();
2733 yield serde_json::to_value(has_pending)?;
2734 }
2735 "wait_for_all_recoveries" => {
2736 self.wait_for_all_recoveries().await?;
2737 yield serde_json::Value::Null;
2738 }
2739 "subscribe_to_recovery_progress" => {
2740 let mut stream = self.subscribe_to_recovery_progress();
2741 while let Some((module_id, progress)) = stream.next().await {
2742 yield serde_json::json!({
2743 "module_id": module_id,
2744 "progress": progress
2745 });
2746 }
2747 }
2748 #[allow(deprecated)]
2749 "backup_to_federation" => {
2750 let metadata = if params.is_null() {
2751 Metadata::from_json_serialized(serde_json::json!({}))
2752 } else {
2753 Metadata::from_json_serialized(params)
2754 };
2755 self.backup_to_federation(metadata).await?;
2756 yield serde_json::Value::Null;
2757 }
2758 _ => {
2759 Err(GlobalRpcError::UnknownMethod { method: method.clone() })?;
2760 unreachable!()
2761 },
2762 }
2763 })
2764 }
2765
2766 pub async fn log_event<E>(&self, module_id: Option<ModuleInstanceId>, event: E)
2767 where
2768 E: Event + Send,
2769 {
2770 let mut dbtx = self.db.begin_transaction().await;
2771 self.log_event_dbtx(&mut dbtx, module_id, event).await;
2772 dbtx.commit_tx().await;
2773 }
2774
2775 pub async fn log_event_dbtx<E, Cap>(
2776 &self,
2777 dbtx: &mut DatabaseTransaction<'_, Cap>,
2778 module_id: Option<ModuleInstanceId>,
2779 event: E,
2780 ) where
2781 E: Event + Send,
2782 Cap: Send,
2783 {
2784 dbtx.log_event(self.log_ordering_wakeup_tx.clone(), module_id, event)
2785 .await;
2786 }
2787
2788 pub async fn log_event_raw_dbtx<Cap>(
2789 &self,
2790 dbtx: &mut DatabaseTransaction<'_, Cap>,
2791 kind: EventKind,
2792 module: Option<(ModuleKind, ModuleInstanceId)>,
2793 payload: Vec<u8>,
2794 persist: EventPersistence,
2795 ) where
2796 Cap: Send,
2797 {
2798 let module_id = module.as_ref().map(|m| m.1);
2799 let module_kind = module.map(|m| m.0);
2800 dbtx.log_event_raw(
2801 self.log_ordering_wakeup_tx.clone(),
2802 kind,
2803 module_kind,
2804 module_id,
2805 payload,
2806 persist,
2807 )
2808 .await;
2809 }
2810
2811 pub fn built_in_application_event_log_tracker(&self) -> DynEventLogTrimableTracker {
2823 struct BuiltInApplicationEventLogTracker;
2824
2825 #[apply(async_trait_maybe_send!)]
2826 impl EventLogTrimableTracker for BuiltInApplicationEventLogTracker {
2827 async fn store(
2829 &mut self,
2830 dbtx: &mut DatabaseTransaction<NonCommittable>,
2831 pos: EventLogTrimableId,
2832 ) -> Result<(), EventLogTrackerError> {
2833 dbtx.insert_entry(&DefaultApplicationEventLogKey, &pos)
2834 .await;
2835 Ok(())
2836 }
2837
2838 async fn load(
2840 &mut self,
2841 dbtx: &mut DatabaseTransaction<NonCommittable>,
2842 ) -> Result<Option<EventLogTrimableId>, EventLogTrackerError> {
2843 Ok(dbtx.get_value(&DefaultApplicationEventLogKey).await)
2844 }
2845 }
2846 Box::new(BuiltInApplicationEventLogTracker)
2847 }
2848
2849 pub async fn handle_historical_events<F, R, E>(
2857 &self,
2858 tracker: fedimint_eventlog::DynEventLogTracker,
2859 handler_fn: F,
2860 ) -> Result<(), EventHandlerError<E>>
2861 where
2862 F: Fn(&mut DatabaseTransaction<NonCommittable>, EventLogEntry) -> R,
2863 R: Future<Output = Result<(), E>>,
2864 E: std::error::Error + 'static,
2865 {
2866 fedimint_eventlog::handle_events(
2867 self.db.clone(),
2868 tracker,
2869 self.log_event_added_rx.clone(),
2870 handler_fn,
2871 )
2872 .await
2873 }
2874
2875 pub async fn handle_events<F, R, E>(
2894 &self,
2895 tracker: fedimint_eventlog::DynEventLogTrimableTracker,
2896 handler_fn: F,
2897 ) -> Result<(), EventHandlerError<E>>
2898 where
2899 F: Fn(&mut DatabaseTransaction<NonCommittable>, EventLogEntry) -> R,
2900 R: Future<Output = Result<(), E>>,
2901 E: std::error::Error + 'static,
2902 {
2903 fedimint_eventlog::handle_trimable_events(
2904 self.db.clone(),
2905 tracker,
2906 self.log_event_added_rx.clone(),
2907 handler_fn,
2908 )
2909 .await
2910 }
2911
2912 pub async fn get_event_log(
2913 &self,
2914 pos: Option<EventLogId>,
2915 limit: u64,
2916 ) -> Vec<PersistedLogEntry> {
2917 self.get_event_log_dbtx(&mut self.db.begin_transaction_nc().await, pos, limit)
2918 .await
2919 }
2920
2921 pub async fn get_next_event_log_id(&self) -> EventLogId {
2924 self.db
2925 .begin_transaction_nc()
2926 .await
2927 .get_next_event_log_id()
2928 .await
2929 }
2930
2931 pub async fn get_event_log_trimable(
2932 &self,
2933 pos: Option<EventLogTrimableId>,
2934 limit: u64,
2935 ) -> Vec<PersistedLogEntry> {
2936 self.get_event_log_trimable_dbtx(&mut self.db.begin_transaction_nc().await, pos, limit)
2937 .await
2938 }
2939
2940 pub async fn get_event_log_dbtx<Cap>(
2941 &self,
2942 dbtx: &mut DatabaseTransaction<'_, Cap>,
2943 pos: Option<EventLogId>,
2944 limit: u64,
2945 ) -> Vec<PersistedLogEntry>
2946 where
2947 Cap: Send,
2948 {
2949 dbtx.get_event_log(pos, limit).await
2950 }
2951
2952 pub async fn get_event_log_trimable_dbtx<Cap>(
2953 &self,
2954 dbtx: &mut DatabaseTransaction<'_, Cap>,
2955 pos: Option<EventLogTrimableId>,
2956 limit: u64,
2957 ) -> Vec<PersistedLogEntry>
2958 where
2959 Cap: Send,
2960 {
2961 dbtx.get_event_log_trimable(pos, limit).await
2962 }
2963
2964 pub fn get_event_log_transient_receiver(&self) -> broadcast::Receiver<EventLogEntry> {
2966 self.log_event_added_transient_tx.subscribe()
2967 }
2968
2969 pub fn log_event_added_rx(&self) -> watch::Receiver<()> {
2971 self.log_event_added_rx.clone()
2972 }
2973
2974 pub fn iroh_enable_dht(&self) -> bool {
2975 self.iroh_enable_dht
2976 }
2977
2978 pub fn iroh_enable_next(&self) -> bool {
2981 self.iroh_enable_next
2982 }
2983
2984 pub(crate) async fn run_core_migrations(
2985 db_no_decoders: &Database,
2986 ) -> Result<(), DbMigrationError> {
2987 let mut dbtx = db_no_decoders.begin_transaction().await;
2988 apply_migrations_core_client_dbtx(&mut dbtx.to_ref_nc(), "fedimint-client".to_string())
2989 .await?;
2990 if is_running_in_test_env!() {
2991 verify_client_db_integrity_dbtx(&mut dbtx.to_ref_nc()).await;
2992 }
2993 dbtx.commit_tx_result().await?;
2994 Ok(())
2995 }
2996
2997 fn primary_modules_for_unit(
2999 &self,
3000 unit: AmountUnit,
3001 ) -> impl Iterator<Item = (ModuleInstanceId, &DynClientModule)> {
3002 self.primary_modules
3003 .iter()
3004 .flat_map(move |(_prio, candidates)| {
3005 candidates
3006 .specific
3007 .get(&unit)
3008 .into_iter()
3009 .flatten()
3010 .copied()
3011 .chain(candidates.wildcard.iter().copied())
3013 })
3014 .map(|id| (id, self.modules.get_expect(id)))
3015 }
3016
3017 pub fn primary_module_for_unit(
3021 &self,
3022 unit: AmountUnit,
3023 ) -> Option<(ModuleInstanceId, &DynClientModule)> {
3024 self.primary_modules_for_unit(unit).next()
3025 }
3026
3027 pub fn supports_account(&self, unit: AmountUnit, account: Account) -> bool {
3035 self.primary_module_for_unit(unit)
3036 .is_some_and(|(_, module)| Self::module_supports_account(module, account))
3037 }
3038
3039 fn module_supports_account(module: &DynClientModule, account: Account) -> bool {
3040 match module.supports_being_primary() {
3041 PrimaryModuleSupport::Any { accounts, .. }
3042 | PrimaryModuleSupport::Selected { accounts, .. } => accounts.supports(account),
3043 PrimaryModuleSupport::None => {
3044 unreachable!("a module selected as primary advertises primary support")
3045 }
3046 }
3047 }
3048
3049 pub fn primary_module_for_btc(&self) -> (ModuleInstanceId, &DynClientModule) {
3051 self.primary_module_for_unit(AmountUnit::BITCOIN)
3052 .expect("No primary module for Bitcoin")
3053 }
3054
3055 pub fn get_primary_module_for_unit<M: ClientModule>(
3068 &self,
3069 unit: AmountUnit,
3070 ) -> Result<&M, ModuleLookupError> {
3071 let mut modules = self.primary_modules_for_unit(unit).peekable();
3072 if modules.peek().is_none() {
3073 return Err(ModuleLookupError::NoPrimaryModule { unit });
3074 }
3075 modules
3076 .find_map(|(_, module)| module.as_any().downcast_ref::<M>())
3077 .ok_or_else(|| ModuleLookupError::NoPrimaryModuleOfKind {
3078 kind: M::kind(),
3079 unit,
3080 })
3081 }
3082}
3083
3084#[apply(async_trait_maybe_send!)]
3085impl ClientContextIface for Client {
3086 fn get_module(&self, instance: ModuleInstanceId) -> &maybe_add_send_sync!(dyn IClientModule) {
3087 Client::get_module(self, instance)
3088 }
3089
3090 fn api_clone(&self) -> DynGlobalApi {
3091 Client::api_clone(self)
3092 }
3093 fn decoders(&self) -> &ModuleDecoderRegistry {
3094 Client::decoders(self)
3095 }
3096
3097 async fn finalize_and_submit_transaction(
3098 &self,
3099 operation_id: OperationId,
3100 operation_type: &str,
3101 operation_meta_gen: Box<maybe_add_send_sync!(dyn Fn(OutPointRange) -> serde_json::Value)>,
3102 tx_builder: TransactionBuilder,
3103 ) -> Result<OutPointRange, TransactionSubmitError> {
3104 Client::finalize_and_submit_transaction(
3105 self,
3106 operation_id,
3107 operation_type,
3108 &operation_meta_gen,
3110 tx_builder,
3111 )
3112 .await
3113 }
3114
3115 async fn finalize_and_submit_transaction_dbtx(
3116 &self,
3117 dbtx: &mut DatabaseTransaction<'_>,
3118 operation_id: OperationId,
3119 operation_type: &str,
3120 operation_meta_gen: Box<maybe_add_send_sync!(dyn Fn(OutPointRange) -> serde_json::Value)>,
3121 tx_builder: TransactionBuilder,
3122 ) -> Result<OutPointRange, TransactionSubmitError> {
3123 Client::finalize_and_submit_transaction_dbtx(
3124 self,
3125 dbtx,
3126 operation_id,
3127 operation_type,
3128 &operation_meta_gen,
3129 tx_builder,
3130 )
3131 .await
3132 }
3133
3134 async fn finalize_and_submit_transaction_inner(
3135 &self,
3136 dbtx: &mut DatabaseTransaction<'_>,
3137 operation_id: OperationId,
3138 tx_builder: TransactionBuilder,
3139 ) -> Result<OutPointRange, TransactionSubmitError> {
3140 Client::finalize_and_submit_transaction_inner(self, dbtx, operation_id, tx_builder).await
3141 }
3142
3143 async fn fee_quote(
3144 &self,
3145 operation_id: OperationId,
3146 request: FeeQuoteRequest,
3147 ) -> Result<FeeQuote, TransactionSubmitError> {
3148 Client::fee_quote(self, operation_id, request).await
3149 }
3150
3151 async fn get_balance_for_unit(
3152 &self,
3153 unit: AmountUnit,
3154 account: Account,
3155 ) -> Result<Amount, ModuleLookupError> {
3156 Client::get_balance_for_unit(self, unit, account).await
3157 }
3158
3159 fn supports_account(&self, unit: AmountUnit, account: Account) -> bool {
3160 Client::supports_account(self, unit, account)
3161 }
3162
3163 async fn operation_account_dbtx(
3164 &self,
3165 dbtx: &mut DatabaseTransaction<'_>,
3166 operation_id: OperationId,
3167 ) -> Account {
3168 Client::operation_account_dbtx(dbtx, operation_id).await
3169 }
3170
3171 async fn set_operation_account_dbtx(
3172 &self,
3173 dbtx: &mut DatabaseTransaction<'_>,
3174 operation_id: OperationId,
3175 account: Account,
3176 ) {
3177 Client::set_operation_account_dbtx(dbtx, operation_id, account).await;
3178 }
3179
3180 async fn transaction_updates(&self, operation_id: OperationId) -> TransactionUpdates {
3181 Client::transaction_updates(self, operation_id).await
3182 }
3183
3184 async fn await_primary_module_outputs(
3185 &self,
3186 operation_id: OperationId,
3187 outputs: Vec<OutPoint>,
3189 ) -> Result<(), TransactionSubmitError> {
3190 Client::await_primary_bitcoin_module_outputs(self, operation_id, outputs).await
3191 }
3192
3193 fn operation_log(&self) -> &dyn IOperationLog {
3194 Client::operation_log(self)
3195 }
3196
3197 async fn has_active_states(&self, operation_id: OperationId) -> bool {
3198 Client::has_active_states(self, operation_id).await
3199 }
3200
3201 async fn await_no_active_states(&self, operation_id: OperationId) {
3202 Client::await_no_active_states(self, operation_id).await;
3203 }
3204
3205 async fn operation_exists(&self, operation_id: OperationId) -> bool {
3206 Client::operation_exists(self, operation_id).await
3207 }
3208
3209 async fn config(&self) -> ClientConfig {
3210 Client::config(self).await
3211 }
3212
3213 fn db(&self) -> &Database {
3214 Client::db(self)
3215 }
3216
3217 fn executor(&self) -> &(maybe_add_send_sync!(dyn IExecutor + 'static)) {
3218 Client::executor(self)
3219 }
3220
3221 async fn invite_code(&self, peer: PeerId) -> Option<InviteCode> {
3222 Client::invite_code(self, peer).await
3223 }
3224
3225 fn get_internal_payment_markers(&self) -> Result<(PublicKey, u64), bitcoin::secp256k1::Error> {
3226 Client::get_internal_payment_markers(self)
3227 }
3228
3229 async fn log_event_json(
3230 &self,
3231 dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
3232 module_kind: Option<ModuleKind>,
3233 module_id: ModuleInstanceId,
3234 kind: EventKind,
3235 payload: serde_json::Value,
3236 persist: EventPersistence,
3237 ) {
3238 dbtx.ensure_global()
3239 .expect("Must be called with global dbtx");
3240 self.log_event_raw_dbtx(
3241 dbtx,
3242 kind,
3243 module_kind.map(|kind| (kind, module_id)),
3244 serde_json::to_vec(&payload).expect("Serialization can't fail"),
3245 persist,
3246 )
3247 .await;
3248 }
3249
3250 async fn read_operation_active_states<'dbtx>(
3251 &self,
3252 operation_id: OperationId,
3253 module_id: ModuleInstanceId,
3254 dbtx: &'dbtx mut DatabaseTransaction<'_>,
3255 ) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (ActiveStateKey, ActiveStateMeta)> + 'dbtx)>>
3256 {
3257 Box::pin(
3258 dbtx.find_by_prefix(&ActiveModuleOperationStateKeyPrefix {
3259 operation_id,
3260 module_instance: module_id,
3261 })
3262 .await
3263 .map(move |(k, v)| (k.0, v)),
3264 )
3265 }
3266 async fn read_operation_inactive_states<'dbtx>(
3267 &self,
3268 operation_id: OperationId,
3269 module_id: ModuleInstanceId,
3270 dbtx: &'dbtx mut DatabaseTransaction<'_>,
3271 ) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (InactiveStateKey, InactiveStateMeta)> + 'dbtx)>>
3272 {
3273 Box::pin(
3274 dbtx.find_by_prefix(&InactiveModuleOperationStateKeyPrefix {
3275 operation_id,
3276 module_instance: module_id,
3277 })
3278 .await
3279 .map(move |(k, v)| (k.0, v)),
3280 )
3281 }
3282}
3283
3284impl fmt::Debug for Client {
3286 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
3287 write!(f, "Client")
3288 }
3289}
3290
3291pub fn client_decoders<'a>(
3292 registry: &ModuleInitRegistry<DynClientModuleInit>,
3293 module_kinds: impl Iterator<Item = (ModuleInstanceId, &'a ModuleKind)>,
3294) -> ModuleDecoderRegistry {
3295 let mut modules = BTreeMap::new();
3296 for (id, kind) in module_kinds {
3297 let Some(init) = registry.get(kind) else {
3298 debug!("Detected configuration for unsupported module id: {id}, kind: {kind}");
3299 continue;
3300 };
3301
3302 modules.insert(
3303 id,
3304 (
3305 kind.clone(),
3306 IClientModuleInit::decoder(AsRef::<dyn IClientModuleInit + 'static>::as_ref(init)),
3307 ),
3308 );
3309 }
3310 ModuleDecoderRegistry::from(modules)
3311}