Skip to main content

fedimint_client/
client.rs

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
117/// List of core api versions supported by the implementation.
118/// Notably `major` version is the one being supported, and corresponding
119/// `minor` version is the one required (for given `major` version).
120const 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/// Primary module candidates at specific priority level
131#[derive(Default)]
132pub(crate) struct PrimaryModuleCandidates {
133    /// Modules that listed specific units they handle
134    specific: BTreeMap<AmountUnit, Vec<ModuleInstanceId>>,
135    /// Modules handling any unit
136    wildcard: Vec<ModuleInstanceId>,
137}
138
139/// An in-progress module recovery future, resolving to the amount recovered
140/// from the module (if it tracks one) once recovery completes.
141pub(crate) type ModuleRecoveryFuture =
142    Pin<Box<maybe_add_send!(dyn Future<Output = Result<Option<Amount>, ClientModuleError>>)>>;
143
144/// The state of a single module's recovery, as tracked by the client.
145///
146/// [`RecoveryProgress`] can only ever express how far a recovery got, never
147/// that it gave up, which makes a failed recovery indistinguishable from a
148/// merely slow one and blocks every waiter on the outcome forever. Carrying the
149/// failure as a state of the very thing the progress describes makes the
150/// contradictory "done and failed" unrepresentable for a module, so a recovery
151/// that terminally fails resolves the waiters it used to strand. Only a
152/// terminal failure does: a recovery that keeps retrying instead of giving up,
153/// as fetching the federation's history does, resolves nothing, and its waiters
154/// keep waiting.
155///
156/// Only the APIs returning a result observe the failure. The ones exposing the
157/// progress itself, like [`Client::has_pending_recoveries`] and
158/// [`Client::subscribe_to_recovery_progress`], keep reporting a failed recovery
159/// as not done, which it is.
160///
161/// Internal: the failure reaches callers as the error of the waiting API, not
162/// as this type, so it stays crate-private rather than committing an
163/// accessorless public type to the API surface.
164///
165/// The module this describes is the key of the map this is stored in, so it is
166/// deliberately not repeated here: a copy could contradict the key it is
167/// filed under.
168#[derive(Clone, Debug)]
169pub(crate) enum RecoveryStatus {
170    /// The latest progress of a recovery that has not failed.
171    ///
172    /// A successfully completed recovery is represented by a done progress.
173    InProgress(RecoveryProgress),
174    /// The recovery terminally failed at `last_progress`, which is kept so the
175    /// progress-reporting APIs can keep describing the module. `error` is
176    /// shared, because every waiter on the recovery is handed the same failure.
177    Failed {
178        last_progress: RecoveryProgress,
179        error: Arc<ClientModuleError>,
180    },
181}
182
183impl RecoveryStatus {
184    /// Whether the module's recovery completed successfully.
185    ///
186    /// A failure is terminal but never done: the module recovered nothing
187    /// beyond the progress it got to.
188    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    /// The progress view of the status, which is all a progress-reporting API
196    /// can express.
197    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
208/// Main client type
209///
210/// A handle and API to interacting with a single federation. End user
211/// applications that want to support interacting with multiple federations at
212/// the same time, will need to instantiate and manage multiple instances of
213/// this struct.
214///
215/// Under the hood it is starting and managing service tasks, state machines,
216/// database and other resources required.
217///
218/// This type is shared externally and internally, and
219/// [`crate::ClientHandle`] is responsible for external lifecycle management
220/// and resource freeing of the [`Client`].
221pub 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    /// Long-lived span attached to every task spawned via [`Client::spawn`] /
243    /// [`Client::spawn_cancellable`], so logs from background tasks carry the
244    /// federation prefix.
245    client_span: Span,
246
247    /// Updates about the recovery status of every recovering module, keyed by
248    /// module instance
249    ///
250    /// Keyed rather than a single slot because a `watch` channel only keeps its
251    /// latest value: if one module's terminal state overwrote another's before
252    /// a waiter observed it, [`Self::wait_for_module_kind_recovery`] could miss
253    /// a failure of its own kind and block forever. Keeping a status per module
254    /// keeps the outcome determinate no matter how many modules fail.
255    ///
256    /// A [`RecoveryStatus::Failed`] is intentionally not persisted: on a
257    /// restart the recovery is simply attempted again, which is the right thing
258    /// to do for a transient cause.
259    client_recovery_status_receiver: watch::Receiver<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
260
261    /// Internal client sender to wake up log ordering task every time a
262    /// (unuordered) log event is added.
263    log_ordering_wakeup_tx: watch::Sender<()>,
264    /// Receiver for events fired every time (ordered) log event is added.
265    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    /// User-provided Bitcoin RPC client for modules to use
271    ///
272    /// Stored here for potential future access; currently passed to modules
273    /// during initialization.
274    #[allow(dead_code)]
275    user_bitcoind_rpc: Option<DynBitcoindRpc>,
276    /// User-provided Bitcoin RPC factory for when ChainId is not available
277    ///
278    /// This is used as a fallback when the federation doesn't support ChainId.
279    /// Modules can call this with a URL from their config to get an RPC client.
280    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/// Which balance `get_balance` and `subscribe_balance_changes` are asking
305/// about. Both fields default, so a caller that predates either the multi-unit
306/// or the multi-account world can keep sending what it always sent.
307#[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
315/// Spelt out rather than derived, since [`Account`] has no `Default` on
316/// purpose. What is defaulted here is one RPC's legacy wire shape, not an
317/// account-scoped write.
318impl Default for BalanceRequest {
319    fn default() -> Self {
320        Self {
321            unit: AmountUnit::bitcoin(),
322            account: Account::primary(),
323        }
324    }
325}
326
327impl Client {
328    /// Initialize a client builder that can be configured to create a new
329    /// client.
330    // Nothing here awaits; the function stays `async` so existing call sites
331    // keep their `.await`.
332    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    /// Returns a stream that emits the current connection status of all peers
345    /// whenever any peer's status changes. Emits initial state immediately.
346    pub fn connection_status_stream(&self) -> impl Stream<Item = BTreeMap<PeerId, PeerStatus>> {
347        self.api.connection_status_stream()
348    }
349
350    /// Establishes connections to all federation guardians once.
351    ///
352    /// Spawns tasks to connect to each guardian in the federation. Unlike
353    /// [`Self::spawn_federation_reconnect`], this only attempts to establish
354    /// connections once and completes - it does not maintain or reconnect.
355    ///
356    /// Useful for warming up connections before making API calls.
357    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    /// Spawns background tasks that proactively maintain connections to all
376    /// federation guardians unconditionally.
377    ///
378    /// For each guardian, a task loops: establishes a connection, waits for it
379    /// to disconnect, then reconnects.
380    ///
381    /// The tasks are cancellable and will be terminated when the client shuts
382    /// down.
383    ///
384    /// By default [`Client`] creates connections on demand only, and share
385    /// them as long as they are alive.
386    ///
387    /// Reconnecting continuously might increase data and battery usage,
388    /// but potentially improve UX, depending on the time it takes to establish
389    /// a new network connection in given network conditions.
390    ///
391    /// Downstream users are encouraged to implement their own version of
392    /// this function, e.g. by reconnecting only when it is anticipated
393    /// that connection might be needed, or alternatively pre-warm
394    /// connections by calling [`Self::federation_reconnect`] when it seems
395    /// worthwhile.
396    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                            // Connection failed, backoff is handled inside
409                            // get_or_create_connection
410                            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    /// Get the [`TaskGroup`] that is tied to Client's lifetime.
424    pub fn task_group(&self) -> &TaskGroup {
425        &self.task_group
426    }
427
428    /// Construct the long-lived span attached to all tasks spawned by this
429    /// client.
430    ///
431    /// `parent: None` keeps the span tree shallow; `runtime::spawn` already
432    /// wraps each task in its own `spawn(task=…)` span, so log events from
433    /// these tasks carry both `task` and `fed_id`.
434    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    /// Spawn a cancellable task on the client's task group, instrumented with
444    /// the client's [`Span`] so all events from the task carry `fed_id`.
445    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    /// Spawn a task on the client's task group, parented to the client's
458    /// [`Span`] so all events from the task carry `fed_id` (including the
459    /// task lifecycle events emitted by [`TaskGroup`] itself).
460    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    /// Returns all registered Prometheus metrics encoded in text format.
474    ///
475    /// This can be used by downstream clients to expose metrics via their own
476    /// HTTP server or print them for debugging purposes.
477    pub fn get_metrics() -> Result<String, fedimint_metrics::prometheus::Error> {
478        fedimint_metrics::get_metrics()
479    }
480
481    /// Useful for our CLI tooling, not meant for external use
482    #[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        // Don't overwrite an existing secret
509        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    // TODO: change to `-> Option<&str>`
602    pub fn api_secret(&self) -> &Option<String> {
603        &self.api_secret
604    }
605
606    /// Returns the core API version that the federation supports
607    ///
608    /// This reads from the cached version stored during client initialization.
609    /// If no cache is available (e.g., during initial setup), returns a default
610    /// version (0, 0).
611    pub async fn core_api_version(&self) -> ApiVersion {
612        // Try to get from cache. If not available, return a conservative
613        // default. The cache should always be populated after successful client init.
614        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    /// Returns the chain ID (bitcoin block hash at height 1) from the
624    /// federation
625    ///
626    /// This is cached in the database after the first successful fetch.
627    /// The chain ID uniquely identifies which bitcoin network the federation
628    /// operates on (mainnet, testnet, signet, regtest).
629    pub async fn chain_id(&self) -> Result<ChainId, FederationError> {
630        // Check cache first
631        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        // Fetch from federation with consensus
642        let chain_id = self.api.chain_id().await?;
643
644        // Cache the result
645        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    /// Returns a reference to the module, panics if not found
657    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    /// Returns the input amount and output amount of a transaction
674    ///
675    /// # Panics
676    /// If any of the input or output versions in the transaction builder are
677    /// unknown by the respective module.
678    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
706/// Accumulate the transaction input and output amounts (including fees) and
707/// check for overflow.
708fn 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    /// Get metadata value from the federation config itself
748    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    // TODO: implement as part of [`OperationLog`]
765    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    /// Get the meta manager to read meta fields.
787    pub fn meta_service(&self) -> &Arc<MetaService> {
788        &self.meta_service
789    }
790
791    /// Get the meta manager to read meta fields.
792    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    /// Adds funding to a transaction or removes over-funding via change.
802    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        // The way currently things are implemented is OK for modules which can
815        // collect a fee relative to one being used, but will break down in any
816        // fancy scenarios. Future TODOs:
817        //
818        // * create_final_inputs_and_outputs needs to get broken down, so we can use
819        //   primary modules using priorities (possibly separate prios for inputs and
820        //   outputs to be able to drain modules, etc.); we need the split "check if
821        //   possible" and "take" steps,
822        // * extra inputs and outputs adding fees needs to be taken into account,
823        //   possibly with some looping
824        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        // This is the range of  outputs that will be added to the transaction
861        // in order to balance it. Notice that it may stay empty in case the transaction
862        // is already balanced.
863        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        // Compute fees as the difference between total input and output amounts.
890        // This captures both explicit federation fees and any overpayment due to
891        // denomination constraints.
892        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    /// Computes the fee that finalizing and submitting a transaction with the
921    /// explicit items described by `request` would incur, without submitting
922    /// anything.
923    ///
924    /// This is the read-only twin of `Self::finalize_transaction`: it runs
925    /// primary-module balancing through `quote_final_inputs_and_outputs`,
926    /// using the same funding selection, consolidation, and rebalancing as
927    /// finalization without requiring cryptographic change outputs.
928    /// It uses a non-committable transaction
929    /// that is dropped rather than committed, so the client's funds are
930    /// read but left untouched. The quote is point-in-time: it depends on
931    /// the current inventory and can move as funds change.
932    ///
933    /// The mechanism is module-agnostic — [`FeeQuoteRequest`] only summarizes
934    /// the explicit side (gross amounts + federation fees) of whichever module
935    /// is quoting (mint, lightning, wallet, …), and the change is generated by
936    /// the primary module of each affected unit. The request and the resulting
937    /// breakdown are multi-unit, so an operation spanning several units (e.g.
938    /// Bitcoin plus a custom currency) is quoted in one call, mirroring how
939    /// `finalize_transaction` balances each unit independently.
940    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        // Start the totals from the explicit side; the change the primary
954        // modules add below is a disjoint set of items, accumulated into these
955        // same totals.
956        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        // The primary modules balance the transaction by minting change (and
962        // possibly pulling in extra inputs). The amounts they must balance
963        // mirror `finalize_transaction`: per unit the input side is the gross
964        // input value, the output side carries the gross output value plus
965        // every explicit fee (fees consume funding on the output side).
966        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        // Non-committable: the balancing writes (e.g. removing consolidated
973        // notes) are discarded on drop, so this is a pure dry-run over the real
974        // inventory.
975        let mut dbtx = self.db.begin_transaction_nc().await;
976
977        // Balance each affected unit independently via its own primary module,
978        // exactly as `finalize_transaction` does over the real transaction.
979        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        // Mark the dropped dbtx as intentionally uncommitted so the commit
1016        // tracker doesn't warn.
1017        dbtx.ignore_uncommitted();
1018
1019        // Per unit: net wallet gain = produced outputs − consumed inputs. The
1020        // total fee is everything the gross input value did not become a net
1021        // gain; whatever is left after the input/output fees is
1022        // sub-denomination dust.
1023        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    /// Add funding and/or change to the transaction builder as needed, finalize
1045    /// the transaction and submit it to the federation.
1046    ///
1047    /// ## Cancel safety
1048    /// This method is cancel safe. It performs all its work (funding the
1049    /// inputs, registering the state machines, and creating the operation log
1050    /// entry) inside a single `autocommit` transaction, so dropping the future
1051    /// either commits that unit in full or leaves the database untouched.
1052    /// Submission to the federation is not awaited here, it is carried out by
1053    /// the transaction-submission state machine in the executor, so cancelling
1054    /// does not abort an already-committed submission.
1055    ///
1056    /// ## Errors
1057    /// Every variant of [`TransactionSubmitError`] can come back from here:
1058    /// [`OperationAlreadyExists`] if an operation with this id is already
1059    /// recorded; [`NoPrimaryModule`] if no primary module holds the unit, so
1060    /// the transaction cannot be balanced; [`InsufficientFunds`] if a genuine
1061    /// shortfall of the primary module leaves it unable to fund the
1062    /// transaction, and [`PrimaryModule`] for every other failure of that
1063    /// module; [`TransactionTooLarge`] if the finalized transaction exceeds
1064    /// the federation's size limit; [`StateMachines`] if the transaction's
1065    /// state machines cannot be registered; [`AmountOverflow`] if calculating
1066    /// the transaction balance or fees overflowed; and [`Database`] if the
1067    /// transaction keeps colliding with others and cannot be committed within
1068    /// its retry budget, which should not happen except in excessively
1069    /// concurrent scenarios.
1070    ///
1071    /// [`OperationAlreadyExists`]: TransactionSubmitError::OperationAlreadyExists
1072    /// [`NoPrimaryModule`]: TransactionSubmitError::NoPrimaryModule
1073    /// [`InsufficientFunds`]: TransactionSubmitError::InsufficientFunds
1074    /// [`PrimaryModule`]: TransactionSubmitError::PrimaryModule
1075    /// [`TransactionTooLarge`]: TransactionSubmitError::TransactionTooLarge
1076    /// [`StateMachines`]: TransactionSubmitError::StateMachines
1077    /// [`AmountOverflow`]: TransactionSubmitError::AmountOverflow
1078    /// [`Database`]: TransactionSubmitError::Database
1079    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), // TODO: handle what happens after 100 retries
1111            )
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    /// See [`Self::finalize_and_submit_transaction`], just inside a database
1124    /// transaction.
1125    ///
1126    /// ## Cancel safety
1127    /// Unlike [`Self::finalize_and_submit_transaction`], this does not own the
1128    /// transaction: all writes go to the passed `dbtx`, so its cancel safety
1129    /// is that of the caller's transaction. The caller is responsible for
1130    /// committing (or rolling back) `dbtx` atomically.
1131    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    /// The account `operation_id` acts on. See [`OperationAccountKey`] for
1266    /// why an absent row is primary.
1267    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    /// Records the account an operation acts on. The operation log calls
1277    /// this as it writes an entry; a module that starts state machines
1278    /// without one, as a recovery does, calls it directly.
1279    ///
1280    /// Write-once: the binding is what a state machine's later claims and
1281    /// refunds are credited by, so an operation already bound to one account
1282    /// cannot be rebound to another. Recording the same account again is a
1283    /// no-op, so an operation recorded here and then started through the log
1284    /// is fine. Absent reads as primary, see [`OperationAccountKey`].
1285    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    /// Whether any state machine of the operation is still running.
1330    pub async fn has_active_states(&self, operation_id: OperationId) -> bool {
1331        self.executor.has_active_states(operation_id).await
1332    }
1333
1334    /// Waits until no state machine of the operation is running any more:
1335    /// every transaction it submitted has been accepted or rejected, and
1336    /// every input and output state machine those started, the primary
1337    /// module's among them, has reached its final state.
1338    ///
1339    /// This is the wait to use for "the operation is over", whatever it
1340    /// consisted of. Unlike [`Self::await_primary_bitcoin_module_outputs`] it
1341    /// needs no outputs named, and it also covers transactions the
1342    /// operation's state machines submit along the way, such as a refund. It
1343    /// does not report how the operation ended; ask the module the operation
1344    /// belongs to for that.
1345    ///
1346    /// Returns at once if no state machine of the operation is running, which
1347    /// includes an operation that never started one. State machines added to
1348    /// the operation after this returns make it active again.
1349    ///
1350    /// State machines only make progress while the client runs, so this never
1351    /// returns for an operation that still has some once the client has shut
1352    /// down.
1353    pub async fn await_no_active_states(&self, operation_id: OperationId) {
1354        self.executor.await_no_active_states(operation_id).await;
1355    }
1356
1357    /// Calculates the federation fees paid in the course of the operation.
1358    ///
1359    /// Federation fees are fees paid to the federation (e.g. for ecash) and do
1360    /// not include fees paid to service providers like the Lightning gateway.
1361    /// These still have to be separately reported by the module.
1362    ///
1363    /// Fees are calculated by subtracting the total output amount from the
1364    /// total input amount, any difference is either due to direct fees or
1365    /// overpayment to avoid generating uneconomic outputs.
1366    ///
1367    /// The returned amount may still increase while the operation is active;
1368    /// use [`Client::has_active_states`] to check whether it is final.
1369    ///
1370    /// Returns `Ok(None)` if any transaction's fee data is missing (e.g. for
1371    /// operations created before this feature was enabled).
1372    ///
1373    /// # Errors
1374    /// Returns an error if the operation does not exist.
1375    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        // For each accepted transaction, look up its stored fees
1403        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    /// Waits for an output from the primary module to reach its final
1418    /// state.
1419    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    /// Returns a reference to a typed module client instance by kind
1435    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    /// Returns a stream of transaction updates for the given operation id that
1479    /// can later be used to watch for a specific transaction being accepted.
1480    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    /// Returns the instance id of the first module of the given kind.
1487    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    /// Waits for outputs from the primary module to reach its final
1495    /// state.
1496    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    /// Returns the config of the client in JSON format.
1510    ///
1511    /// Compared to the consensus module format where module configs are binary
1512    /// encoded this format cannot be cryptographically verified but is easier
1513    /// to consume and to some degree human-readable.
1514    pub async fn get_config_json(&self) -> JsonClientConfig {
1515        self.config().await.to_json()
1516    }
1517
1518    // Ideally this would not be in the API, but there's a lot of places where this
1519    // makes it easier.
1520    #[doc(hidden)]
1521    /// Like [`Self::get_balance`] but returns an error if primary module is not
1522    /// available
1523    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    /// Returns a stream that yields the current client balance every time it
1551    /// changes.
1552    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                // If there is no primary module, there will not be one until client is
1579                // restarted
1580                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                // Deduplicate in case modules cannot always tell if the balance actually changed
1593                if balance != prev_balance {
1594                    prev_balance = balance;
1595                    yield balance;
1596                }
1597            }
1598        })
1599    }
1600
1601    /// Make a single API version request to a peer after a delay.
1602    ///
1603    /// The delay is here to unify the type of a future both for initial request
1604    /// and possible retries.
1605    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    /// Create a backoff strategy for API version requests.
1626    ///
1627    /// Keep trying, initially somewhat aggressively, but after a while retry
1628    /// very slowly, because chances for response are getting lower and
1629    /// lower.
1630    fn create_api_version_backoff() -> impl Iterator<Item = Duration> {
1631        custom_backoff(Duration::from_millis(200), Duration::from_secs(600), None)
1632    }
1633
1634    /// Query the federation for API version support and then calculate
1635    /// the best API version to use (supported by most guardians).
1636    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        // NOTE: `FuturesUnordered` is a footgun, but since we only poll it for result
1645        // and make a single async db write operation, it should be OK.
1646        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                    // Save the response to the database right away, just to
1679                    // not lose it
1680                    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    /// Fetch API versions from peers, retrying until we get threshold number of
1705    /// successful responses. Returns the successful responses collected
1706    /// from at least `num_peers.threshold()` peers.
1707    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        // NOTE: `FuturesUnordered` is a footgun, but since we only poll it for result
1714        // and collect responses, it should be OK.
1715        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    /// Fetch API versions from peers and discover common API versions to use.
1759    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    /// Write API version set to database cache.
1774    /// Used when we have a pre-calculated API version set that should be stored
1775    /// for later use.
1776    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    /// Store prefetched peer API version responses and calculate/store common
1794    /// API version set. This processes the individual peer responses by
1795    /// storing them in the database and calculating the common API version
1796    /// set for caching.
1797    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        // Calculate common API version set from individual responses
1811        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                // Write the calculated common API version set to database cache
1819                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        // Store individual peer responses to database
1828        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    /// [`SupportedApiVersionsSummary`] that the client and its modules support
1840    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    /// Force refresh API versions from the federation, bypassing the cache.
1887    ///
1888    /// This queries all peers for their supported API versions and calculates
1889    /// the common API version set to use. The result is stored in the database
1890    /// cache for future use.
1891    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    /// Load the common api versions to use from cache and start a background
1905    /// process to refresh them.
1906    ///
1907    /// This is a compromise, so we not have to wait for version discovery to
1908    /// complete every time a [`Client`] is being built.
1909    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            // Separate task group, because we actually don't want to be waiting for this to
1937            // finish, and it's just best effort.
1938            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            // Wait to collect enough answers before calculating a set of common api
2012            // versions to use. Note that all peers individual responses from
2013            // previous attempts are still being used, and requests, or even
2014            // retries for response of peers are not actually cancelled, as they
2015            // are happening on a separate task. This is all just to bound the
2016            // time user can be waiting for the join operation to finish, at the
2017            // risk of picking wrong version in very rare circumstances.
2018            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    /// Get the client [`Metadata`]
2062    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    /// Set the client [`Metadata`]
2078    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    /// Whether every module of this client can be used right now.
2102    ///
2103    /// A module that cannot be used while it recovers is left out of the module
2104    /// registry, and only becomes available once the client is reopened with
2105    /// its recovery complete. This reports whether any module is currently held
2106    /// back that way, so an application can tell whether it has to wait for
2107    /// [`Self::wait_for_all_recoveries`] and reopen before it can do anything,
2108    /// or can go ahead right away with a recovery still running.
2109    ///
2110    /// Always `true` for a client that is not recovering.
2111    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    /// Wait for all module recoveries to finish
2119    ///
2120    /// Returns `Ok(())` once every module recovery completed, or an error as
2121    /// soon as any one of them fails terminally.
2122    ///
2123    /// A [`RecoveryError::Failed`] does not mean the recovery task is done: the
2124    /// failed module's progress stays pending forever (so
2125    /// [`Self::has_pending_recoveries`] keeps returning `true`) and the
2126    /// recovery task stays parked. The failure is in-memory only and is not
2127    /// persisted, so reopening the client retries the recovery from its last
2128    /// persisted, non-terminal progress.
2129    ///
2130    /// A bit of a heavy approach.
2131    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    /// Wait for the recovery of every module accepted by `module_filter` to
2140    /// either complete or fail.
2141    ///
2142    /// Since [`RecoveryProgress`] can never express a failure, waiting on
2143    /// progress alone would block forever on a module that gave up. A module
2144    /// that gave up is recorded as [`RecoveryStatus::Failed`] by
2145    /// [`Self::run_module_recoveries_task`] instead, so both outcomes are
2146    /// observable on the same per-module status.
2147    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                // A failure is terminal, so waiting for the modules that are
2161                // still recovering would only delay an outcome that can no
2162                // longer change.
2163                matching().any(|status| matches!(status, RecoveryStatus::Failed { .. }))
2164                    || matching().all(RecoveryStatus::is_successfully_done)
2165            })
2166            .await
2167            .map_err(|_closed| RecoveryError::ClientStopped)?
2168            // Classified from the woken-up snapshot before anything else, so a
2169            // failure of one module still wins over another one completing.
2170            .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    /// Subscribe to recover progress for all the modules.
2188    ///
2189    /// This stream can contain duplicate progress for a module.
2190    /// Don't use this stream for detecting completion of recovery.
2191    ///
2192    /// It can't express a failure either: a module that failed to recover keeps
2193    /// being reported with the last progress it made, which is never done. Use
2194    /// [`Self::wait_for_all_recoveries`] or
2195    /// [`Self::wait_for_module_kind_recovery`] to learn the outcome.
2196    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    /// Wait for the recoveries of all modules of `module_kind` to finish
2209    ///
2210    /// Returns `Ok(())` once every recovery of that kind completed, or an error
2211    /// as soon as one of them fails terminally. Failures of other module kinds
2212    /// are ignored.
2213    ///
2214    /// See [`Self::wait_for_all_recoveries`] for what an error does and does
2215    /// not say about the state of the recovery.
2216    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    /// Set the client [`Metadata`]
2243    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        // Sourced from the config rather than `self.modules`, since modules
2256        // currently being recovered are not yet initialized in the registry.
2257        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        // A module can finish its own final database commit before the client
2262        // persists the corresponding completed progress below. Keep the
2263        // coordinator alive across graceful shutdown so that gap cannot cause
2264        // a non-idempotent module finalization to be replayed on reopen.
2265        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        // A recovery update for a single module: either an intermediate progress
2292        // report, or the final completion carrying the recovered amount (if the
2293        // module tracks it).
2294        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                        // since the progress a module reports can't express a
2314                        // failure, record it as the terminal state of this
2315                        // module's recovery for anyone waiting on the outcome.
2316                        // Keyed by module instance so a later failure of
2317                        // another module can't overwrite this one before a
2318                        // waiter observes it.
2319                        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                        // The terminal failure is now published to the waiters,
2333                        // and this branch stays pending on purpose so the
2334                        // recovery coordinator and its single status sender
2335                        // remain alive. The failed module's progress never
2336                        // becomes done either, so observers that only see the
2337                        // progress keep treating the recovery as pending, which
2338                        // it effectively is. The failure is deliberately not
2339                        // persisted, so reopening the client retries the
2340                        // recovery.
2341                        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            // Cloned so the `watch::Ref` is released right here: holding it
2363            // across the awaits or the `send_modify` below would deadlock the
2364            // channel it borrows from.
2365            let prev_status = recovery_sender
2366                .borrow()
2367                .get(&module_instance_id)
2368                .expect("existing status must be present")
2369                .clone();
2370
2371            // A failure is the terminal state of a module's recovery, but
2372            // progress and completion are merged without any ordering between
2373            // them, so a stale progress update of that module can still arrive
2374            // after it. Applying it would overwrite the failure with an
2375            // in-progress status, and a waiter subscribing afterwards would
2376            // block forever again. Ignoring it entirely, without touching the
2377            // channel, also keeps subscribers from seeing a snapshot that says
2378            // nothing new. Mirrors the sticky "once done, stick with it"
2379            // handling below.
2380            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            // A module reports its progress on a channel it owns, so the values
2392            // arriving here are untrusted: `update_recovery_progress` filters
2393            // them, but a module can send on `progress_tx` directly. Reject the
2394            // values that would break the invariants downstream depends on
2395            // before anything is persisted or broadcast.
2396            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                // The module's channel starts at the progress the client seeded
2407                // it with, so a "none" that doesn't regress anything is the
2408                // normal start of a recovery, not a module misbehaving. Neither
2409                // is one seen after the module already completed: progress and
2410                // completion are merged without ordering between them, so a
2411                // seeded value can arrive after the completion it preceded.
2412                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            // The recovered amount is only known once the module's recovery
2425            // future resolves, which is also the only way progress transitions
2426            // to "done": the guard above rejects a completed progress reported
2427            // by a module, so `RecoveryUpdate::Completed` stays the only
2428            // producer of a done progress, and done therefore implies success.
2429            let (progress, recovered_amount) = if prev_progress.is_done() {
2430                // since updates might be out of order, once done, stick with it
2431                (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    /// You likely want to use [`Client::get_peer_urls`]. This function returns
2501    /// only the announcements and doesn't use the config as fallback.
2502    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    /// Returns guardian metadata stored in the client database
2514    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    /// Asks every guardian for its view of the others' availability and
2528    /// combines the answers with [`merge_peer_availability`]. Guardians that do
2529    /// not answer within a few seconds are left out.
2530    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    /// Returns a list of guardian API URLs
2550    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    /// Create an invite code with the api endpoint of the given peer which can
2555    /// be used to download this client config
2556    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    /// Blocks till the client has synced the guardian public key set
2572    /// (introduced in version 0.4) and returns it. Once it has been fetched
2573    /// once this function is guaranteed to return immediately.
2574    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    /// Serves a JSON request that is not addressed to a module, such as one
2656    /// `fedimint-client-rpc` forwards.
2657    ///
2658    /// # Errors
2659    ///
2660    /// The stream yields a [`GlobalRpcError`] for a request it cannot serve.
2661    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                    // Callers that predate accounts send no params at all.
2670                    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    /// Built in event log (trimmable) tracker
2812    ///
2813    /// For the convenience of downstream applications, [`Client`] can store
2814    /// internally event log position for the main application using/driving it.
2815    ///
2816    /// Note that this position is a singleton, so this tracker should not be
2817    /// used for multiple purposes or applications, etc. at the same time.
2818    ///
2819    /// If the application has a need to follow log using multiple trackers, it
2820    /// should implement own [`DynEventLogTrimableTracker`] and store its
2821    /// persient data by itself.
2822    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            // Store position in the event log
2828            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            /// Load the last previous stored position (or None if never stored)
2839            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    /// Like [`Self::handle_events`] but for historical data.
2850    ///
2851    ///
2852    /// This function can be used to process subset of events
2853    /// that is infrequent and important enough to be persisted
2854    /// forever. Most applications should prefer to use [`Self::handle_events`]
2855    /// which emits *all* events.
2856    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    /// Handle events emitted by the client
2876    ///
2877    /// This is a preferred method for reactive & asynchronous
2878    /// processing of events emitted by the client.
2879    ///
2880    /// It needs a `tracker` that will persist the position in the log
2881    /// as it is being handled. You can use the
2882    /// [`Client::built_in_application_event_log_tracker`] if this call is
2883    /// used for the single main application handling this instance of the
2884    /// [`Client`]. Otherwise you should implement your own tracker.
2885    ///
2886    /// This handler will call `handle_fn` with ever event emitted by
2887    /// [`Client`], including transient ones. The caller should atomically
2888    /// handle each event it is interested in and ignore other ones.
2889    ///
2890    /// This method returns only when client is shutting down or on internal
2891    /// error, so typically should be called in a background task dedicated
2892    /// to handling events.
2893    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    /// Returns the id that the next entry appended to the event log will be
2922    /// assigned, i.e. the position just past the current end of the log.
2923    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    /// Register to receiver all new transient (unpersisted) events
2965    pub fn get_event_log_transient_receiver(&self) -> broadcast::Receiver<EventLogEntry> {
2966        self.log_event_added_transient_tx.subscribe()
2967    }
2968
2969    /// Get a receiver that signals when new events are added to the event log
2970    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    /// Whether compatible iroh-next endpoints from guardian metadata are
2979    /// preferred.
2980    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    /// Iterator over primary modules for a given `unit`
2998    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                    // within same priority, wildcard matches come last
3012                    .chain(candidates.wildcard.iter().copied())
3013            })
3014            .map(|id| (id, self.modules.get_expect(id)))
3015    }
3016
3017    /// Primary module to use for `unit`
3018    ///
3019    /// Currently, just pick the first (highest priority) match
3020    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    /// Whether the primary module for `unit` can hold a balance for
3028    /// `account`. False when there is no primary module for the unit at all.
3029    ///
3030    /// Enforced here rather than by each primary module: balancing a
3031    /// transaction or a fee quote against an unsupported account fails, and
3032    /// its balance reads as zero, so a module only ever sees accounts it
3033    /// advertised.
3034    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    /// [`Self::primary_module_for_unit`] for Bitcoin
3050    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    /// Returns the typed module of kind `M` this client would use for `unit`.
3056    ///
3057    /// Unlike [`Self::get_first_module`], which picks the first instance of a
3058    /// kind regardless of asset, this selects by `unit` so a federation with
3059    /// several mints for different assets routes to the right one.
3060    ///
3061    /// # Errors
3062    ///
3063    /// Fails with [`ModuleLookupError::NoPrimaryModule`] if `unit` has no
3064    /// primary module at all, or with
3065    /// [`ModuleLookupError::NoPrimaryModuleOfKind`] if it has one or more, but
3066    /// none of them is of type `M`.
3067    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            // |out_point_range| operation_meta_gen(out_point_range),
3109            &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        // TODO: make `impl Iterator<Item = ...>`
3188        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
3284// TODO: impl `Debug` for `Client` and derive here
3285impl 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}