Skip to main content

fedimint_client/
client.rs

1use std::collections::{BTreeMap, HashSet};
2use std::fmt::{self, Formatter};
3use std::future::{Future, pending};
4use std::ops::Range;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9use anyhow::{Context as _, anyhow, bail, format_err};
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 _, FederationResult, IGlobalFederationApi,
17};
18use fedimint_bitcoind::DynBitcoindRpc;
19use fedimint_client_module::module::recovery::RecoveryProgress;
20use fedimint_client_module::module::{
21    ClientContextIface, ClientModule, ClientModuleRegistry, DynClientModule, FinalClientIface,
22    IClientModule, IdxRange, OutPointRange, PrimaryModulePriority,
23};
24use fedimint_client_module::oplog::IOperationLog;
25use fedimint_client_module::secret::{PlainRootSecretStrategy, RootSecretStrategy as _};
26use fedimint_client_module::sm::executor::{ActiveStateKey, IExecutor, InactiveStateKey};
27use fedimint_client_module::sm::{ActiveStateMeta, DynState, InactiveStateMeta};
28use fedimint_client_module::transaction::{
29    FeeQuote, FeeQuoteRequest, TRANSACTION_SUBMISSION_MODULE_INSTANCE, TransactionBuilder,
30    TxSubmissionStates, TxSubmissionStatesSM,
31};
32use fedimint_client_module::{
33    AddStateMachinesResult, ClientModuleInstance, GetInviteCodeRequest, ModuleGlobalContextGen,
34    ModuleRecoveryCompleted, TransactionUpdates, TxCreatedEvent,
35};
36use fedimint_connectors::{ConnectorRegistry, PeerStatus};
37use fedimint_core::config::{
38    ClientConfig, FederationId, GlobalClientConfig, JsonClientConfig, ModuleInitRegistry,
39};
40use fedimint_core::core::{DynInput, DynOutput, ModuleInstanceId, ModuleKind, OperationId};
41use fedimint_core::db::{
42    AutocommitError, Database, DatabaseRecord, DatabaseTransaction,
43    IDatabaseTransactionOpsCore as _, IDatabaseTransactionOpsCoreTyped as _, NonCommittable,
44};
45use fedimint_core::encoding::{Decodable, Encodable};
46use fedimint_core::endpoint_constants::{CLIENT_CONFIG_ENDPOINT, VERSION_ENDPOINT};
47use fedimint_core::envs::is_running_in_test_env;
48use fedimint_core::invite_code::InviteCode;
49use fedimint_core::module::registry::{ModuleDecoderRegistry, ModuleRegistry};
50use fedimint_core::module::{
51    AmountUnit, Amounts, ApiRequestErased, ApiVersion, MultiApiVersion,
52    SupportedApiVersionsSummary, SupportedCoreApiVersions, SupportedModuleApiVersions,
53};
54use fedimint_core::net::api_announcement::SignedApiAnnouncement;
55use fedimint_core::runtime::sleep;
56use fedimint_core::task::{
57    Elapsed, MaybeSend, MaybeSync, ShuttingDownError, TaskGroup, TaskHandle,
58};
59use fedimint_core::transaction::Transaction;
60use fedimint_core::util::backoff_util::custom_backoff;
61use fedimint_core::util::{
62    BoxStream, FmtCompact as _, FmtCompactAnyhow as _, SafeUrl, backoff_util, retry,
63};
64use fedimint_core::{
65    Amount, ChainId, NumPeers, OutPoint, PeerId, apply, async_trait_maybe_send, maybe_add_send,
66    maybe_add_send_sync, runtime,
67};
68use fedimint_derive_secret::DerivableSecret;
69use fedimint_eventlog::{
70    DBTransactionEventLogExt as _, DynEventLogTrimableTracker, Event, EventKind, EventLogEntry,
71    EventLogId, EventLogTrimableId, EventLogTrimableTracker, EventPersistence, PersistedLogEntry,
72};
73use fedimint_logging::{LOG_CLIENT, LOG_CLIENT_NET_API, LOG_CLIENT_RECOVERY};
74use futures::stream::FuturesUnordered;
75use futures::{Stream, StreamExt as _};
76use global_ctx::ModuleGlobalClientContext;
77use serde::{Deserialize, Serialize};
78use tokio::sync::{broadcast, oneshot, watch};
79use tokio_stream::wrappers::WatchStream;
80use tracing::{Span, debug, info, warn};
81
82use crate::ClientBuilder;
83use crate::api_announcements::{ApiAnnouncementPrefix, get_api_urls};
84use crate::backup::Metadata;
85use crate::client::event_log::DefaultApplicationEventLogKey;
86use crate::db::{
87    ApiSecretKey, CachedApiVersionSet, CachedApiVersionSetKey, ChainIdKey,
88    ChronologicalOperationLogKey, ClientConfigKey, ClientMetadataKey, ClientModuleRecovery,
89    ClientModuleRecoveryState, EncodedClientSecretKey, OperationLogKey, PeerLastApiVersionsSummary,
90    PeerLastApiVersionsSummaryKey, PendingClientConfigKey, TransactionFeesKey,
91    apply_migrations_core_client_dbtx, get_decoded_client_secret, verify_client_db_integrity_dbtx,
92};
93use crate::meta::MetaService;
94use crate::module_init::{ClientModuleInitRegistry, DynClientModuleInit, IClientModuleInit};
95use crate::oplog::OperationLog;
96use crate::sm::executor::{
97    ActiveModuleOperationStateKeyPrefix, ActiveOperationStateKeyPrefix, Executor,
98    InactiveModuleOperationStateKeyPrefix, InactiveOperationStateKeyPrefix,
99};
100
101pub(crate) mod builder;
102pub(crate) mod event_log;
103pub(crate) mod global_ctx;
104pub(crate) mod handle;
105
106#[cfg(test)]
107mod tests;
108
109/// List of core api versions supported by the implementation.
110/// Notably `major` version is the one being supported, and corresponding
111/// `minor` version is the one required (for given `major` version).
112const SUPPORTED_CORE_API_VERSIONS: &[fedimint_core::module::ApiVersion] =
113    &[ApiVersion { major: 0, minor: 0 }];
114
115struct FinalizedTransaction {
116    transaction: Transaction,
117    states: Vec<DynState>,
118    change_range: Range<u64>,
119    fees: Amounts,
120}
121
122/// Primary module candidates at specific priority level
123#[derive(Default)]
124pub(crate) struct PrimaryModuleCandidates {
125    /// Modules that listed specific units they handle
126    specific: BTreeMap<AmountUnit, Vec<ModuleInstanceId>>,
127    /// Modules handling any unit
128    wildcard: Vec<ModuleInstanceId>,
129}
130
131/// An in-progress module recovery future, resolving to the amount recovered
132/// from the module (if it tracks one) once recovery completes.
133pub(crate) type ModuleRecoveryFuture =
134    Pin<Box<maybe_add_send!(dyn Future<Output = anyhow::Result<Option<Amount>>>)>>;
135
136/// The state of a single module's recovery, as tracked by the client.
137///
138/// [`RecoveryProgress`] can only ever express how far a recovery got, never
139/// that it gave up, which makes a failed recovery indistinguishable from a
140/// merely slow one and blocks every waiter on the outcome forever. Carrying the
141/// failure as a state of the very thing the progress describes makes the
142/// contradictory "done and failed" unrepresentable for a module, so a recovery
143/// that terminally fails resolves the waiters it used to strand. Only a
144/// terminal failure does: a recovery that keeps retrying instead of giving up,
145/// as fetching the federation's history does, resolves nothing, and its waiters
146/// keep waiting.
147///
148/// Only the APIs returning a result observe the failure. The ones exposing the
149/// progress itself, like [`Client::has_pending_recoveries`] and
150/// [`Client::subscribe_to_recovery_progress`], keep reporting a failed recovery
151/// as not done, which it is.
152///
153/// Internal: the failure reaches callers as the error of the waiting API, not
154/// as this type, so it stays crate-private rather than committing an
155/// accessorless public type to the API surface.
156///
157/// The module this describes is the key of the map this is stored in, so it is
158/// deliberately not repeated here: a copy could contradict the key it is
159/// filed under.
160#[derive(Clone, Debug)]
161pub(crate) enum RecoveryStatus {
162    /// The latest progress of a recovery that has not failed.
163    ///
164    /// A successfully completed recovery is represented by a done progress.
165    InProgress(RecoveryProgress),
166    /// The recovery terminally failed at `last_progress`, which is kept so the
167    /// progress-reporting APIs can keep describing the module.
168    Failed {
169        last_progress: RecoveryProgress,
170        error: String,
171    },
172}
173
174impl RecoveryStatus {
175    /// Whether the module's recovery completed successfully.
176    ///
177    /// A failure is terminal but never done: the module recovered nothing
178    /// beyond the progress it got to.
179    pub(crate) fn is_successfully_done(&self) -> bool {
180        match self {
181            Self::InProgress(progress) => progress.is_done(),
182            Self::Failed { .. } => false,
183        }
184    }
185
186    /// The progress view of the status, which is all a progress-reporting API
187    /// can express.
188    pub(crate) fn progress(&self) -> RecoveryProgress {
189        match self {
190            Self::InProgress(progress)
191            | Self::Failed {
192                last_progress: progress,
193                ..
194            } => *progress,
195        }
196    }
197}
198
199/// Main client type
200///
201/// A handle and API to interacting with a single federation. End user
202/// applications that want to support interacting with multiple federations at
203/// the same time, will need to instantiate and manage multiple instances of
204/// this struct.
205///
206/// Under the hood it is starting and managing service tasks, state machines,
207/// database and other resources required.
208///
209/// This type is shared externally and internally, and
210/// [`crate::ClientHandle`] is responsible for external lifecycle management
211/// and resource freeing of the [`Client`].
212pub struct Client {
213    final_client: FinalClientIface,
214    config: tokio::sync::RwLock<ClientConfig>,
215    api_secret: Option<String>,
216    decoders: ModuleDecoderRegistry,
217    connectors: ConnectorRegistry,
218    db: Database,
219    federation_id: FederationId,
220    federation_config_meta: BTreeMap<String, String>,
221    primary_modules: BTreeMap<PrimaryModulePriority, PrimaryModuleCandidates>,
222    pub(crate) modules: ClientModuleRegistry,
223    module_inits: ClientModuleInitRegistry,
224    executor: Executor,
225    pub(crate) api: DynGlobalApi,
226    root_secret: DerivableSecret,
227    operation_log: OperationLog,
228    secp_ctx: Secp256k1<secp256k1::All>,
229    meta_service: Arc<MetaService>,
230
231    task_group: TaskGroup,
232
233    /// Long-lived span attached to every task spawned via [`Client::spawn`] /
234    /// [`Client::spawn_cancellable`], so logs from background tasks carry the
235    /// federation prefix.
236    client_span: Span,
237
238    /// Updates about the recovery status of every recovering module, keyed by
239    /// module instance
240    ///
241    /// Keyed rather than a single slot because a `watch` channel only keeps its
242    /// latest value: if one module's terminal state overwrote another's before
243    /// a waiter observed it, [`Self::wait_for_module_kind_recovery`] could miss
244    /// a failure of its own kind and block forever. Keeping a status per module
245    /// keeps the outcome determinate no matter how many modules fail.
246    ///
247    /// A [`RecoveryStatus::Failed`] is intentionally not persisted: on a
248    /// restart the recovery is simply attempted again, which is the right thing
249    /// to do for a transient cause.
250    client_recovery_status_receiver: watch::Receiver<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
251
252    /// Internal client sender to wake up log ordering task every time a
253    /// (unuordered) log event is added.
254    log_ordering_wakeup_tx: watch::Sender<()>,
255    /// Receiver for events fired every time (ordered) log event is added.
256    log_event_added_rx: watch::Receiver<()>,
257    log_event_added_transient_tx: broadcast::Sender<EventLogEntry>,
258    request_hook: ApiRequestHook,
259    iroh_enable_dht: bool,
260    iroh_enable_next: bool,
261    /// User-provided Bitcoin RPC client for modules to use
262    ///
263    /// Stored here for potential future access; currently passed to modules
264    /// during initialization.
265    #[allow(dead_code)]
266    user_bitcoind_rpc: Option<DynBitcoindRpc>,
267    /// User-provided Bitcoin RPC factory for when ChainId is not available
268    ///
269    /// This is used as a fallback when the federation doesn't support ChainId.
270    /// Modules can call this with a URL from their config to get an RPC client.
271    pub(crate) user_bitcoind_rpc_no_chain_id:
272        Option<fedimint_client_module::module::init::BitcoindRpcNoChainIdFactory>,
273}
274
275#[derive(Debug, Serialize, Deserialize)]
276struct ListOperationsParams {
277    limit: Option<usize>,
278    last_seen: Option<ChronologicalOperationLogKey>,
279}
280
281pub const DEFAULT_EVENT_LOG_PAGE_SIZE: u64 = 100;
282pub const MAX_EVENT_LOG_PAGE_SIZE: u64 = 10_000;
283
284#[derive(Debug, Clone, Serialize, Deserialize)]
285struct GetEventLogRequest {
286    pos: Option<EventLogId>,
287    limit: Option<u64>,
288}
289
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct GetOperationIdRequest {
292    operation_id: OperationId,
293}
294
295#[derive(Debug, Clone, Serialize, Deserialize)]
296pub struct GetBalanceChangesRequest {
297    #[serde(default = "AmountUnit::bitcoin")]
298    unit: AmountUnit,
299}
300
301impl Client {
302    /// Initialize a client builder that can be configured to create a new
303    /// client.
304    pub async fn builder() -> anyhow::Result<ClientBuilder> {
305        Ok(ClientBuilder::new())
306    }
307
308    pub fn api(&self) -> &(dyn IGlobalFederationApi + 'static) {
309        self.api.as_ref()
310    }
311
312    pub fn api_clone(&self) -> DynGlobalApi {
313        self.api.clone()
314    }
315
316    /// Returns a stream that emits the current connection status of all peers
317    /// whenever any peer's status changes. Emits initial state immediately.
318    pub fn connection_status_stream(&self) -> impl Stream<Item = BTreeMap<PeerId, PeerStatus>> {
319        self.api.connection_status_stream()
320    }
321
322    /// Establishes connections to all federation guardians once.
323    ///
324    /// Spawns tasks to connect to each guardian in the federation. Unlike
325    /// [`Self::spawn_federation_reconnect`], this only attempts to establish
326    /// connections once and completes - it does not maintain or reconnect.
327    ///
328    /// Useful for warming up connections before making API calls.
329    pub fn federation_reconnect(&self) {
330        let peers: Vec<PeerId> = self.api.all_peers().iter().copied().collect();
331
332        for peer_id in peers {
333            let api = self.api.clone();
334            self.spawn_cancellable(format!("federation-reconnect-once-{peer_id}"), async move {
335                if let Err(e) = api.get_peer_connection(peer_id).await {
336                    debug!(
337                        target: LOG_CLIENT_NET_API,
338                        %peer_id,
339                        err = %e.fmt_compact(),
340                        "Failed to connect to peer"
341                    );
342                }
343            });
344        }
345    }
346
347    /// Spawns background tasks that proactively maintain connections to all
348    /// federation guardians unconditionally.
349    ///
350    /// For each guardian, a task loops: establishes a connection, waits for it
351    /// to disconnect, then reconnects.
352    ///
353    /// The tasks are cancellable and will be terminated when the client shuts
354    /// down.
355    ///
356    /// By default [`Client`] creates connections on demand only, and share
357    /// them as long as they are alive.
358    ///
359    /// Reconnecting continuously might increase data and battery usage,
360    /// but potentially improve UX, depending on the time it takes to establish
361    /// a new network connection in given network conditions.
362    ///
363    /// Downstream users are encouraged to implement their own version of
364    /// this function, e.g. by reconnecting only when it is anticipated
365    /// that connection might be needed, or alternatively pre-warm
366    /// connections by calling [`Self::federation_reconnect`] when it seems
367    /// worthwhile.
368    pub fn spawn_federation_reconnect(&self) {
369        let peers: Vec<PeerId> = self.api.all_peers().iter().copied().collect();
370
371        for peer_id in peers {
372            let api = self.api.clone();
373            self.spawn_cancellable(format!("federation-reconnect-{peer_id}"), async move {
374                loop {
375                    match api.get_peer_connection(peer_id).await {
376                        Ok(conn) => {
377                            conn.await_disconnection().await;
378                        }
379                        Err(e) => {
380                            // Connection failed, backoff is handled inside
381                            // get_or_create_connection
382                            debug!(
383                                target: LOG_CLIENT_NET_API,
384                                %peer_id,
385                                err = %e.fmt_compact(),
386                                "Failed to connect to peer, will retry"
387                            );
388                        }
389                    }
390                }
391            });
392        }
393    }
394
395    /// Get the [`TaskGroup`] that is tied to Client's lifetime.
396    pub fn task_group(&self) -> &TaskGroup {
397        &self.task_group
398    }
399
400    /// Construct the long-lived span attached to all tasks spawned by this
401    /// client.
402    ///
403    /// `parent: None` keeps the span tree shallow; `runtime::spawn` already
404    /// wraps each task in its own `spawn(task=…)` span, so log events from
405    /// these tasks carry both `task` and `fed_id`.
406    pub(crate) fn make_client_span(federation_id: FederationId) -> Span {
407        tracing::info_span!(
408            target: LOG_CLIENT,
409            parent: None,
410            "client",
411            fed_id = %federation_id.to_prefix(),
412        )
413    }
414
415    /// Spawn a cancellable task on the client's task group, instrumented with
416    /// the client's [`Span`] so all events from the task carry `fed_id`.
417    pub(crate) fn spawn_cancellable<R>(
418        &self,
419        name: impl Into<String>,
420        future: impl Future<Output = R> + MaybeSend + 'static,
421    ) -> oneshot::Receiver<Result<R, ShuttingDownError>>
422    where
423        R: MaybeSend + 'static,
424    {
425        self.task_group
426            .spawn_cancellable_with_span(self.client_span.clone(), name, future)
427    }
428
429    /// Spawn a task on the client's task group, parented to the client's
430    /// [`Span`] so all events from the task carry `fed_id` (including the
431    /// task lifecycle events emitted by [`TaskGroup`] itself).
432    pub(crate) fn spawn<Fut, R>(
433        &self,
434        name: impl Into<String>,
435        f: impl FnOnce(TaskHandle) -> Fut + MaybeSend + 'static,
436    ) -> oneshot::Receiver<R>
437    where
438        Fut: Future<Output = R> + MaybeSend + 'static,
439        R: MaybeSend + 'static,
440    {
441        self.task_group
442            .spawn_with_span(self.client_span.clone(), name, f)
443    }
444
445    /// Returns all registered Prometheus metrics encoded in text format.
446    ///
447    /// This can be used by downstream clients to expose metrics via their own
448    /// HTTP server or print them for debugging purposes.
449    pub fn get_metrics() -> anyhow::Result<String> {
450        fedimint_metrics::get_metrics()
451    }
452
453    /// Useful for our CLI tooling, not meant for external use
454    #[doc(hidden)]
455    pub fn executor(&self) -> &Executor {
456        &self.executor
457    }
458
459    pub async fn get_config_from_db(db: &Database) -> Option<ClientConfig> {
460        let mut dbtx = db.begin_transaction_nc().await;
461        dbtx.get_value(&ClientConfigKey).await
462    }
463
464    pub async fn get_pending_config_from_db(db: &Database) -> Option<ClientConfig> {
465        let mut dbtx = db.begin_transaction_nc().await;
466        dbtx.get_value(&PendingClientConfigKey).await
467    }
468
469    pub async fn get_api_secret_from_db(db: &Database) -> Option<String> {
470        let mut dbtx = db.begin_transaction_nc().await;
471        dbtx.get_value(&ApiSecretKey).await
472    }
473
474    pub async fn store_encodable_client_secret<T: Encodable>(
475        db: &Database,
476        secret: T,
477    ) -> anyhow::Result<()> {
478        let mut dbtx = db.begin_transaction().await;
479
480        // Don't overwrite an existing secret
481        if dbtx.get_value(&EncodedClientSecretKey).await.is_some() {
482            bail!("Encoded client secret already exists, cannot overwrite")
483        }
484
485        let encoded_secret = T::consensus_encode_to_vec(&secret);
486        dbtx.insert_entry(&EncodedClientSecretKey, &encoded_secret)
487            .await;
488        dbtx.commit_tx().await;
489        Ok(())
490    }
491
492    pub async fn load_decodable_client_secret<T: Decodable>(db: &Database) -> anyhow::Result<T> {
493        let Some(secret) = Self::load_decodable_client_secret_opt(db).await? else {
494            bail!("Encoded client secret not present in DB")
495        };
496
497        Ok(secret)
498    }
499    pub async fn load_decodable_client_secret_opt<T: Decodable>(
500        db: &Database,
501    ) -> anyhow::Result<Option<T>> {
502        let mut dbtx = db.begin_transaction_nc().await;
503
504        let client_secret = dbtx.get_value(&EncodedClientSecretKey).await;
505
506        Ok(match client_secret {
507            Some(client_secret) => Some(
508                T::consensus_decode_whole(&client_secret, &ModuleRegistry::default())
509                    .map_err(|e| anyhow!("Decoding failed: {e}"))?,
510            ),
511            None => None,
512        })
513    }
514
515    pub async fn load_or_generate_client_secret(db: &Database) -> anyhow::Result<[u8; 64]> {
516        let client_secret = match Self::load_decodable_client_secret::<[u8; 64]>(db).await {
517            Ok(secret) => secret,
518            _ => {
519                let secret = PlainRootSecretStrategy::random(&mut thread_rng());
520                Self::store_encodable_client_secret(db, secret)
521                    .await
522                    .expect("Storing client secret must work");
523                secret
524            }
525        };
526        Ok(client_secret)
527    }
528
529    pub async fn is_initialized(db: &Database) -> bool {
530        let mut dbtx = db.begin_transaction_nc().await;
531        dbtx.raw_get_bytes(&[ClientConfigKey::DB_PREFIX])
532            .await
533            .expect("Unrecoverable error occurred while reading and entry from the database")
534            .is_some()
535    }
536
537    pub fn start_executor(self: &Arc<Self>) {
538        self.client_span.in_scope(|| {
539            debug!(
540                target: LOG_CLIENT,
541                "Starting fedimint client executor",
542            );
543        });
544        self.executor
545            .start_executor(self.context_gen(), self.client_span.clone());
546    }
547
548    pub fn federation_id(&self) -> FederationId {
549        self.federation_id
550    }
551
552    fn context_gen(self: &Arc<Self>) -> ModuleGlobalContextGen {
553        let client_inner = Arc::downgrade(self);
554        Arc::new(move |module_instance, operation| {
555            ModuleGlobalClientContext {
556                client: client_inner
557                    .clone()
558                    .upgrade()
559                    .expect("ModuleGlobalContextGen called after client was dropped"),
560                module_instance_id: module_instance,
561                operation,
562            }
563            .into()
564        })
565    }
566
567    pub async fn config(&self) -> ClientConfig {
568        self.config.read().await.clone()
569    }
570
571    // TODO: change to `-> Option<&str>`
572    pub fn api_secret(&self) -> &Option<String> {
573        &self.api_secret
574    }
575
576    /// Returns the core API version that the federation supports
577    ///
578    /// This reads from the cached version stored during client initialization.
579    /// If no cache is available (e.g., during initial setup), returns a default
580    /// version (0, 0).
581    pub async fn core_api_version(&self) -> ApiVersion {
582        // Try to get from cache. If not available, return a conservative
583        // default. The cache should always be populated after successful client init.
584        self.db
585            .begin_transaction_nc()
586            .await
587            .get_value(&CachedApiVersionSetKey)
588            .await
589            .map(|cached: CachedApiVersionSet| cached.0.core)
590            .unwrap_or(ApiVersion { major: 0, minor: 0 })
591    }
592
593    /// Returns the chain ID (bitcoin block hash at height 1) from the
594    /// federation
595    ///
596    /// This is cached in the database after the first successful fetch.
597    /// The chain ID uniquely identifies which bitcoin network the federation
598    /// operates on (mainnet, testnet, signet, regtest).
599    pub async fn chain_id(&self) -> anyhow::Result<ChainId> {
600        // Check cache first
601        if let Some(chain_id) = self
602            .db
603            .begin_transaction_nc()
604            .await
605            .get_value(&ChainIdKey)
606            .await
607        {
608            return Ok(chain_id);
609        }
610
611        // Fetch from federation with consensus
612        let chain_id = self.api.chain_id().await?;
613
614        // Cache the result
615        let mut dbtx = self.db.begin_transaction().await;
616        dbtx.insert_entry(&ChainIdKey, &chain_id).await;
617        dbtx.commit_tx().await;
618
619        Ok(chain_id)
620    }
621
622    pub fn decoders(&self) -> &ModuleDecoderRegistry {
623        &self.decoders
624    }
625
626    /// Returns a reference to the module, panics if not found
627    fn get_module(&self, instance: ModuleInstanceId) -> &maybe_add_send_sync!(dyn IClientModule) {
628        self.try_get_module(instance)
629            .expect("Module instance not found")
630    }
631
632    fn try_get_module(
633        &self,
634        instance: ModuleInstanceId,
635    ) -> Option<&maybe_add_send_sync!(dyn IClientModule)> {
636        Some(self.modules.get(instance)?.as_ref())
637    }
638
639    pub fn has_module(&self, instance: ModuleInstanceId) -> bool {
640        self.modules.get(instance).is_some()
641    }
642
643    /// Returns the input amount and output amount of a transaction
644    ///
645    /// # Panics
646    /// If any of the input or output versions in the transaction builder are
647    /// unknown by the respective module.
648    fn transaction_builder_get_balance(&self, builder: &TransactionBuilder) -> (Amounts, Amounts) {
649        // FIXME: prevent overflows, currently not suitable for untrusted input
650        let mut in_amounts = Amounts::ZERO;
651        let mut out_amounts = Amounts::ZERO;
652        let mut fee_amounts = Amounts::ZERO;
653
654        for input in builder.inputs() {
655            let module = self.get_module(input.input.module_instance_id());
656
657            let item_fees = module.input_fee(&input.amounts, &input.input).expect(
658                "We only build transactions with input versions that are supported by the module",
659            );
660
661            in_amounts.checked_add_mut(&input.amounts);
662            fee_amounts.checked_add_mut(&item_fees);
663        }
664
665        for output in builder.outputs() {
666            let module = self.get_module(output.output.module_instance_id());
667
668            let item_fees = module.output_fee(&output.amounts, &output.output).expect(
669                "We only build transactions with output versions that are supported by the module",
670            );
671
672            out_amounts.checked_add_mut(&output.amounts);
673            fee_amounts.checked_add_mut(&item_fees);
674        }
675
676        out_amounts.checked_add_mut(&fee_amounts);
677        (in_amounts, out_amounts)
678    }
679
680    pub fn get_internal_payment_markers(&self) -> anyhow::Result<(PublicKey, u64)> {
681        Ok((self.federation_id().to_fake_ln_pub_key(&self.secp_ctx)?, 0))
682    }
683
684    /// Get metadata value from the federation config itself
685    pub fn get_config_meta(&self, key: &str) -> Option<String> {
686        self.federation_config_meta.get(key).cloned()
687    }
688
689    pub(crate) fn root_secret(&self) -> DerivableSecret {
690        self.root_secret.clone()
691    }
692
693    pub async fn add_state_machines(
694        &self,
695        dbtx: &mut DatabaseTransaction<'_>,
696        states: Vec<DynState>,
697    ) -> AddStateMachinesResult {
698        self.executor.add_state_machines_dbtx(dbtx, states).await
699    }
700
701    // TODO: implement as part of [`OperationLog`]
702    pub async fn get_active_operations(&self) -> HashSet<OperationId> {
703        let active_states = self.executor.get_active_states().await;
704        let mut active_operations = HashSet::with_capacity(active_states.len());
705        let mut dbtx = self.db().begin_transaction_nc().await;
706        for (state, _) in active_states {
707            let operation_id = state.operation_id();
708            if dbtx
709                .get_value(&OperationLogKey { operation_id })
710                .await
711                .is_some()
712            {
713                active_operations.insert(operation_id);
714            }
715        }
716        active_operations
717    }
718
719    pub fn operation_log(&self) -> &OperationLog {
720        &self.operation_log
721    }
722
723    /// Get the meta manager to read meta fields.
724    pub fn meta_service(&self) -> &Arc<MetaService> {
725        &self.meta_service
726    }
727
728    /// Get the meta manager to read meta fields.
729    pub async fn get_meta_expiration_timestamp(&self) -> Option<SystemTime> {
730        let meta_service = self.meta_service();
731        let ts = meta_service
732            .get_field::<u64>(self.db(), "federation_expiry_timestamp")
733            .await
734            .and_then(|v| v.value)?;
735        Some(UNIX_EPOCH + Duration::from_secs(ts))
736    }
737
738    /// Adds funding to a transaction or removes over-funding via change.
739    async fn finalize_transaction(
740        &self,
741        dbtx: &mut DatabaseTransaction<'_>,
742        operation_id: OperationId,
743        mut partial_transaction: TransactionBuilder,
744    ) -> anyhow::Result<FinalizedTransaction> {
745        let (in_amounts, out_amounts) = self.transaction_builder_get_balance(&partial_transaction);
746
747        let mut added_inputs_bundles = vec![];
748        let mut added_outputs_bundles = vec![];
749
750        // The way currently things are implemented is OK for modules which can
751        // collect a fee relative to one being used, but will break down in any
752        // fancy scenarios. Future TODOs:
753        //
754        // * create_final_inputs_and_outputs needs to get broken down, so we can use
755        //   primary modules using priorities (possibly separate prios for inputs and
756        //   outputs to be able to drain modules, etc.); we need the split "check if
757        //   possible" and "take" steps,
758        // * extra inputs and outputs adding fees needs to be taken into account,
759        //   possibly with some looping
760        for unit in in_amounts.units().union(&out_amounts.units()) {
761            let input_amount = in_amounts.get(unit).copied().unwrap_or_default();
762            let output_amount = out_amounts.get(unit).copied().unwrap_or_default();
763            if input_amount == output_amount {
764                continue;
765            }
766
767            let Some((module_id, module)) = self.primary_module_for_unit(*unit) else {
768                bail!("No module to balance a partial transaction (affected unit: {unit:?}");
769            };
770
771            let (added_input_bundle, added_output_bundle) = module
772                .create_final_inputs_and_outputs(
773                    module_id,
774                    dbtx,
775                    operation_id,
776                    *unit,
777                    input_amount,
778                    output_amount,
779                )
780                .await?;
781
782            added_inputs_bundles.push(added_input_bundle);
783            added_outputs_bundles.push(added_output_bundle);
784        }
785
786        // This is the range of  outputs that will be added to the transaction
787        // in order to balance it. Notice that it may stay empty in case the transaction
788        // is already balanced.
789        let change_range = Range {
790            start: partial_transaction.outputs().count() as u64,
791            end: (partial_transaction.outputs().count() as u64
792                + added_outputs_bundles
793                    .iter()
794                    .map(|output| output.outputs().len() as u64)
795                    .sum::<u64>()),
796        };
797
798        for added_inputs in added_inputs_bundles {
799            partial_transaction = partial_transaction.with_inputs(added_inputs);
800        }
801
802        for added_outputs in added_outputs_bundles {
803            partial_transaction = partial_transaction.with_outputs(added_outputs);
804        }
805
806        let (input_amounts, output_amounts) =
807            self.transaction_builder_get_balance(&partial_transaction);
808
809        for (unit, output_amount) in output_amounts {
810            let input_amount = input_amounts.get(&unit).copied().unwrap_or_default();
811
812            assert!(input_amount >= output_amount, "Transaction is underfunded");
813        }
814
815        // Compute fees as the difference between total input and output amounts.
816        // This captures both explicit federation fees and any overpayment due to
817        // denomination constraints.
818        let fees = {
819            let mut input_total = Amounts::ZERO;
820            for input in partial_transaction.inputs() {
821                input_total
822                    .checked_add_mut(&input.amounts)
823                    .expect("Own transaction amounts don't overflow");
824            }
825            let mut output_total = Amounts::ZERO;
826            for output in partial_transaction.outputs() {
827                output_total
828                    .checked_add_mut(&output.amounts)
829                    .expect("Own transaction amounts don't overflow");
830            }
831            input_total
832                .checked_sub(&output_total)
833                .expect("Inputs >= outputs for own transactions")
834        };
835
836        let (transaction, states) = partial_transaction.build(&self.secp_ctx, thread_rng());
837
838        Ok(FinalizedTransaction {
839            transaction,
840            states,
841            change_range,
842            fees,
843        })
844    }
845
846    /// Computes the fee that finalizing and submitting a transaction with the
847    /// explicit items described by `request` would incur, without submitting
848    /// anything.
849    ///
850    /// This is the read-only twin of `Self::finalize_transaction`: it runs
851    /// the exact same primary-module balancing
852    /// (`create_final_inputs_and_outputs`, including funding selection /
853    /// consolidation / rebalancing) against a non-committable transaction
854    /// that is dropped rather than committed, so the client's funds are
855    /// read but left untouched. The quote is point-in-time: it depends on
856    /// the current inventory and can move as funds change.
857    ///
858    /// The mechanism is module-agnostic — [`FeeQuoteRequest`] only summarizes
859    /// the explicit side (gross amounts + federation fees) of whichever module
860    /// is quoting (mint, lightning, wallet, …), and the change is generated by
861    /// the primary module of each affected unit. The request and the resulting
862    /// breakdown are multi-unit, so an operation spanning several units (e.g.
863    /// Bitcoin plus a custom currency) is quoted in one call, mirroring how
864    /// `finalize_transaction` balances each unit independently.
865    pub async fn fee_quote(
866        &self,
867        operation_id: OperationId,
868        request: FeeQuoteRequest,
869    ) -> anyhow::Result<FeeQuote> {
870        let FeeQuoteRequest {
871            input_amount,
872            output_amount,
873            input_fee,
874            output_fee,
875        } = request;
876
877        // Start the totals from the explicit side; the change the primary
878        // modules add below is a disjoint set of items, accumulated into these
879        // same totals.
880        let mut gross_input = input_amount.clone();
881        let mut gross_output = output_amount.clone();
882        let mut input_fees = input_fee.clone();
883        let mut output_fees = output_fee.clone();
884
885        // The primary modules balance the transaction by minting change (and
886        // possibly pulling in extra inputs). The amounts they must balance
887        // mirror `finalize_transaction`: per unit the input side is the gross
888        // input value, the output side carries the gross output value plus
889        // every explicit fee (fees consume funding on the output side).
890        let balance_input = input_amount;
891        let balance_output = output_amount
892            .checked_add(&input_fee)
893            .and_then(|amounts| amounts.checked_add(&output_fee))
894            .expect("explicit amounts and fees cannot overflow an Amounts");
895
896        // Non-committable: the balancing writes (e.g. removing consolidated
897        // notes) are discarded on drop, so this is a pure dry-run over the real
898        // inventory.
899        let mut dbtx = self.db.begin_transaction_nc().await;
900
901        // Balance each affected unit independently via its own primary module,
902        // exactly as `finalize_transaction` does over the real transaction.
903        for unit in balance_input.units().union(&balance_output.units()) {
904            let balance_input_amount = balance_input.get(unit).copied().unwrap_or_default();
905            let balance_output_amount = balance_output.get(unit).copied().unwrap_or_default();
906            if balance_input_amount == balance_output_amount {
907                continue;
908            }
909
910            let Some((module_id, module)) = self.primary_module_for_unit(*unit) else {
911                bail!("No module to balance a partial transaction (affected unit: {unit:?}");
912            };
913
914            let (change_input, change_output) = module
915                .create_final_inputs_and_outputs(
916                    module_id,
917                    &mut dbtx.to_ref_nc(),
918                    operation_id,
919                    *unit,
920                    balance_input_amount,
921                    balance_output_amount,
922                )
923                .await?;
924
925            // Fold the change into the totals. These are a disjoint set of items
926            // from the explicit ones (the primary module only sees the scalar
927            // amounts to balance, never the explicit items), so this is not
928            // double-counting. Iterate the bundles the way `finalize_transaction`
929            // would, looking each fee up via the module that owns the item.
930            for input in change_input.inputs() {
931                let module = self.get_module(input.input.module_instance_id());
932                let fee = module
933                    .input_fee(&input.amounts, &input.input)
934                    .expect("Primary module must know its own change input fees");
935                gross_input.checked_add_mut(&input.amounts);
936                input_fees.checked_add_mut(&fee);
937            }
938
939            for output in change_output.outputs() {
940                let module = self.get_module(output.output.module_instance_id());
941                let fee = module
942                    .output_fee(&output.amounts, &output.output)
943                    .expect("Primary module must know its own change output fees");
944                gross_output.checked_add_mut(&output.amounts);
945                output_fees.checked_add_mut(&fee);
946            }
947        }
948
949        // Mark the dropped dbtx as intentionally uncommitted so the commit
950        // tracker doesn't warn.
951        dbtx.ignore_uncommitted();
952
953        // Per unit: net wallet gain = produced outputs − consumed inputs. The
954        // total fee is everything the gross input value did not become a net
955        // gain; whatever is left after the input/output fees is
956        // sub-denomination dust.
957        let mut dust = Amounts::ZERO;
958        for unit in gross_input.units().union(&gross_output.units()) {
959            let total = gross_input
960                .get(unit)
961                .copied()
962                .unwrap_or_default()
963                .saturating_sub(gross_output.get(unit).copied().unwrap_or_default());
964            let fees = input_fees.get(unit).copied().unwrap_or_default()
965                + output_fees.get(unit).copied().unwrap_or_default();
966            dust = dust
967                .checked_add_unit(total.saturating_sub(fees), *unit)
968                .expect("dust cannot overflow an Amounts");
969        }
970
971        Ok(FeeQuote {
972            input: input_fees,
973            output: output_fees,
974            dust,
975        })
976    }
977
978    /// Add funding and/or change to the transaction builder as needed, finalize
979    /// the transaction and submit it to the federation.
980    ///
981    /// ## Errors
982    /// The function will return an error if the operation with given ID already
983    /// exists.
984    ///
985    /// ## Panics
986    /// The function will panic if the database transaction collides with
987    /// other and fails with others too often, this should not happen except for
988    /// excessively concurrent scenarios.
989    pub async fn finalize_and_submit_transaction<F, M>(
990        &self,
991        operation_id: OperationId,
992        operation_type: &str,
993        operation_meta_gen: F,
994        tx_builder: TransactionBuilder,
995    ) -> anyhow::Result<OutPointRange>
996    where
997        F: Fn(OutPointRange) -> M + Clone + MaybeSend + MaybeSync,
998        M: serde::Serialize + MaybeSend,
999    {
1000        let operation_type = operation_type.to_owned();
1001
1002        let autocommit_res = self
1003            .db
1004            .autocommit(
1005                |dbtx, _| {
1006                    let operation_type = operation_type.clone();
1007                    let tx_builder = tx_builder.clone();
1008                    let operation_meta_gen = operation_meta_gen.clone();
1009                    Box::pin(async move {
1010                        self.finalize_and_submit_transaction_dbtx(
1011                            dbtx,
1012                            operation_id,
1013                            &operation_type,
1014                            operation_meta_gen,
1015                            tx_builder,
1016                        )
1017                        .await
1018                    })
1019                },
1020                Some(100), // TODO: handle what happens after 100 retries
1021            )
1022            .await;
1023
1024        match autocommit_res {
1025            Ok(txid) => Ok(txid),
1026            Err(AutocommitError::ClosureError { error, .. }) => Err(error),
1027            Err(AutocommitError::CommitFailed {
1028                attempts,
1029                last_error,
1030            }) => panic!(
1031                "Failed to commit tx submission dbtx after {attempts} attempts: {last_error}"
1032            ),
1033        }
1034    }
1035
1036    /// See [`Self::finalize_and_submit_transaction`], just inside a database
1037    /// transaction.
1038    pub async fn finalize_and_submit_transaction_dbtx<F, M>(
1039        &self,
1040        dbtx: &mut DatabaseTransaction<'_>,
1041        operation_id: OperationId,
1042        operation_type: &str,
1043        operation_meta_gen: F,
1044        tx_builder: TransactionBuilder,
1045    ) -> anyhow::Result<OutPointRange>
1046    where
1047        F: FnOnce(OutPointRange) -> M + MaybeSend,
1048        M: serde::Serialize + MaybeSend,
1049    {
1050        if Client::operation_exists_dbtx(dbtx, operation_id).await {
1051            bail!("There already exists an operation with id {operation_id:?}")
1052        }
1053
1054        let out_point_range = self
1055            .finalize_and_submit_transaction_inner(dbtx, operation_id, tx_builder)
1056            .await?;
1057
1058        self.operation_log()
1059            .add_operation_log_entry_dbtx(
1060                dbtx,
1061                operation_id,
1062                operation_type,
1063                operation_meta_gen(out_point_range),
1064            )
1065            .await;
1066
1067        Ok(out_point_range)
1068    }
1069
1070    async fn finalize_and_submit_transaction_inner(
1071        &self,
1072        dbtx: &mut DatabaseTransaction<'_>,
1073        operation_id: OperationId,
1074        tx_builder: TransactionBuilder,
1075    ) -> anyhow::Result<OutPointRange> {
1076        let FinalizedTransaction {
1077            transaction,
1078            mut states,
1079            change_range,
1080            fees,
1081        } = self
1082            .finalize_transaction(&mut dbtx.to_ref_nc(), operation_id, tx_builder)
1083            .await?;
1084
1085        if transaction.consensus_encode_to_vec().len() > Transaction::MAX_TX_SIZE {
1086            let inputs = transaction
1087                .inputs
1088                .iter()
1089                .map(DynInput::module_instance_id)
1090                .collect::<Vec<_>>();
1091            let outputs = transaction
1092                .outputs
1093                .iter()
1094                .map(DynOutput::module_instance_id)
1095                .collect::<Vec<_>>();
1096            warn!(
1097                target: LOG_CLIENT_NET_API,
1098                size=%transaction.consensus_encode_to_vec().len(),
1099                ?inputs,
1100                ?outputs,
1101                "Transaction too large",
1102            );
1103            debug!(target: LOG_CLIENT_NET_API, ?transaction, "transaction details");
1104            bail!(
1105                "The generated transaction would be rejected by the federation for being too large."
1106            );
1107        }
1108
1109        let txid = transaction.tx_hash();
1110
1111        debug!(
1112            target: LOG_CLIENT_NET_API,
1113            %txid,
1114            operation_id = %operation_id.fmt_short(),
1115            ?transaction,
1116            "Finalized and submitting transaction",
1117        );
1118
1119        let tx_submission_sm = DynState::from_typed(
1120            TRANSACTION_SUBMISSION_MODULE_INSTANCE,
1121            TxSubmissionStatesSM {
1122                operation_id,
1123                state: TxSubmissionStates::Created(transaction),
1124            },
1125        );
1126        states.push(tx_submission_sm);
1127
1128        self.executor.add_state_machines_dbtx(dbtx, states).await?;
1129
1130        dbtx.insert_new_entry(&TransactionFeesKey(txid), &fees)
1131            .await;
1132
1133        self.log_event_dbtx(dbtx, None, TxCreatedEvent { txid, operation_id })
1134            .await;
1135
1136        Ok(OutPointRange::new(txid, IdxRange::from(change_range)))
1137    }
1138
1139    async fn transaction_update_stream(
1140        &self,
1141        operation_id: OperationId,
1142    ) -> BoxStream<'static, TxSubmissionStatesSM> {
1143        self.executor
1144            .notifier()
1145            .module_notifier::<TxSubmissionStatesSM>(
1146                TRANSACTION_SUBMISSION_MODULE_INSTANCE,
1147                self.final_client.clone(),
1148            )
1149            .subscribe(operation_id)
1150            .await
1151    }
1152
1153    pub async fn operation_exists(&self, operation_id: OperationId) -> bool {
1154        let mut dbtx = self.db().begin_transaction_nc().await;
1155
1156        Client::operation_exists_dbtx(&mut dbtx, operation_id).await
1157    }
1158
1159    pub async fn operation_exists_dbtx(
1160        dbtx: &mut DatabaseTransaction<'_>,
1161        operation_id: OperationId,
1162    ) -> bool {
1163        let active_state_exists = dbtx
1164            .find_by_prefix(&ActiveOperationStateKeyPrefix { operation_id })
1165            .await
1166            .next()
1167            .await
1168            .is_some();
1169
1170        let inactive_state_exists = dbtx
1171            .find_by_prefix(&InactiveOperationStateKeyPrefix { operation_id })
1172            .await
1173            .next()
1174            .await
1175            .is_some();
1176
1177        active_state_exists || inactive_state_exists
1178    }
1179
1180    pub async fn has_active_states(&self, operation_id: OperationId) -> bool {
1181        self.db
1182            .begin_transaction_nc()
1183            .await
1184            .find_by_prefix(&ActiveOperationStateKeyPrefix { operation_id })
1185            .await
1186            .next()
1187            .await
1188            .is_some()
1189    }
1190
1191    /// Calculates the federation fees paid in the course of the operation.
1192    ///
1193    /// Federation fees are fees paid to the federation (e.g. for ecash) and do
1194    /// not include fees paid to service providers like the Lightning gateway.
1195    /// These still have to be separately reported by the module.
1196    ///
1197    /// Fees are calculated by subtracting the total output amount from the
1198    /// total input amount, any difference is either due to direct fees or
1199    /// overpayment to avoid generating uneconomic outputs.
1200    ///
1201    /// The returned amount may still increase while the operation is active;
1202    /// use [`Client::has_active_states`] to check whether it is final.
1203    ///
1204    /// Returns `Ok(None)` if any transaction's fee data is missing (e.g. for
1205    /// operations created before this feature was enabled).
1206    ///
1207    /// # Errors
1208    /// Returns an error if the operation does not exist.
1209    pub async fn get_operation_fees(
1210        &self,
1211        operation_id: OperationId,
1212    ) -> anyhow::Result<Option<Amounts>> {
1213        if !self.operation_exists(operation_id).await {
1214            bail!("Operation does not exist");
1215        }
1216
1217        let (active_states, inactive_states) =
1218            self.executor().get_operation_states(operation_id).await;
1219
1220        let states = active_states
1221            .into_iter()
1222            .map(|(state, _)| state)
1223            .chain(inactive_states.into_iter().map(|(state, _)| state));
1224
1225        let accepted_transactions = states
1226            .filter_map(|state| {
1227                let tx_state = state.as_any().downcast_ref::<TxSubmissionStatesSM>()?;
1228
1229                match &tx_state.state {
1230                    TxSubmissionStates::Accepted(transaction_id) => Some(*transaction_id),
1231                    _ => None,
1232                }
1233            })
1234            .collect::<HashSet<_>>();
1235
1236        // For each accepted transaction, look up its stored fees
1237        let mut dbtx = self.db.begin_transaction_nc().await;
1238        let mut total_fees = Amounts::ZERO;
1239        for txid in &accepted_transactions {
1240            let Some(fees) = dbtx.get_value(&TransactionFeesKey(*txid)).await else {
1241                return Ok(None);
1242            };
1243            total_fees = total_fees
1244                .checked_add(&fees)
1245                .expect("Fee amounts don't overflow in practice");
1246        }
1247
1248        Ok(Some(total_fees))
1249    }
1250
1251    /// Waits for an output from the primary module to reach its final
1252    /// state.
1253    pub async fn await_primary_bitcoin_module_output(
1254        &self,
1255        operation_id: OperationId,
1256        out_point: OutPoint,
1257    ) -> anyhow::Result<()> {
1258        self.primary_module_for_unit(AmountUnit::BITCOIN)
1259            .ok_or_else(|| anyhow!("No primary module available"))?
1260            .1
1261            .await_primary_module_output(operation_id, out_point)
1262            .await
1263    }
1264
1265    /// Returns a reference to a typed module client instance by kind
1266    pub fn get_first_module<M: ClientModule>(
1267        &'_ self,
1268    ) -> anyhow::Result<ClientModuleInstance<'_, M>> {
1269        let module_kind = M::kind();
1270        let id = self
1271            .get_first_instance(&module_kind)
1272            .ok_or_else(|| format_err!("No modules found of kind {module_kind}"))?;
1273        let module: &M = self
1274            .try_get_module(id)
1275            .ok_or_else(|| format_err!("Unknown module instance {id}"))?
1276            .as_any()
1277            .downcast_ref::<M>()
1278            .ok_or_else(|| format_err!("Module is not of type {}", std::any::type_name::<M>()))?;
1279        let (db, _) = self.db().with_prefix_module_id(id);
1280        Ok(ClientModuleInstance {
1281            id,
1282            db,
1283            api: self.api().with_module(id),
1284            module,
1285        })
1286    }
1287
1288    /// Returns an owned `Arc` to a typed module client instance by kind.
1289    ///
1290    /// Unlike [`Self::get_first_module`], this hands out a cloned `Arc` so the
1291    /// caller can hold the module independently of the `Client`'s lifetime.
1292    #[cfg(not(target_family = "wasm"))]
1293    pub fn get_first_module_arc<M: ClientModule>(&self) -> anyhow::Result<Arc<M>> {
1294        let module_kind = M::kind();
1295        let id = self
1296            .get_first_instance(&module_kind)
1297            .ok_or_else(|| format_err!("No modules found of kind {module_kind}"))?;
1298        let dyn_module = self
1299            .modules
1300            .get(id)
1301            .ok_or_else(|| format_err!("Unknown module instance {id}"))?;
1302        dyn_module
1303            .as_any_arc()
1304            .downcast::<M>()
1305            .map_err(|_| format_err!("Module is not of type {}", std::any::type_name::<M>()))
1306    }
1307
1308    pub fn get_module_client_dyn(
1309        &self,
1310        instance_id: ModuleInstanceId,
1311    ) -> anyhow::Result<&maybe_add_send_sync!(dyn IClientModule)> {
1312        self.try_get_module(instance_id)
1313            .ok_or(anyhow!("Unknown module instance {}", instance_id))
1314    }
1315
1316    pub fn db(&self) -> &Database {
1317        &self.db
1318    }
1319
1320    pub fn endpoints(&self) -> &ConnectorRegistry {
1321        &self.connectors
1322    }
1323
1324    /// Returns a stream of transaction updates for the given operation id that
1325    /// can later be used to watch for a specific transaction being accepted.
1326    pub async fn transaction_updates(&self, operation_id: OperationId) -> TransactionUpdates {
1327        TransactionUpdates {
1328            update_stream: self.transaction_update_stream(operation_id).await,
1329        }
1330    }
1331
1332    /// Returns the instance id of the first module of the given kind.
1333    pub fn get_first_instance(&self, module_kind: &ModuleKind) -> Option<ModuleInstanceId> {
1334        self.modules
1335            .iter_modules()
1336            .find(|(_, kind, _module)| *kind == module_kind)
1337            .map(|(instance_id, _, _)| instance_id)
1338    }
1339
1340    /// Returns the data from which the client's root secret is derived (e.g.
1341    /// BIP39 seed phrase struct).
1342    pub async fn root_secret_encoding<T: Decodable>(&self) -> anyhow::Result<T> {
1343        get_decoded_client_secret::<T>(self.db()).await
1344    }
1345
1346    /// Waits for outputs from the primary module to reach its final
1347    /// state.
1348    pub async fn await_primary_bitcoin_module_outputs(
1349        &self,
1350        operation_id: OperationId,
1351        outputs: Vec<OutPoint>,
1352    ) -> anyhow::Result<()> {
1353        for out_point in outputs {
1354            self.await_primary_bitcoin_module_output(operation_id, out_point)
1355                .await?;
1356        }
1357
1358        Ok(())
1359    }
1360
1361    /// Returns the config of the client in JSON format.
1362    ///
1363    /// Compared to the consensus module format where module configs are binary
1364    /// encoded this format cannot be cryptographically verified but is easier
1365    /// to consume and to some degree human-readable.
1366    pub async fn get_config_json(&self) -> JsonClientConfig {
1367        self.config().await.to_json()
1368    }
1369
1370    // Ideally this would not be in the API, but there's a lot of places where this
1371    // makes it easier.
1372    #[doc(hidden)]
1373    /// Like [`Self::get_balance`] but returns an error if primary module is not
1374    /// available
1375    pub async fn get_balance_for_btc(&self) -> anyhow::Result<Amount> {
1376        self.get_balance_for_unit(AmountUnit::BITCOIN).await
1377    }
1378
1379    pub async fn get_balance_for_unit(&self, unit: AmountUnit) -> anyhow::Result<Amount> {
1380        let (id, module) = self
1381            .primary_module_for_unit(unit)
1382            .ok_or_else(|| anyhow!("Primary module not available"))?;
1383        Ok(module
1384            .get_balance(id, &mut self.db().begin_transaction_nc().await, unit)
1385            .await)
1386    }
1387
1388    /// Returns a stream that yields the current client balance every time it
1389    /// changes.
1390    pub async fn subscribe_balance_changes(&self, unit: AmountUnit) -> BoxStream<'static, Amount> {
1391        let primary_module_things =
1392            if let Some((primary_module_id, primary_module)) = self.primary_module_for_unit(unit) {
1393                let balance_changes = primary_module.subscribe_balance_changes().await;
1394                let initial_balance = self
1395                    .get_balance_for_unit(unit)
1396                    .await
1397                    .expect("Primary is present");
1398
1399                Some((
1400                    primary_module_id,
1401                    primary_module.clone(),
1402                    balance_changes,
1403                    initial_balance,
1404                ))
1405            } else {
1406                None
1407            };
1408        let db = self.db().clone();
1409
1410        Box::pin(async_stream::stream! {
1411            let Some((primary_module_id, primary_module, mut balance_changes, initial_balance)) = primary_module_things else {
1412                // If there is no primary module, there will not be one until client is
1413                // restarted
1414                pending().await
1415            };
1416
1417
1418            yield initial_balance;
1419            let mut prev_balance = initial_balance;
1420            while let Some(()) = balance_changes.next().await {
1421                let mut dbtx = db.begin_transaction_nc().await;
1422                let balance = primary_module
1423                     .get_balance(primary_module_id, &mut dbtx, unit)
1424                    .await;
1425
1426                // Deduplicate in case modules cannot always tell if the balance actually changed
1427                if balance != prev_balance {
1428                    prev_balance = balance;
1429                    yield balance;
1430                }
1431            }
1432        })
1433    }
1434
1435    /// Make a single API version request to a peer after a delay.
1436    ///
1437    /// The delay is here to unify the type of a future both for initial request
1438    /// and possible retries.
1439    async fn make_api_version_request(
1440        delay: Duration,
1441        peer_id: PeerId,
1442        api: &DynGlobalApi,
1443    ) -> (
1444        PeerId,
1445        Result<SupportedApiVersionsSummary, fedimint_connectors::error::ServerError>,
1446    ) {
1447        runtime::sleep(delay).await;
1448        (
1449            peer_id,
1450            api.request_single_peer::<SupportedApiVersionsSummary>(
1451                VERSION_ENDPOINT.to_owned(),
1452                ApiRequestErased::default(),
1453                peer_id,
1454            )
1455            .await,
1456        )
1457    }
1458
1459    /// Create a backoff strategy for API version requests.
1460    ///
1461    /// Keep trying, initially somewhat aggressively, but after a while retry
1462    /// very slowly, because chances for response are getting lower and
1463    /// lower.
1464    fn create_api_version_backoff() -> impl Iterator<Item = Duration> {
1465        custom_backoff(Duration::from_millis(200), Duration::from_secs(600), None)
1466    }
1467
1468    /// Query the federation for API version support and then calculate
1469    /// the best API version to use (supported by most guardians).
1470    pub async fn fetch_common_api_versions_from_all_peers(
1471        num_peers: NumPeers,
1472        api: DynGlobalApi,
1473        db: Database,
1474        num_responses_sender: watch::Sender<usize>,
1475    ) {
1476        let mut backoff = Self::create_api_version_backoff();
1477
1478        // NOTE: `FuturesUnordered` is a footgun, but since we only poll it for result
1479        // and make a single async db write operation, it should be OK.
1480        let mut requests = FuturesUnordered::new();
1481
1482        for peer_id in num_peers.peer_ids() {
1483            requests.push(Self::make_api_version_request(
1484                Duration::ZERO,
1485                peer_id,
1486                &api,
1487            ));
1488        }
1489
1490        let mut num_responses = 0;
1491
1492        while let Some((peer_id, response)) = requests.next().await {
1493            let retry = match response {
1494                Err(err) => {
1495                    let has_previous_response = db
1496                        .begin_transaction_nc()
1497                        .await
1498                        .get_value(&PeerLastApiVersionsSummaryKey(peer_id))
1499                        .await
1500                        .is_some();
1501                    debug!(
1502                        target: LOG_CLIENT,
1503                        %peer_id,
1504                        err = %err.fmt_compact(),
1505                        %has_previous_response,
1506                        "Failed to refresh API versions of a peer"
1507                    );
1508
1509                    !has_previous_response
1510                }
1511                Ok(o) => {
1512                    // Save the response to the database right away, just to
1513                    // not lose it
1514                    let mut dbtx = db.begin_transaction().await;
1515                    dbtx.insert_entry(
1516                        &PeerLastApiVersionsSummaryKey(peer_id),
1517                        &PeerLastApiVersionsSummary(o),
1518                    )
1519                    .await;
1520                    dbtx.commit_tx().await;
1521                    false
1522                }
1523            };
1524
1525            if retry {
1526                requests.push(Self::make_api_version_request(
1527                    backoff.next().expect("Keeps retrying"),
1528                    peer_id,
1529                    &api,
1530                ));
1531            } else {
1532                num_responses += 1;
1533                num_responses_sender.send_replace(num_responses);
1534            }
1535        }
1536    }
1537
1538    /// Fetch API versions from peers, retrying until we get threshold number of
1539    /// successful responses. Returns the successful responses collected
1540    /// from at least `num_peers.threshold()` peers.
1541    pub async fn fetch_peers_api_versions_from_threshold_of_peers(
1542        num_peers: NumPeers,
1543        api: DynGlobalApi,
1544    ) -> BTreeMap<PeerId, SupportedApiVersionsSummary> {
1545        let mut backoff = Self::create_api_version_backoff();
1546
1547        // NOTE: `FuturesUnordered` is a footgun, but since we only poll it for result
1548        // and collect responses, it should be OK.
1549        let mut requests = FuturesUnordered::new();
1550
1551        for peer_id in num_peers.peer_ids() {
1552            requests.push(Self::make_api_version_request(
1553                Duration::ZERO,
1554                peer_id,
1555                &api,
1556            ));
1557        }
1558
1559        let mut successful_responses = BTreeMap::new();
1560
1561        while successful_responses.len() < num_peers.threshold()
1562            && let Some((peer_id, response)) = requests.next().await
1563        {
1564            let retry = match response {
1565                Err(err) => {
1566                    debug!(
1567                        target: LOG_CLIENT,
1568                        %peer_id,
1569                        err = %err.fmt_compact(),
1570                        "Failed to fetch API versions from peer"
1571                    );
1572                    true
1573                }
1574                Ok(response) => {
1575                    successful_responses.insert(peer_id, response);
1576                    false
1577                }
1578            };
1579
1580            if retry {
1581                requests.push(Self::make_api_version_request(
1582                    backoff.next().expect("Keeps retrying"),
1583                    peer_id,
1584                    &api,
1585                ));
1586            }
1587        }
1588
1589        successful_responses
1590    }
1591
1592    /// Fetch API versions from peers and discover common API versions to use.
1593    pub async fn fetch_common_api_versions(
1594        config: &ClientConfig,
1595        api: &DynGlobalApi,
1596    ) -> anyhow::Result<BTreeMap<PeerId, SupportedApiVersionsSummary>> {
1597        debug!(
1598            target: LOG_CLIENT,
1599            "Fetching common api versions"
1600        );
1601
1602        let num_peers = NumPeers::from(config.global.api_endpoints.len());
1603
1604        let peer_api_version_sets =
1605            Self::fetch_peers_api_versions_from_threshold_of_peers(num_peers, api.clone()).await;
1606
1607        Ok(peer_api_version_sets)
1608    }
1609
1610    /// Write API version set to database cache.
1611    /// Used when we have a pre-calculated API version set that should be stored
1612    /// for later use.
1613    pub async fn write_api_version_cache(
1614        dbtx: &mut DatabaseTransaction<'_>,
1615        api_version_set: ApiVersionSet,
1616    ) {
1617        debug!(
1618            target: LOG_CLIENT,
1619            value = ?api_version_set,
1620            "Writing API version set to cache"
1621        );
1622
1623        dbtx.insert_entry(
1624            &CachedApiVersionSetKey,
1625            &CachedApiVersionSet(api_version_set),
1626        )
1627        .await;
1628    }
1629
1630    /// Store prefetched peer API version responses and calculate/store common
1631    /// API version set. This processes the individual peer responses by
1632    /// storing them in the database and calculating the common API version
1633    /// set for caching.
1634    pub async fn store_prefetched_api_versions(
1635        db: &Database,
1636        config: &ClientConfig,
1637        client_module_init: &ClientModuleInitRegistry,
1638        peer_api_versions: &BTreeMap<PeerId, SupportedApiVersionsSummary>,
1639    ) {
1640        debug!(
1641            target: LOG_CLIENT,
1642            "Storing {} prefetched peer API version responses and calculating common version set",
1643            peer_api_versions.len()
1644        );
1645
1646        let mut dbtx = db.begin_transaction().await;
1647        // Calculate common API version set from individual responses
1648        let client_supported_versions =
1649            Self::supported_api_versions_summary_static(config, client_module_init);
1650        match fedimint_client_module::api_version_discovery::discover_common_api_versions_set(
1651            &client_supported_versions,
1652            peer_api_versions,
1653        ) {
1654            Ok(common_api_versions) => {
1655                // Write the calculated common API version set to database cache
1656                Self::write_api_version_cache(&mut dbtx.to_ref_nc(), common_api_versions).await;
1657                debug!(target: LOG_CLIENT, "Calculated and stored common API version set");
1658            }
1659            Err(err) => {
1660                debug!(target: LOG_CLIENT, err = %err.fmt_compact_anyhow(), "Failed to calculate common API versions from prefetched data");
1661            }
1662        }
1663
1664        // Store individual peer responses to database
1665        for (peer_id, peer_api_versions) in peer_api_versions {
1666            dbtx.insert_entry(
1667                &PeerLastApiVersionsSummaryKey(*peer_id),
1668                &PeerLastApiVersionsSummary(peer_api_versions.clone()),
1669            )
1670            .await;
1671        }
1672        dbtx.commit_tx().await;
1673        debug!(target: LOG_CLIENT, "Stored individual peer API version responses");
1674    }
1675
1676    /// [`SupportedApiVersionsSummary`] that the client and its modules support
1677    pub fn supported_api_versions_summary_static(
1678        config: &ClientConfig,
1679        client_module_init: &ClientModuleInitRegistry,
1680    ) -> SupportedApiVersionsSummary {
1681        SupportedApiVersionsSummary {
1682            core: SupportedCoreApiVersions {
1683                core_consensus: config.global.consensus_version,
1684                api: MultiApiVersion::try_from_iter(SUPPORTED_CORE_API_VERSIONS.to_owned())
1685                    .expect("must not have conflicting versions"),
1686            },
1687            modules: config
1688                .modules
1689                .iter()
1690                .filter_map(|(&module_instance_id, module_config)| {
1691                    client_module_init
1692                        .get(module_config.kind())
1693                        .map(|module_init| {
1694                            (
1695                                module_instance_id,
1696                                SupportedModuleApiVersions {
1697                                    core_consensus: config.global.consensus_version,
1698                                    module_consensus: module_config.version,
1699                                    api: module_init.supported_api_versions(),
1700                                },
1701                            )
1702                        })
1703                })
1704                .collect(),
1705        }
1706    }
1707
1708    pub async fn load_and_refresh_common_api_version(&self) -> anyhow::Result<ApiVersionSet> {
1709        Self::load_and_refresh_common_api_version_static(
1710            &self.config().await,
1711            &self.module_inits,
1712            self.connectors.clone(),
1713            &self.api,
1714            &self.db,
1715            &self.task_group,
1716            &self.client_span,
1717        )
1718        .await
1719    }
1720
1721    /// Force refresh API versions from the federation, bypassing the cache.
1722    ///
1723    /// This queries all peers for their supported API versions and calculates
1724    /// the common API version set to use. The result is stored in the database
1725    /// cache for future use.
1726    pub async fn refresh_api_versions(&self) -> anyhow::Result<ApiVersionSet> {
1727        Self::refresh_common_api_version_static(
1728            &self.config().await,
1729            &self.module_inits,
1730            &self.api,
1731            &self.db,
1732            self.task_group.clone(),
1733            &self.client_span,
1734            true,
1735        )
1736        .await
1737    }
1738
1739    /// Load the common api versions to use from cache and start a background
1740    /// process to refresh them.
1741    ///
1742    /// This is a compromise, so we not have to wait for version discovery to
1743    /// complete every time a [`Client`] is being built.
1744    pub(crate) async fn load_and_refresh_common_api_version_static(
1745        config: &ClientConfig,
1746        module_init: &ClientModuleInitRegistry,
1747        connectors: ConnectorRegistry,
1748        api: &DynGlobalApi,
1749        db: &Database,
1750        task_group: &TaskGroup,
1751        client_span: &Span,
1752    ) -> anyhow::Result<ApiVersionSet> {
1753        if let Some(v) = db
1754            .begin_transaction_nc()
1755            .await
1756            .get_value(&CachedApiVersionSetKey)
1757            .await
1758        {
1759            client_span.in_scope(|| {
1760                debug!(
1761                    target: LOG_CLIENT,
1762                    "Found existing cached common api versions"
1763                );
1764            });
1765            let config = config.clone();
1766            let client_module_init = module_init.clone();
1767            let api = api.clone();
1768            let db = db.clone();
1769            let task_group = task_group.clone();
1770            let client_span_owned = client_span.clone();
1771            // Separate task group, because we actually don't want to be waiting for this to
1772            // finish, and it's just best effort.
1773            task_group.clone().spawn_cancellable_with_span(
1774                client_span.clone(),
1775                "refresh_common_api_version_static",
1776                async move {
1777                    connectors.wait_for_initialized_connections().await;
1778
1779                    if let Err(error) = Self::refresh_common_api_version_static(
1780                        &config,
1781                        &client_module_init,
1782                        &api,
1783                        &db,
1784                        task_group,
1785                        &client_span_owned,
1786                        false,
1787                    )
1788                    .await
1789                    {
1790                        warn!(
1791                            target: LOG_CLIENT,
1792                            err = %error.fmt_compact_anyhow(), "Failed to discover common api versions"
1793                        );
1794                    }
1795                },
1796            );
1797
1798            return Ok(v.0);
1799        }
1800
1801        info!(
1802            target: LOG_CLIENT,
1803            "Fetching initial API versions "
1804        );
1805        Self::refresh_common_api_version_static(
1806            config,
1807            module_init,
1808            api,
1809            db,
1810            task_group.clone(),
1811            client_span,
1812            true,
1813        )
1814        .await
1815    }
1816
1817    async fn refresh_common_api_version_static(
1818        config: &ClientConfig,
1819        client_module_init: &ClientModuleInitRegistry,
1820        api: &DynGlobalApi,
1821        db: &Database,
1822        task_group: TaskGroup,
1823        client_span: &Span,
1824        block_until_ok: bool,
1825    ) -> anyhow::Result<ApiVersionSet> {
1826        debug!(
1827            target: LOG_CLIENT,
1828            "Refreshing common api versions"
1829        );
1830
1831        let (num_responses_sender, mut num_responses_receiver) = tokio::sync::watch::channel(0);
1832        let num_peers = NumPeers::from(config.global.api_endpoints.len());
1833
1834        task_group.spawn_cancellable_with_span(
1835            client_span.clone(),
1836            "refresh peers api versions",
1837            Client::fetch_common_api_versions_from_all_peers(
1838                num_peers,
1839                api.clone(),
1840                db.clone(),
1841                num_responses_sender,
1842            ),
1843        );
1844
1845        let common_api_versions = loop {
1846            // Wait to collect enough answers before calculating a set of common api
1847            // versions to use. Note that all peers individual responses from
1848            // previous attempts are still being used, and requests, or even
1849            // retries for response of peers are not actually cancelled, as they
1850            // are happening on a separate task. This is all just to bound the
1851            // time user can be waiting for the join operation to finish, at the
1852            // risk of picking wrong version in very rare circumstances.
1853            let _: Result<_, Elapsed> = runtime::timeout(
1854                Duration::from_secs(30),
1855                num_responses_receiver.wait_for(|num| num_peers.threshold() <= *num),
1856            )
1857            .await;
1858
1859            let peer_api_version_sets = Self::load_peers_last_api_versions(db, num_peers).await;
1860
1861            match fedimint_client_module::api_version_discovery::discover_common_api_versions_set(
1862                &Self::supported_api_versions_summary_static(config, client_module_init),
1863                &peer_api_version_sets,
1864            ) {
1865                Ok(o) => break o,
1866                Err(err) if block_until_ok => {
1867                    warn!(
1868                        target: LOG_CLIENT,
1869                        err = %err.fmt_compact_anyhow(),
1870                        "Failed to discover API version to use. Retrying..."
1871                    );
1872                    continue;
1873                }
1874                Err(e) => return Err(e),
1875            }
1876        };
1877
1878        debug!(
1879            target: LOG_CLIENT,
1880            value = ?common_api_versions,
1881            "Updating the cached common api versions"
1882        );
1883        let mut dbtx = db.begin_transaction().await;
1884        let _ = dbtx
1885            .insert_entry(
1886                &CachedApiVersionSetKey,
1887                &CachedApiVersionSet(common_api_versions.clone()),
1888            )
1889            .await;
1890
1891        dbtx.commit_tx().await;
1892
1893        Ok(common_api_versions)
1894    }
1895
1896    /// Get the client [`Metadata`]
1897    pub async fn get_metadata(&self) -> Metadata {
1898        self.db
1899            .begin_transaction_nc()
1900            .await
1901            .get_value(&ClientMetadataKey)
1902            .await
1903            .unwrap_or_else(|| {
1904                warn!(
1905                    target: LOG_CLIENT,
1906                    "Missing existing metadata. This key should have been set on Client init"
1907                );
1908                Metadata::empty()
1909            })
1910    }
1911
1912    /// Set the client [`Metadata`]
1913    pub async fn set_metadata(&self, metadata: &Metadata) {
1914        self.db
1915            .autocommit::<_, _, anyhow::Error>(
1916                |dbtx, _| {
1917                    Box::pin(async {
1918                        Self::set_metadata_dbtx(dbtx, metadata).await;
1919                        Ok(())
1920                    })
1921                },
1922                None,
1923            )
1924            .await
1925            .expect("Failed to autocommit metadata");
1926    }
1927
1928    pub fn has_pending_recoveries(&self) -> bool {
1929        !self
1930            .client_recovery_status_receiver
1931            .borrow()
1932            .values()
1933            .all(RecoveryStatus::is_successfully_done)
1934    }
1935
1936    /// Whether every module of this client can be used right now.
1937    ///
1938    /// A module that cannot be used while it recovers is left out of the module
1939    /// registry, and only becomes available once the client is reopened with
1940    /// its recovery complete. This reports whether any module is currently held
1941    /// back that way, so an application can tell whether it has to wait for
1942    /// [`Self::wait_for_all_recoveries`] and reopen before it can do anything,
1943    /// or can go ahead right away with a recovery still running.
1944    ///
1945    /// Always `true` for a client that is not recovering.
1946    pub fn all_modules_usable(&self) -> bool {
1947        self.client_recovery_status_receiver
1948            .borrow()
1949            .keys()
1950            .all(|module_instance_id| self.modules.get(*module_instance_id).is_some())
1951    }
1952
1953    /// Wait for all module recoveries to finish
1954    ///
1955    /// Returns `Ok(())` once every module recovery completed, or an error as
1956    /// soon as any one of them fails terminally.
1957    ///
1958    /// An error does not mean the recovery task is done: the failed module's
1959    /// progress stays pending forever (so [`Self::has_pending_recoveries`]
1960    /// keeps returning `true`) and the recovery task stays parked. The
1961    /// failure is in-memory only and is not persisted, so reopening the
1962    /// client retries the recovery from its last persisted, non-terminal
1963    /// progress.
1964    ///
1965    /// A bit of a heavy approach.
1966    pub async fn wait_for_all_recoveries(&self) -> anyhow::Result<()> {
1967        Self::wait_for_recoveries(
1968            self.client_recovery_status_receiver.clone(),
1969            |_module_instance_id| true,
1970            "Recovery task completed and update receiver disconnected, but some modules failed to recover",
1971        )
1972        .await
1973    }
1974
1975    /// Wait for the recovery of every module accepted by `module_filter` to
1976    /// either complete or fail.
1977    ///
1978    /// Since [`RecoveryProgress`] can never express a failure, waiting on
1979    /// progress alone would block forever on a module that gave up. A module
1980    /// that gave up is recorded as [`RecoveryStatus::Failed`] by
1981    /// [`Self::run_module_recoveries_task`] instead, so both outcomes are
1982    /// observable on the same per-module status.
1983    async fn wait_for_recoveries(
1984        mut status_receiver: watch::Receiver<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
1985        module_filter: impl Fn(ModuleInstanceId) -> bool,
1986        disconnected_context: &'static str,
1987    ) -> anyhow::Result<()> {
1988        let failure = status_receiver
1989            .wait_for(|statuses| {
1990                let matching = || {
1991                    statuses
1992                        .iter()
1993                        .filter(|(module_instance_id, _status)| module_filter(**module_instance_id))
1994                        .map(|(_module_instance_id, status)| status)
1995                };
1996
1997                // A failure is terminal, so waiting for the modules that are
1998                // still recovering would only delay an outcome that can no
1999                // longer change.
2000                matching().any(|status| matches!(status, RecoveryStatus::Failed { .. }))
2001                    || matching().all(RecoveryStatus::is_successfully_done)
2002            })
2003            .await
2004            .context(disconnected_context)?
2005            // Classified from the woken-up snapshot before anything else, so a
2006            // failure of one module still wins over another one completing.
2007            .iter()
2008            .find_map(|(module_instance_id, status)| match status {
2009                RecoveryStatus::Failed { error, .. } if module_filter(*module_instance_id) => {
2010                    Some((*module_instance_id, error.clone()))
2011                }
2012                _ => None,
2013            });
2014
2015        match failure {
2016            Some((module_instance_id, error)) => Err(anyhow!(
2017                "Module recovery failed: module_instance_id={module_instance_id}, error={error}"
2018            )),
2019            None => Ok(()),
2020        }
2021    }
2022
2023    /// Subscribe to recover progress for all the modules.
2024    ///
2025    /// This stream can contain duplicate progress for a module.
2026    /// Don't use this stream for detecting completion of recovery.
2027    ///
2028    /// It can't express a failure either: a module that failed to recover keeps
2029    /// being reported with the last progress it made, which is never done. Use
2030    /// [`Self::wait_for_all_recoveries`] or
2031    /// [`Self::wait_for_module_kind_recovery`] to learn the outcome.
2032    pub fn subscribe_to_recovery_progress(
2033        &self,
2034    ) -> impl Stream<Item = (ModuleInstanceId, RecoveryProgress)> + use<> {
2035        WatchStream::new(self.client_recovery_status_receiver.clone()).flat_map(|statuses| {
2036            futures::stream::iter(
2037                statuses
2038                    .into_iter()
2039                    .map(|(module_instance_id, status)| (module_instance_id, status.progress())),
2040            )
2041        })
2042    }
2043
2044    /// Wait for the recoveries of all modules of `module_kind` to finish
2045    ///
2046    /// Returns `Ok(())` once every recovery of that kind completed, or an error
2047    /// as soon as one of them fails terminally. Failures of other module kinds
2048    /// are ignored.
2049    ///
2050    /// See [`Self::wait_for_all_recoveries`] for what an error does and does
2051    /// not say about the state of the recovery.
2052    pub async fn wait_for_module_kind_recovery(
2053        &self,
2054        module_kind: ModuleKind,
2055    ) -> anyhow::Result<()> {
2056        let config = self.config().await;
2057        Self::wait_for_recoveries(
2058            self.client_recovery_status_receiver.clone(),
2059            move |module_instance_id| {
2060                config
2061                    .modules
2062                    .get(&module_instance_id)
2063                    .is_some_and(|module| module.kind == module_kind)
2064            },
2065            "Recovery task completed and update receiver disconnected, but the desired modules are still unavailable or failed to recover",
2066        )
2067        .await
2068    }
2069
2070    pub async fn wait_for_all_active_state_machines(&self) -> anyhow::Result<()> {
2071        loop {
2072            if self.executor.get_active_states().await.is_empty() {
2073                break;
2074            }
2075            sleep(Duration::from_millis(100)).await;
2076        }
2077        Ok(())
2078    }
2079
2080    /// Set the client [`Metadata`]
2081    pub async fn set_metadata_dbtx(dbtx: &mut DatabaseTransaction<'_>, metadata: &Metadata) {
2082        dbtx.insert_new_entry(&ClientMetadataKey, metadata).await;
2083    }
2084
2085    fn spawn_module_recoveries_task(
2086        &self,
2087        recovery_sender: watch::Sender<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
2088        module_recoveries: BTreeMap<ModuleInstanceId, ModuleRecoveryFuture>,
2089        module_recovery_progress_receivers: BTreeMap<
2090            ModuleInstanceId,
2091            watch::Receiver<RecoveryProgress>,
2092        >,
2093        // Sourced from the config rather than `self.modules`, since modules
2094        // currently being recovered are not yet initialized in the registry.
2095        module_kinds: BTreeMap<ModuleInstanceId, ModuleKind>,
2096    ) {
2097        let db = self.db.clone();
2098        let log_ordering_wakeup_tx = self.log_ordering_wakeup_tx.clone();
2099        // A module can finish its own final database commit before the client
2100        // persists the corresponding completed progress below. Keep the
2101        // coordinator alive across graceful shutdown so that gap cannot cause
2102        // a non-idempotent module finalization to be replayed on reopen.
2103        self.spawn("module recoveries", |_task_handle| async {
2104            Self::run_module_recoveries_task(
2105                db,
2106                log_ordering_wakeup_tx,
2107                recovery_sender,
2108                module_recoveries,
2109                module_recovery_progress_receivers,
2110                module_kinds,
2111            )
2112            .await;
2113        });
2114    }
2115
2116    async fn run_module_recoveries_task(
2117        db: Database,
2118        log_ordering_wakeup_tx: watch::Sender<()>,
2119        recovery_sender: watch::Sender<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
2120        module_recoveries: BTreeMap<ModuleInstanceId, ModuleRecoveryFuture>,
2121        module_recovery_progress_receivers: BTreeMap<
2122            ModuleInstanceId,
2123            watch::Receiver<RecoveryProgress>,
2124        >,
2125        module_kinds: BTreeMap<ModuleInstanceId, ModuleKind>,
2126    ) {
2127        debug!(target: LOG_CLIENT_RECOVERY, num_modules=%module_recovery_progress_receivers.len(), "Staring module recoveries");
2128
2129        // A recovery update for a single module: either an intermediate progress
2130        // report, or the final completion carrying the recovered amount (if the
2131        // module tracks it).
2132        enum RecoveryUpdate {
2133            Progress(RecoveryProgress),
2134            Completed(Option<Amount>),
2135        }
2136
2137        let mut completed_stream = Vec::new();
2138        let progress_stream = futures::stream::FuturesUnordered::new();
2139
2140        for (module_instance_id, f) in module_recoveries {
2141            let recovery_sender = recovery_sender.clone();
2142            completed_stream.push(futures::stream::once(Box::pin(async move {
2143                match f.await {
2144                    Ok(amount) => (module_instance_id, RecoveryUpdate::Completed(amount)),
2145                    Err(err) => {
2146                        let error = err.fmt_compact_anyhow().to_string();
2147                        warn!(
2148                            target: LOG_CLIENT,
2149                            err = %error.as_str(), module_instance_id, "Module recovery failed"
2150                        );
2151                        // since the progress a module reports can't express a
2152                        // failure, record it as the terminal state of this
2153                        // module's recovery for anyone waiting on the outcome.
2154                        // Keyed by module instance so a later failure of
2155                        // another module can't overwrite this one before a
2156                        // waiter observes it.
2157                        recovery_sender.send_modify(|statuses| {
2158                            let last_progress = statuses
2159                                .get(&module_instance_id)
2160                                .expect("existing status must be present")
2161                                .progress();
2162                            statuses.insert(
2163                                module_instance_id,
2164                                RecoveryStatus::Failed {
2165                                    last_progress,
2166                                    error,
2167                                },
2168                            );
2169                        });
2170                        // The terminal failure is now published to the waiters,
2171                        // and this branch stays pending on purpose so the
2172                        // recovery coordinator and its single status sender
2173                        // remain alive. The failed module's progress never
2174                        // becomes done either, so observers that only see the
2175                        // progress keep treating the recovery as pending, which
2176                        // it effectively is. The failure is deliberately not
2177                        // persisted, so reopening the client retries the
2178                        // recovery.
2179                        futures::future::pending::<()>().await;
2180                        unreachable!()
2181                    }
2182                }
2183            })));
2184        }
2185
2186        for (module_instance_id, rx) in module_recovery_progress_receivers {
2187            progress_stream.push(
2188                tokio_stream::wrappers::WatchStream::new(rx)
2189                    .fuse()
2190                    .map(move |progress| (module_instance_id, RecoveryUpdate::Progress(progress))),
2191            );
2192        }
2193
2194        let mut futures = futures::stream::select(
2195            futures::stream::select_all(progress_stream),
2196            futures::stream::select_all(completed_stream),
2197        );
2198
2199        while let Some((module_instance_id, update)) = futures.next().await {
2200            // Cloned so the `watch::Ref` is released right here: holding it
2201            // across the awaits or the `send_modify` below would deadlock the
2202            // channel it borrows from.
2203            let prev_status = recovery_sender
2204                .borrow()
2205                .get(&module_instance_id)
2206                .expect("existing status must be present")
2207                .clone();
2208
2209            // A failure is the terminal state of a module's recovery, but
2210            // progress and completion are merged without any ordering between
2211            // them, so a stale progress update of that module can still arrive
2212            // after it. Applying it would overwrite the failure with an
2213            // in-progress status, and a waiter subscribing afterwards would
2214            // block forever again. Ignoring it entirely, without touching the
2215            // channel, also keeps subscribers from seeing a snapshot that says
2216            // nothing new. Mirrors the sticky "once done, stick with it"
2217            // handling below.
2218            if matches!(prev_status, RecoveryStatus::Failed { .. }) {
2219                debug!(
2220                    target: LOG_CLIENT_RECOVERY,
2221                    module_instance_id,
2222                    "Ignoring a recovery update of a module whose recovery already failed"
2223                );
2224                continue;
2225            }
2226
2227            let prev_progress = prev_status.progress();
2228
2229            // A module reports its progress on a channel it owns, so the values
2230            // arriving here are untrusted: `update_recovery_progress` filters
2231            // them, but a module can send on `progress_tx` directly. Reject the
2232            // values that would break the invariants downstream depends on
2233            // before anything is persisted or broadcast.
2234            if let RecoveryUpdate::Progress(progress) = &update {
2235                if progress.is_done() {
2236                    warn!(
2237                        target: LOG_CLIENT_RECOVERY,
2238                        module_instance_id,
2239                        "Module bypassed the sanctioned recovery progress reporting API and reported a completed recovery progress. Ignoring"
2240                    );
2241                    continue;
2242                }
2243
2244                // The module's channel starts at the progress the client seeded
2245                // it with, so a "none" that doesn't regress anything is the
2246                // normal start of a recovery, not a module misbehaving. Neither
2247                // is one seen after the module already completed: progress and
2248                // completion are merged without ordering between them, so a
2249                // seeded value can arrive after the completion it preceded.
2250                if progress.is_none() && !prev_progress.is_none() && !prev_progress.is_done() {
2251                    warn!(
2252                        target: LOG_CLIENT_RECOVERY,
2253                        module_instance_id,
2254                        "Module bypassed the sanctioned recovery progress reporting API and reported a none recovery progress, regressing its previous one. Ignoring"
2255                    );
2256                    continue;
2257                }
2258            }
2259
2260            let mut dbtx = db.begin_transaction().await;
2261
2262            // The recovered amount is only known once the module's recovery
2263            // future resolves, which is also the only way progress transitions
2264            // to "done": the guard above rejects a completed progress reported
2265            // by a module, so `RecoveryUpdate::Completed` stays the only
2266            // producer of a done progress, and done therefore implies success.
2267            let (progress, recovered_amount) = if prev_progress.is_done() {
2268                // since updates might be out of order, once done, stick with it
2269                (prev_progress, None)
2270            } else {
2271                match update {
2272                    RecoveryUpdate::Progress(progress) => (progress, None),
2273                    RecoveryUpdate::Completed(amount) => (prev_progress.to_complete(), amount),
2274                }
2275            };
2276
2277            if !prev_progress.is_done() && progress.is_done() {
2278                info!(
2279                    target: LOG_CLIENT,
2280                    module_instance_id,
2281                    progress = format!("{}/{}", progress.complete, progress.total),
2282                    amount = ?recovered_amount,
2283                    "Recovery complete"
2284                );
2285                dbtx.log_event(
2286                    log_ordering_wakeup_tx.clone(),
2287                    None,
2288                    ModuleRecoveryCompleted {
2289                        module_id: module_instance_id,
2290                        kind: module_kinds.get(&module_instance_id).cloned(),
2291                        amount: recovered_amount,
2292                    },
2293                )
2294                .await;
2295            } else {
2296                info!(
2297                    target: LOG_CLIENT,
2298                    module_instance_id,
2299                    kind = ?module_kinds.get(&module_instance_id),
2300                    progress = format!("{}/{}", progress.complete, progress.total),
2301                    "Recovery progress"
2302                );
2303            }
2304
2305            dbtx.insert_entry(
2306                &ClientModuleRecovery { module_instance_id },
2307                &ClientModuleRecoveryState { progress },
2308            )
2309            .await;
2310            dbtx.commit_tx().await;
2311
2312            recovery_sender.send_modify(|statuses| {
2313                statuses.insert(module_instance_id, RecoveryStatus::InProgress(progress));
2314            });
2315        }
2316        debug!(target: LOG_CLIENT_RECOVERY, "Recovery executor stopped");
2317    }
2318
2319    async fn load_peers_last_api_versions(
2320        db: &Database,
2321        num_peers: NumPeers,
2322    ) -> BTreeMap<PeerId, SupportedApiVersionsSummary> {
2323        let mut peer_api_version_sets = BTreeMap::new();
2324
2325        let mut dbtx = db.begin_transaction_nc().await;
2326        for peer_id in num_peers.peer_ids() {
2327            if let Some(v) = dbtx
2328                .get_value(&PeerLastApiVersionsSummaryKey(peer_id))
2329                .await
2330            {
2331                peer_api_version_sets.insert(peer_id, v.0);
2332            }
2333        }
2334        drop(dbtx);
2335        peer_api_version_sets
2336    }
2337
2338    /// You likely want to use [`Client::get_peer_urls`]. This function returns
2339    /// only the announcements and doesn't use the config as fallback.
2340    pub async fn get_peer_url_announcements(&self) -> BTreeMap<PeerId, SignedApiAnnouncement> {
2341        self.db()
2342            .begin_transaction_nc()
2343            .await
2344            .find_by_prefix(&ApiAnnouncementPrefix)
2345            .await
2346            .map(|(announcement_key, announcement)| (announcement_key.0, announcement))
2347            .collect()
2348            .await
2349    }
2350
2351    /// Returns guardian metadata stored in the client database
2352    pub async fn get_guardian_metadata(
2353        &self,
2354    ) -> BTreeMap<PeerId, fedimint_core::net::guardian_metadata::SignedGuardianMetadata> {
2355        self.db()
2356            .begin_transaction_nc()
2357            .await
2358            .find_by_prefix(&crate::guardian_metadata::GuardianMetadataPrefix)
2359            .await
2360            .map(|(key, metadata)| (key.0, metadata))
2361            .collect()
2362            .await
2363    }
2364
2365    /// Returns a list of guardian API URLs
2366    pub async fn get_peer_urls(&self) -> BTreeMap<PeerId, SafeUrl> {
2367        get_api_urls(&self.db, &self.config().await, self.iroh_enable_next).await
2368    }
2369
2370    /// Create an invite code with the api endpoint of the given peer which can
2371    /// be used to download this client config
2372    pub async fn invite_code(&self, peer: PeerId) -> Option<InviteCode> {
2373        self.get_peer_urls()
2374            .await
2375            .into_iter()
2376            .find_map(|(peer_id, url)| (peer == peer_id).then_some(url))
2377            .map(|peer_url| {
2378                InviteCode::new(
2379                    peer_url.clone(),
2380                    peer,
2381                    self.federation_id(),
2382                    self.api_secret.clone(),
2383                )
2384            })
2385    }
2386
2387    /// Blocks till the client has synced the guardian public key set
2388    /// (introduced in version 0.4) and returns it. Once it has been fetched
2389    /// once this function is guaranteed to return immediately.
2390    pub async fn get_guardian_public_keys_blocking(
2391        &self,
2392    ) -> BTreeMap<PeerId, fedimint_core::secp256k1::PublicKey> {
2393        self.db
2394            .autocommit(
2395                |dbtx, _| {
2396                    Box::pin(async move {
2397                        let config = self.config().await;
2398
2399                        let guardian_pub_keys = self
2400                            .get_or_backfill_broadcast_public_keys(dbtx, config)
2401                            .await;
2402
2403                        Result::<_, ()>::Ok(guardian_pub_keys)
2404                    })
2405                },
2406                None,
2407            )
2408            .await
2409            .expect("Will retry forever")
2410    }
2411
2412    async fn get_or_backfill_broadcast_public_keys(
2413        &self,
2414        dbtx: &mut DatabaseTransaction<'_>,
2415        config: ClientConfig,
2416    ) -> BTreeMap<PeerId, PublicKey> {
2417        match config.global.broadcast_public_keys {
2418            Some(guardian_pub_keys) => guardian_pub_keys,
2419            _ => {
2420                let (guardian_pub_keys, new_config) = self.fetch_and_update_config(config).await;
2421
2422                dbtx.insert_entry(&ClientConfigKey, &new_config).await;
2423                *(self.config.write().await) = new_config;
2424                guardian_pub_keys
2425            }
2426        }
2427    }
2428
2429    pub async fn fetch_session_count(&self) -> FederationResult<u64> {
2430        self.api.session_count().await
2431    }
2432
2433    async fn fetch_and_update_config(
2434        &self,
2435        config: ClientConfig,
2436    ) -> (BTreeMap<PeerId, PublicKey>, ClientConfig) {
2437        let fetched_config = retry(
2438            "Fetching guardian public keys",
2439            backoff_util::background_backoff(),
2440            || async {
2441                Ok(self
2442                    .api
2443                    .request_current_consensus::<ClientConfig>(
2444                        CLIENT_CONFIG_ENDPOINT.to_owned(),
2445                        ApiRequestErased::default(),
2446                    )
2447                    .await?)
2448            },
2449        )
2450        .await
2451        .expect("Will never return on error");
2452
2453        let Some(guardian_pub_keys) = fetched_config.global.broadcast_public_keys else {
2454            warn!(
2455                target: LOG_CLIENT,
2456                "Guardian public keys not found in fetched config, server not updated to 0.4 yet"
2457            );
2458            pending::<()>().await;
2459            unreachable!("Pending will never return");
2460        };
2461
2462        let new_config = ClientConfig {
2463            global: GlobalClientConfig {
2464                broadcast_public_keys: Some(guardian_pub_keys.clone()),
2465                ..config.global
2466            },
2467            modules: config.modules,
2468        };
2469        (guardian_pub_keys, new_config)
2470    }
2471
2472    pub fn handle_global_rpc(
2473        &self,
2474        method: String,
2475        params: serde_json::Value,
2476    ) -> BoxStream<'_, anyhow::Result<serde_json::Value>> {
2477        Box::pin(try_stream! {
2478            match method.as_str() {
2479                "get_balance" => {
2480                    let balance = self.get_balance_for_btc().await.unwrap_or_default();
2481                    yield serde_json::to_value(balance)?;
2482                }
2483                "subscribe_balance_changes" => {
2484                    let req: GetBalanceChangesRequest= serde_json::from_value(params)?;
2485                    let mut stream = self.subscribe_balance_changes(req.unit).await;
2486                    while let Some(balance) = stream.next().await {
2487                        yield serde_json::to_value(balance)?;
2488                    }
2489                }
2490                "get_config" => {
2491                    let config = self.config().await;
2492                    yield serde_json::to_value(config)?;
2493                }
2494                "get_federation_id" => {
2495                    let federation_id = self.federation_id();
2496                    yield serde_json::to_value(federation_id)?;
2497                }
2498                "get_invite_code" => {
2499                    let req: GetInviteCodeRequest = serde_json::from_value(params)?;
2500                    let invite_code = self.invite_code(req.peer).await;
2501                    yield serde_json::to_value(invite_code)?;
2502                }
2503                "get_operation" => {
2504                    let req: GetOperationIdRequest = serde_json::from_value(params)?;
2505                    let operation = self.operation_log().get_operation(req.operation_id).await;
2506                    yield serde_json::to_value(operation)?;
2507                }
2508                "list_operations" => {
2509                    let req: ListOperationsParams = serde_json::from_value(params)?;
2510                    let limit = if req.limit.is_none() && req.last_seen.is_none() {
2511                        usize::MAX
2512                    } else {
2513                        req.limit.unwrap_or(usize::MAX)
2514                    };
2515                    let operations = self.operation_log()
2516                        .paginate_operations_rev(limit, req.last_seen)
2517                        .await;
2518                    yield serde_json::to_value(operations)?;
2519                }
2520                "get_event_log" => {
2521                    let req: GetEventLogRequest = serde_json::from_value(params)?;
2522                    let limit = req
2523                        .limit
2524                        .unwrap_or(DEFAULT_EVENT_LOG_PAGE_SIZE)
2525                        .min(MAX_EVENT_LOG_PAGE_SIZE);
2526                    let events = self.get_event_log(req.pos, limit).await;
2527                    yield serde_json::to_value(events)?;
2528                }
2529                "session_count" => {
2530                    let count = self.fetch_session_count().await?;
2531                    yield serde_json::to_value(count)?;
2532                }
2533                "has_pending_recoveries" => {
2534                    let has_pending = self.has_pending_recoveries();
2535                    yield serde_json::to_value(has_pending)?;
2536                }
2537                "wait_for_all_recoveries" => {
2538                    self.wait_for_all_recoveries().await?;
2539                    yield serde_json::Value::Null;
2540                }
2541                "subscribe_to_recovery_progress" => {
2542                    let mut stream = self.subscribe_to_recovery_progress();
2543                    while let Some((module_id, progress)) = stream.next().await {
2544                        yield serde_json::json!({
2545                            "module_id": module_id,
2546                            "progress": progress
2547                        });
2548                    }
2549                }
2550                #[allow(deprecated)]
2551                "backup_to_federation" => {
2552                    let metadata = if params.is_null() {
2553                        Metadata::from_json_serialized(serde_json::json!({}))
2554                    } else {
2555                        Metadata::from_json_serialized(params)
2556                    };
2557                    self.backup_to_federation(metadata).await?;
2558                    yield serde_json::Value::Null;
2559                }
2560                _ => {
2561                    Err(anyhow::format_err!("Unknown method: {}", method))?;
2562                    unreachable!()
2563                },
2564            }
2565        })
2566    }
2567
2568    pub async fn log_event<E>(&self, module_id: Option<ModuleInstanceId>, event: E)
2569    where
2570        E: Event + Send,
2571    {
2572        let mut dbtx = self.db.begin_transaction().await;
2573        self.log_event_dbtx(&mut dbtx, module_id, event).await;
2574        dbtx.commit_tx().await;
2575    }
2576
2577    pub async fn log_event_dbtx<E, Cap>(
2578        &self,
2579        dbtx: &mut DatabaseTransaction<'_, Cap>,
2580        module_id: Option<ModuleInstanceId>,
2581        event: E,
2582    ) where
2583        E: Event + Send,
2584        Cap: Send,
2585    {
2586        dbtx.log_event(self.log_ordering_wakeup_tx.clone(), module_id, event)
2587            .await;
2588    }
2589
2590    pub async fn log_event_raw_dbtx<Cap>(
2591        &self,
2592        dbtx: &mut DatabaseTransaction<'_, Cap>,
2593        kind: EventKind,
2594        module: Option<(ModuleKind, ModuleInstanceId)>,
2595        payload: Vec<u8>,
2596        persist: EventPersistence,
2597    ) where
2598        Cap: Send,
2599    {
2600        let module_id = module.as_ref().map(|m| m.1);
2601        let module_kind = module.map(|m| m.0);
2602        dbtx.log_event_raw(
2603            self.log_ordering_wakeup_tx.clone(),
2604            kind,
2605            module_kind,
2606            module_id,
2607            payload,
2608            persist,
2609        )
2610        .await;
2611    }
2612
2613    /// Built in event log (trimmable) tracker
2614    ///
2615    /// For the convenience of downstream applications, [`Client`] can store
2616    /// internally event log position for the main application using/driving it.
2617    ///
2618    /// Note that this position is a singleton, so this tracker should not be
2619    /// used for multiple purposes or applications, etc. at the same time.
2620    ///
2621    /// If the application has a need to follow log using multiple trackers, it
2622    /// should implement own [`DynEventLogTrimableTracker`] and store its
2623    /// persient data by itself.
2624    pub fn built_in_application_event_log_tracker(&self) -> DynEventLogTrimableTracker {
2625        struct BuiltInApplicationEventLogTracker;
2626
2627        #[apply(async_trait_maybe_send!)]
2628        impl EventLogTrimableTracker for BuiltInApplicationEventLogTracker {
2629            // Store position in the event log
2630            async fn store(
2631                &mut self,
2632                dbtx: &mut DatabaseTransaction<NonCommittable>,
2633                pos: EventLogTrimableId,
2634            ) -> anyhow::Result<()> {
2635                dbtx.insert_entry(&DefaultApplicationEventLogKey, &pos)
2636                    .await;
2637                Ok(())
2638            }
2639
2640            /// Load the last previous stored position (or None if never stored)
2641            async fn load(
2642                &mut self,
2643                dbtx: &mut DatabaseTransaction<NonCommittable>,
2644            ) -> anyhow::Result<Option<EventLogTrimableId>> {
2645                Ok(dbtx.get_value(&DefaultApplicationEventLogKey).await)
2646            }
2647        }
2648        Box::new(BuiltInApplicationEventLogTracker)
2649    }
2650
2651    /// Like [`Self::handle_events`] but for historical data.
2652    ///
2653    ///
2654    /// This function can be used to process subset of events
2655    /// that is infrequent and important enough to be persisted
2656    /// forever. Most applications should prefer to use [`Self::handle_events`]
2657    /// which emits *all* events.
2658    pub async fn handle_historical_events<F, R>(
2659        &self,
2660        tracker: fedimint_eventlog::DynEventLogTracker,
2661        handler_fn: F,
2662    ) -> anyhow::Result<()>
2663    where
2664        F: Fn(&mut DatabaseTransaction<NonCommittable>, EventLogEntry) -> R,
2665        R: Future<Output = anyhow::Result<()>>,
2666    {
2667        fedimint_eventlog::handle_events(
2668            self.db.clone(),
2669            tracker,
2670            self.log_event_added_rx.clone(),
2671            handler_fn,
2672        )
2673        .await
2674    }
2675
2676    /// Handle events emitted by the client
2677    ///
2678    /// This is a preferred method for reactive & asynchronous
2679    /// processing of events emitted by the client.
2680    ///
2681    /// It needs a `tracker` that will persist the position in the log
2682    /// as it is being handled. You can use the
2683    /// [`Client::built_in_application_event_log_tracker`] if this call is
2684    /// used for the single main application handling this instance of the
2685    /// [`Client`]. Otherwise you should implement your own tracker.
2686    ///
2687    /// This handler will call `handle_fn` with ever event emitted by
2688    /// [`Client`], including transient ones. The caller should atomically
2689    /// handle each event it is interested in and ignore other ones.
2690    ///
2691    /// This method returns only when client is shutting down or on internal
2692    /// error, so typically should be called in a background task dedicated
2693    /// to handling events.
2694    pub async fn handle_events<F, R>(
2695        &self,
2696        tracker: fedimint_eventlog::DynEventLogTrimableTracker,
2697        handler_fn: F,
2698    ) -> anyhow::Result<()>
2699    where
2700        F: Fn(&mut DatabaseTransaction<NonCommittable>, EventLogEntry) -> R,
2701        R: Future<Output = anyhow::Result<()>>,
2702    {
2703        fedimint_eventlog::handle_trimable_events(
2704            self.db.clone(),
2705            tracker,
2706            self.log_event_added_rx.clone(),
2707            handler_fn,
2708        )
2709        .await
2710    }
2711
2712    pub async fn get_event_log(
2713        &self,
2714        pos: Option<EventLogId>,
2715        limit: u64,
2716    ) -> Vec<PersistedLogEntry> {
2717        self.get_event_log_dbtx(&mut self.db.begin_transaction_nc().await, pos, limit)
2718            .await
2719    }
2720
2721    /// Returns the id that the next entry appended to the event log will be
2722    /// assigned, i.e. the position just past the current end of the log.
2723    pub async fn get_next_event_log_id(&self) -> EventLogId {
2724        self.db
2725            .begin_transaction_nc()
2726            .await
2727            .get_next_event_log_id()
2728            .await
2729    }
2730
2731    pub async fn get_event_log_trimable(
2732        &self,
2733        pos: Option<EventLogTrimableId>,
2734        limit: u64,
2735    ) -> Vec<PersistedLogEntry> {
2736        self.get_event_log_trimable_dbtx(&mut self.db.begin_transaction_nc().await, pos, limit)
2737            .await
2738    }
2739
2740    pub async fn get_event_log_dbtx<Cap>(
2741        &self,
2742        dbtx: &mut DatabaseTransaction<'_, Cap>,
2743        pos: Option<EventLogId>,
2744        limit: u64,
2745    ) -> Vec<PersistedLogEntry>
2746    where
2747        Cap: Send,
2748    {
2749        dbtx.get_event_log(pos, limit).await
2750    }
2751
2752    pub async fn get_event_log_trimable_dbtx<Cap>(
2753        &self,
2754        dbtx: &mut DatabaseTransaction<'_, Cap>,
2755        pos: Option<EventLogTrimableId>,
2756        limit: u64,
2757    ) -> Vec<PersistedLogEntry>
2758    where
2759        Cap: Send,
2760    {
2761        dbtx.get_event_log_trimable(pos, limit).await
2762    }
2763
2764    /// Register to receiver all new transient (unpersisted) events
2765    pub fn get_event_log_transient_receiver(&self) -> broadcast::Receiver<EventLogEntry> {
2766        self.log_event_added_transient_tx.subscribe()
2767    }
2768
2769    /// Get a receiver that signals when new events are added to the event log
2770    pub fn log_event_added_rx(&self) -> watch::Receiver<()> {
2771        self.log_event_added_rx.clone()
2772    }
2773
2774    pub fn iroh_enable_dht(&self) -> bool {
2775        self.iroh_enable_dht
2776    }
2777
2778    /// Whether compatible iroh-next endpoints from guardian metadata are
2779    /// preferred.
2780    pub fn iroh_enable_next(&self) -> bool {
2781        self.iroh_enable_next
2782    }
2783
2784    pub(crate) async fn run_core_migrations(
2785        db_no_decoders: &Database,
2786    ) -> Result<(), anyhow::Error> {
2787        let mut dbtx = db_no_decoders.begin_transaction().await;
2788        apply_migrations_core_client_dbtx(&mut dbtx.to_ref_nc(), "fedimint-client".to_string())
2789            .await?;
2790        if is_running_in_test_env() {
2791            verify_client_db_integrity_dbtx(&mut dbtx.to_ref_nc()).await;
2792        }
2793        dbtx.commit_tx_result().await?;
2794        Ok(())
2795    }
2796
2797    /// Iterator over primary modules for a given `unit`
2798    fn primary_modules_for_unit(
2799        &self,
2800        unit: AmountUnit,
2801    ) -> impl Iterator<Item = (ModuleInstanceId, &DynClientModule)> {
2802        self.primary_modules
2803            .iter()
2804            .flat_map(move |(_prio, candidates)| {
2805                candidates
2806                    .specific
2807                    .get(&unit)
2808                    .into_iter()
2809                    .flatten()
2810                    .copied()
2811                    // within same priority, wildcard matches come last
2812                    .chain(candidates.wildcard.iter().copied())
2813            })
2814            .map(|id| (id, self.modules.get_expect(id)))
2815    }
2816
2817    /// Primary module to use for `unit`
2818    ///
2819    /// Currently, just pick the first (highest priority) match
2820    pub fn primary_module_for_unit(
2821        &self,
2822        unit: AmountUnit,
2823    ) -> Option<(ModuleInstanceId, &DynClientModule)> {
2824        self.primary_modules_for_unit(unit).next()
2825    }
2826
2827    /// [`Self::primary_module_for_unit`] for Bitcoin
2828    pub fn primary_module_for_btc(&self) -> (ModuleInstanceId, &DynClientModule) {
2829        self.primary_module_for_unit(AmountUnit::BITCOIN)
2830            .expect("No primary module for Bitcoin")
2831    }
2832}
2833
2834#[apply(async_trait_maybe_send!)]
2835impl ClientContextIface for Client {
2836    fn get_module(&self, instance: ModuleInstanceId) -> &maybe_add_send_sync!(dyn IClientModule) {
2837        Client::get_module(self, instance)
2838    }
2839
2840    fn api_clone(&self) -> DynGlobalApi {
2841        Client::api_clone(self)
2842    }
2843    fn decoders(&self) -> &ModuleDecoderRegistry {
2844        Client::decoders(self)
2845    }
2846
2847    async fn finalize_and_submit_transaction(
2848        &self,
2849        operation_id: OperationId,
2850        operation_type: &str,
2851        operation_meta_gen: Box<maybe_add_send_sync!(dyn Fn(OutPointRange) -> serde_json::Value)>,
2852        tx_builder: TransactionBuilder,
2853    ) -> anyhow::Result<OutPointRange> {
2854        Client::finalize_and_submit_transaction(
2855            self,
2856            operation_id,
2857            operation_type,
2858            // |out_point_range| operation_meta_gen(out_point_range),
2859            &operation_meta_gen,
2860            tx_builder,
2861        )
2862        .await
2863    }
2864
2865    async fn finalize_and_submit_transaction_dbtx(
2866        &self,
2867        dbtx: &mut DatabaseTransaction<'_>,
2868        operation_id: OperationId,
2869        operation_type: &str,
2870        operation_meta_gen: Box<maybe_add_send_sync!(dyn Fn(OutPointRange) -> serde_json::Value)>,
2871        tx_builder: TransactionBuilder,
2872    ) -> anyhow::Result<OutPointRange> {
2873        Client::finalize_and_submit_transaction_dbtx(
2874            self,
2875            dbtx,
2876            operation_id,
2877            operation_type,
2878            &operation_meta_gen,
2879            tx_builder,
2880        )
2881        .await
2882    }
2883
2884    async fn finalize_and_submit_transaction_inner(
2885        &self,
2886        dbtx: &mut DatabaseTransaction<'_>,
2887        operation_id: OperationId,
2888        tx_builder: TransactionBuilder,
2889    ) -> anyhow::Result<OutPointRange> {
2890        Client::finalize_and_submit_transaction_inner(self, dbtx, operation_id, tx_builder).await
2891    }
2892
2893    async fn fee_quote(
2894        &self,
2895        operation_id: OperationId,
2896        request: FeeQuoteRequest,
2897    ) -> anyhow::Result<FeeQuote> {
2898        Client::fee_quote(self, operation_id, request).await
2899    }
2900
2901    async fn get_balance_for_unit(&self, unit: AmountUnit) -> anyhow::Result<Amount> {
2902        Client::get_balance_for_unit(self, unit).await
2903    }
2904
2905    async fn transaction_updates(&self, operation_id: OperationId) -> TransactionUpdates {
2906        Client::transaction_updates(self, operation_id).await
2907    }
2908
2909    async fn await_primary_module_outputs(
2910        &self,
2911        operation_id: OperationId,
2912        // TODO: make `impl Iterator<Item = ...>`
2913        outputs: Vec<OutPoint>,
2914    ) -> anyhow::Result<()> {
2915        Client::await_primary_bitcoin_module_outputs(self, operation_id, outputs).await
2916    }
2917
2918    fn operation_log(&self) -> &dyn IOperationLog {
2919        Client::operation_log(self)
2920    }
2921
2922    async fn has_active_states(&self, operation_id: OperationId) -> bool {
2923        Client::has_active_states(self, operation_id).await
2924    }
2925
2926    async fn operation_exists(&self, operation_id: OperationId) -> bool {
2927        Client::operation_exists(self, operation_id).await
2928    }
2929
2930    async fn config(&self) -> ClientConfig {
2931        Client::config(self).await
2932    }
2933
2934    fn db(&self) -> &Database {
2935        Client::db(self)
2936    }
2937
2938    fn executor(&self) -> &(maybe_add_send_sync!(dyn IExecutor + 'static)) {
2939        Client::executor(self)
2940    }
2941
2942    async fn invite_code(&self, peer: PeerId) -> Option<InviteCode> {
2943        Client::invite_code(self, peer).await
2944    }
2945
2946    fn get_internal_payment_markers(&self) -> anyhow::Result<(PublicKey, u64)> {
2947        Client::get_internal_payment_markers(self)
2948    }
2949
2950    async fn log_event_json(
2951        &self,
2952        dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
2953        module_kind: Option<ModuleKind>,
2954        module_id: ModuleInstanceId,
2955        kind: EventKind,
2956        payload: serde_json::Value,
2957        persist: EventPersistence,
2958    ) {
2959        dbtx.ensure_global()
2960            .expect("Must be called with global dbtx");
2961        self.log_event_raw_dbtx(
2962            dbtx,
2963            kind,
2964            module_kind.map(|kind| (kind, module_id)),
2965            serde_json::to_vec(&payload).expect("Serialization can't fail"),
2966            persist,
2967        )
2968        .await;
2969    }
2970
2971    async fn read_operation_active_states<'dbtx>(
2972        &self,
2973        operation_id: OperationId,
2974        module_id: ModuleInstanceId,
2975        dbtx: &'dbtx mut DatabaseTransaction<'_>,
2976    ) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (ActiveStateKey, ActiveStateMeta)> + 'dbtx)>>
2977    {
2978        Box::pin(
2979            dbtx.find_by_prefix(&ActiveModuleOperationStateKeyPrefix {
2980                operation_id,
2981                module_instance: module_id,
2982            })
2983            .await
2984            .map(move |(k, v)| (k.0, v)),
2985        )
2986    }
2987    async fn read_operation_inactive_states<'dbtx>(
2988        &self,
2989        operation_id: OperationId,
2990        module_id: ModuleInstanceId,
2991        dbtx: &'dbtx mut DatabaseTransaction<'_>,
2992    ) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (InactiveStateKey, InactiveStateMeta)> + 'dbtx)>>
2993    {
2994        Box::pin(
2995            dbtx.find_by_prefix(&InactiveModuleOperationStateKeyPrefix {
2996                operation_id,
2997                module_instance: module_id,
2998            })
2999            .await
3000            .map(move |(k, v)| (k.0, v)),
3001        )
3002    }
3003}
3004
3005// TODO: impl `Debug` for `Client` and derive here
3006impl fmt::Debug for Client {
3007    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
3008        write!(f, "Client")
3009    }
3010}
3011
3012pub fn client_decoders<'a>(
3013    registry: &ModuleInitRegistry<DynClientModuleInit>,
3014    module_kinds: impl Iterator<Item = (ModuleInstanceId, &'a ModuleKind)>,
3015) -> ModuleDecoderRegistry {
3016    let mut modules = BTreeMap::new();
3017    for (id, kind) in module_kinds {
3018        let Some(init) = registry.get(kind) else {
3019            debug!("Detected configuration for unsupported module id: {id}, kind: {kind}");
3020            continue;
3021        };
3022
3023        modules.insert(
3024            id,
3025            (
3026                kind.clone(),
3027                IClientModuleInit::decoder(AsRef::<dyn IClientModuleInit + 'static>::as_ref(init)),
3028            ),
3029        );
3030    }
3031    ModuleDecoderRegistry::from(modules)
3032}