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    /// Wait for all module recoveries to finish
1937    ///
1938    /// Returns `Ok(())` once every module recovery completed, or an error as
1939    /// soon as any one of them fails terminally.
1940    ///
1941    /// An error does not mean the recovery task is done: the failed module's
1942    /// progress stays pending forever (so [`Self::has_pending_recoveries`]
1943    /// keeps returning `true`) and the recovery task stays parked. The
1944    /// failure is in-memory only and is not persisted, so reopening the
1945    /// client retries the recovery from its last persisted, non-terminal
1946    /// progress.
1947    ///
1948    /// A bit of a heavy approach.
1949    pub async fn wait_for_all_recoveries(&self) -> anyhow::Result<()> {
1950        Self::wait_for_recoveries(
1951            self.client_recovery_status_receiver.clone(),
1952            |_module_instance_id| true,
1953            "Recovery task completed and update receiver disconnected, but some modules failed to recover",
1954        )
1955        .await
1956    }
1957
1958    /// Wait for the recovery of every module accepted by `module_filter` to
1959    /// either complete or fail.
1960    ///
1961    /// Since [`RecoveryProgress`] can never express a failure, waiting on
1962    /// progress alone would block forever on a module that gave up. A module
1963    /// that gave up is recorded as [`RecoveryStatus::Failed`] by
1964    /// [`Self::run_module_recoveries_task`] instead, so both outcomes are
1965    /// observable on the same per-module status.
1966    async fn wait_for_recoveries(
1967        mut status_receiver: watch::Receiver<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
1968        module_filter: impl Fn(ModuleInstanceId) -> bool,
1969        disconnected_context: &'static str,
1970    ) -> anyhow::Result<()> {
1971        let failure = status_receiver
1972            .wait_for(|statuses| {
1973                let matching = || {
1974                    statuses
1975                        .iter()
1976                        .filter(|(module_instance_id, _status)| module_filter(**module_instance_id))
1977                        .map(|(_module_instance_id, status)| status)
1978                };
1979
1980                // A failure is terminal, so waiting for the modules that are
1981                // still recovering would only delay an outcome that can no
1982                // longer change.
1983                matching().any(|status| matches!(status, RecoveryStatus::Failed { .. }))
1984                    || matching().all(RecoveryStatus::is_successfully_done)
1985            })
1986            .await
1987            .context(disconnected_context)?
1988            // Classified from the woken-up snapshot before anything else, so a
1989            // failure of one module still wins over another one completing.
1990            .iter()
1991            .find_map(|(module_instance_id, status)| match status {
1992                RecoveryStatus::Failed { error, .. } if module_filter(*module_instance_id) => {
1993                    Some((*module_instance_id, error.clone()))
1994                }
1995                _ => None,
1996            });
1997
1998        match failure {
1999            Some((module_instance_id, error)) => Err(anyhow!(
2000                "Module recovery failed: module_instance_id={module_instance_id}, error={error}"
2001            )),
2002            None => Ok(()),
2003        }
2004    }
2005
2006    /// Subscribe to recover progress for all the modules.
2007    ///
2008    /// This stream can contain duplicate progress for a module.
2009    /// Don't use this stream for detecting completion of recovery.
2010    ///
2011    /// It can't express a failure either: a module that failed to recover keeps
2012    /// being reported with the last progress it made, which is never done. Use
2013    /// [`Self::wait_for_all_recoveries`] or
2014    /// [`Self::wait_for_module_kind_recovery`] to learn the outcome.
2015    pub fn subscribe_to_recovery_progress(
2016        &self,
2017    ) -> impl Stream<Item = (ModuleInstanceId, RecoveryProgress)> + use<> {
2018        WatchStream::new(self.client_recovery_status_receiver.clone()).flat_map(|statuses| {
2019            futures::stream::iter(
2020                statuses
2021                    .into_iter()
2022                    .map(|(module_instance_id, status)| (module_instance_id, status.progress())),
2023            )
2024        })
2025    }
2026
2027    /// Wait for the recoveries of all modules of `module_kind` to finish
2028    ///
2029    /// Returns `Ok(())` once every recovery of that kind completed, or an error
2030    /// as soon as one of them fails terminally. Failures of other module kinds
2031    /// are ignored.
2032    ///
2033    /// See [`Self::wait_for_all_recoveries`] for what an error does and does
2034    /// not say about the state of the recovery.
2035    pub async fn wait_for_module_kind_recovery(
2036        &self,
2037        module_kind: ModuleKind,
2038    ) -> anyhow::Result<()> {
2039        let config = self.config().await;
2040        Self::wait_for_recoveries(
2041            self.client_recovery_status_receiver.clone(),
2042            move |module_instance_id| {
2043                config
2044                    .modules
2045                    .get(&module_instance_id)
2046                    .is_some_and(|module| module.kind == module_kind)
2047            },
2048            "Recovery task completed and update receiver disconnected, but the desired modules are still unavailable or failed to recover",
2049        )
2050        .await
2051    }
2052
2053    pub async fn wait_for_all_active_state_machines(&self) -> anyhow::Result<()> {
2054        loop {
2055            if self.executor.get_active_states().await.is_empty() {
2056                break;
2057            }
2058            sleep(Duration::from_millis(100)).await;
2059        }
2060        Ok(())
2061    }
2062
2063    /// Set the client [`Metadata`]
2064    pub async fn set_metadata_dbtx(dbtx: &mut DatabaseTransaction<'_>, metadata: &Metadata) {
2065        dbtx.insert_new_entry(&ClientMetadataKey, metadata).await;
2066    }
2067
2068    fn spawn_module_recoveries_task(
2069        &self,
2070        recovery_sender: watch::Sender<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
2071        module_recoveries: BTreeMap<ModuleInstanceId, ModuleRecoveryFuture>,
2072        module_recovery_progress_receivers: BTreeMap<
2073            ModuleInstanceId,
2074            watch::Receiver<RecoveryProgress>,
2075        >,
2076        // Sourced from the config rather than `self.modules`, since modules
2077        // currently being recovered are not yet initialized in the registry.
2078        module_kinds: BTreeMap<ModuleInstanceId, ModuleKind>,
2079    ) {
2080        let db = self.db.clone();
2081        let log_ordering_wakeup_tx = self.log_ordering_wakeup_tx.clone();
2082        // A module can finish its own final database commit before the client
2083        // persists the corresponding completed progress below. Keep the
2084        // coordinator alive across graceful shutdown so that gap cannot cause
2085        // a non-idempotent module finalization to be replayed on reopen.
2086        self.spawn("module recoveries", |_task_handle| async {
2087            Self::run_module_recoveries_task(
2088                db,
2089                log_ordering_wakeup_tx,
2090                recovery_sender,
2091                module_recoveries,
2092                module_recovery_progress_receivers,
2093                module_kinds,
2094            )
2095            .await;
2096        });
2097    }
2098
2099    async fn run_module_recoveries_task(
2100        db: Database,
2101        log_ordering_wakeup_tx: watch::Sender<()>,
2102        recovery_sender: watch::Sender<BTreeMap<ModuleInstanceId, RecoveryStatus>>,
2103        module_recoveries: BTreeMap<ModuleInstanceId, ModuleRecoveryFuture>,
2104        module_recovery_progress_receivers: BTreeMap<
2105            ModuleInstanceId,
2106            watch::Receiver<RecoveryProgress>,
2107        >,
2108        module_kinds: BTreeMap<ModuleInstanceId, ModuleKind>,
2109    ) {
2110        debug!(target: LOG_CLIENT_RECOVERY, num_modules=%module_recovery_progress_receivers.len(), "Staring module recoveries");
2111
2112        // A recovery update for a single module: either an intermediate progress
2113        // report, or the final completion carrying the recovered amount (if the
2114        // module tracks it).
2115        enum RecoveryUpdate {
2116            Progress(RecoveryProgress),
2117            Completed(Option<Amount>),
2118        }
2119
2120        let mut completed_stream = Vec::new();
2121        let progress_stream = futures::stream::FuturesUnordered::new();
2122
2123        for (module_instance_id, f) in module_recoveries {
2124            let recovery_sender = recovery_sender.clone();
2125            completed_stream.push(futures::stream::once(Box::pin(async move {
2126                match f.await {
2127                    Ok(amount) => (module_instance_id, RecoveryUpdate::Completed(amount)),
2128                    Err(err) => {
2129                        let error = err.fmt_compact_anyhow().to_string();
2130                        warn!(
2131                            target: LOG_CLIENT,
2132                            err = %error.as_str(), module_instance_id, "Module recovery failed"
2133                        );
2134                        // since the progress a module reports can't express a
2135                        // failure, record it as the terminal state of this
2136                        // module's recovery for anyone waiting on the outcome.
2137                        // Keyed by module instance so a later failure of
2138                        // another module can't overwrite this one before a
2139                        // waiter observes it.
2140                        recovery_sender.send_modify(|statuses| {
2141                            let last_progress = statuses
2142                                .get(&module_instance_id)
2143                                .expect("existing status must be present")
2144                                .progress();
2145                            statuses.insert(
2146                                module_instance_id,
2147                                RecoveryStatus::Failed {
2148                                    last_progress,
2149                                    error,
2150                                },
2151                            );
2152                        });
2153                        // The terminal failure is now published to the waiters,
2154                        // and this branch stays pending on purpose so the
2155                        // recovery coordinator and its single status sender
2156                        // remain alive. The failed module's progress never
2157                        // becomes done either, so observers that only see the
2158                        // progress keep treating the recovery as pending, which
2159                        // it effectively is. The failure is deliberately not
2160                        // persisted, so reopening the client retries the
2161                        // recovery.
2162                        futures::future::pending::<()>().await;
2163                        unreachable!()
2164                    }
2165                }
2166            })));
2167        }
2168
2169        for (module_instance_id, rx) in module_recovery_progress_receivers {
2170            progress_stream.push(
2171                tokio_stream::wrappers::WatchStream::new(rx)
2172                    .fuse()
2173                    .map(move |progress| (module_instance_id, RecoveryUpdate::Progress(progress))),
2174            );
2175        }
2176
2177        let mut futures = futures::stream::select(
2178            futures::stream::select_all(progress_stream),
2179            futures::stream::select_all(completed_stream),
2180        );
2181
2182        while let Some((module_instance_id, update)) = futures.next().await {
2183            // Cloned so the `watch::Ref` is released right here: holding it
2184            // across the awaits or the `send_modify` below would deadlock the
2185            // channel it borrows from.
2186            let prev_status = recovery_sender
2187                .borrow()
2188                .get(&module_instance_id)
2189                .expect("existing status must be present")
2190                .clone();
2191
2192            // A failure is the terminal state of a module's recovery, but
2193            // progress and completion are merged without any ordering between
2194            // them, so a stale progress update of that module can still arrive
2195            // after it. Applying it would overwrite the failure with an
2196            // in-progress status, and a waiter subscribing afterwards would
2197            // block forever again. Ignoring it entirely, without touching the
2198            // channel, also keeps subscribers from seeing a snapshot that says
2199            // nothing new. Mirrors the sticky "once done, stick with it"
2200            // handling below.
2201            if matches!(prev_status, RecoveryStatus::Failed { .. }) {
2202                debug!(
2203                    target: LOG_CLIENT_RECOVERY,
2204                    module_instance_id,
2205                    "Ignoring a recovery update of a module whose recovery already failed"
2206                );
2207                continue;
2208            }
2209
2210            let prev_progress = prev_status.progress();
2211
2212            // A module reports its progress on a channel it owns, so the values
2213            // arriving here are untrusted: `update_recovery_progress` filters
2214            // them, but a module can send on `progress_tx` directly. Reject the
2215            // values that would break the invariants downstream depends on
2216            // before anything is persisted or broadcast.
2217            if let RecoveryUpdate::Progress(progress) = &update {
2218                if progress.is_done() {
2219                    warn!(
2220                        target: LOG_CLIENT_RECOVERY,
2221                        module_instance_id,
2222                        "Module bypassed the sanctioned recovery progress reporting API and reported a completed recovery progress. Ignoring"
2223                    );
2224                    continue;
2225                }
2226
2227                // The module's channel starts at the progress the client seeded
2228                // it with, so a "none" that doesn't regress anything is the
2229                // normal start of a recovery, not a module misbehaving. Neither
2230                // is one seen after the module already completed: progress and
2231                // completion are merged without ordering between them, so a
2232                // seeded value can arrive after the completion it preceded.
2233                if progress.is_none() && !prev_progress.is_none() && !prev_progress.is_done() {
2234                    warn!(
2235                        target: LOG_CLIENT_RECOVERY,
2236                        module_instance_id,
2237                        "Module bypassed the sanctioned recovery progress reporting API and reported a none recovery progress, regressing its previous one. Ignoring"
2238                    );
2239                    continue;
2240                }
2241            }
2242
2243            let mut dbtx = db.begin_transaction().await;
2244
2245            // The recovered amount is only known once the module's recovery
2246            // future resolves, which is also the only way progress transitions
2247            // to "done": the guard above rejects a completed progress reported
2248            // by a module, so `RecoveryUpdate::Completed` stays the only
2249            // producer of a done progress, and done therefore implies success.
2250            let (progress, recovered_amount) = if prev_progress.is_done() {
2251                // since updates might be out of order, once done, stick with it
2252                (prev_progress, None)
2253            } else {
2254                match update {
2255                    RecoveryUpdate::Progress(progress) => (progress, None),
2256                    RecoveryUpdate::Completed(amount) => (prev_progress.to_complete(), amount),
2257                }
2258            };
2259
2260            if !prev_progress.is_done() && progress.is_done() {
2261                info!(
2262                    target: LOG_CLIENT,
2263                    module_instance_id,
2264                    progress = format!("{}/{}", progress.complete, progress.total),
2265                    amount = ?recovered_amount,
2266                    "Recovery complete"
2267                );
2268                dbtx.log_event(
2269                    log_ordering_wakeup_tx.clone(),
2270                    None,
2271                    ModuleRecoveryCompleted {
2272                        module_id: module_instance_id,
2273                        kind: module_kinds.get(&module_instance_id).cloned(),
2274                        amount: recovered_amount,
2275                    },
2276                )
2277                .await;
2278            } else {
2279                info!(
2280                    target: LOG_CLIENT,
2281                    module_instance_id,
2282                    kind = ?module_kinds.get(&module_instance_id),
2283                    progress = format!("{}/{}", progress.complete, progress.total),
2284                    "Recovery progress"
2285                );
2286            }
2287
2288            dbtx.insert_entry(
2289                &ClientModuleRecovery { module_instance_id },
2290                &ClientModuleRecoveryState { progress },
2291            )
2292            .await;
2293            dbtx.commit_tx().await;
2294
2295            recovery_sender.send_modify(|statuses| {
2296                statuses.insert(module_instance_id, RecoveryStatus::InProgress(progress));
2297            });
2298        }
2299        debug!(target: LOG_CLIENT_RECOVERY, "Recovery executor stopped");
2300    }
2301
2302    async fn load_peers_last_api_versions(
2303        db: &Database,
2304        num_peers: NumPeers,
2305    ) -> BTreeMap<PeerId, SupportedApiVersionsSummary> {
2306        let mut peer_api_version_sets = BTreeMap::new();
2307
2308        let mut dbtx = db.begin_transaction_nc().await;
2309        for peer_id in num_peers.peer_ids() {
2310            if let Some(v) = dbtx
2311                .get_value(&PeerLastApiVersionsSummaryKey(peer_id))
2312                .await
2313            {
2314                peer_api_version_sets.insert(peer_id, v.0);
2315            }
2316        }
2317        drop(dbtx);
2318        peer_api_version_sets
2319    }
2320
2321    /// You likely want to use [`Client::get_peer_urls`]. This function returns
2322    /// only the announcements and doesn't use the config as fallback.
2323    pub async fn get_peer_url_announcements(&self) -> BTreeMap<PeerId, SignedApiAnnouncement> {
2324        self.db()
2325            .begin_transaction_nc()
2326            .await
2327            .find_by_prefix(&ApiAnnouncementPrefix)
2328            .await
2329            .map(|(announcement_key, announcement)| (announcement_key.0, announcement))
2330            .collect()
2331            .await
2332    }
2333
2334    /// Returns guardian metadata stored in the client database
2335    pub async fn get_guardian_metadata(
2336        &self,
2337    ) -> BTreeMap<PeerId, fedimint_core::net::guardian_metadata::SignedGuardianMetadata> {
2338        self.db()
2339            .begin_transaction_nc()
2340            .await
2341            .find_by_prefix(&crate::guardian_metadata::GuardianMetadataPrefix)
2342            .await
2343            .map(|(key, metadata)| (key.0, metadata))
2344            .collect()
2345            .await
2346    }
2347
2348    /// Returns a list of guardian API URLs
2349    pub async fn get_peer_urls(&self) -> BTreeMap<PeerId, SafeUrl> {
2350        get_api_urls(&self.db, &self.config().await, self.iroh_enable_next).await
2351    }
2352
2353    /// Create an invite code with the api endpoint of the given peer which can
2354    /// be used to download this client config
2355    pub async fn invite_code(&self, peer: PeerId) -> Option<InviteCode> {
2356        self.get_peer_urls()
2357            .await
2358            .into_iter()
2359            .find_map(|(peer_id, url)| (peer == peer_id).then_some(url))
2360            .map(|peer_url| {
2361                InviteCode::new(
2362                    peer_url.clone(),
2363                    peer,
2364                    self.federation_id(),
2365                    self.api_secret.clone(),
2366                )
2367            })
2368    }
2369
2370    /// Blocks till the client has synced the guardian public key set
2371    /// (introduced in version 0.4) and returns it. Once it has been fetched
2372    /// once this function is guaranteed to return immediately.
2373    pub async fn get_guardian_public_keys_blocking(
2374        &self,
2375    ) -> BTreeMap<PeerId, fedimint_core::secp256k1::PublicKey> {
2376        self.db
2377            .autocommit(
2378                |dbtx, _| {
2379                    Box::pin(async move {
2380                        let config = self.config().await;
2381
2382                        let guardian_pub_keys = self
2383                            .get_or_backfill_broadcast_public_keys(dbtx, config)
2384                            .await;
2385
2386                        Result::<_, ()>::Ok(guardian_pub_keys)
2387                    })
2388                },
2389                None,
2390            )
2391            .await
2392            .expect("Will retry forever")
2393    }
2394
2395    async fn get_or_backfill_broadcast_public_keys(
2396        &self,
2397        dbtx: &mut DatabaseTransaction<'_>,
2398        config: ClientConfig,
2399    ) -> BTreeMap<PeerId, PublicKey> {
2400        match config.global.broadcast_public_keys {
2401            Some(guardian_pub_keys) => guardian_pub_keys,
2402            _ => {
2403                let (guardian_pub_keys, new_config) = self.fetch_and_update_config(config).await;
2404
2405                dbtx.insert_entry(&ClientConfigKey, &new_config).await;
2406                *(self.config.write().await) = new_config;
2407                guardian_pub_keys
2408            }
2409        }
2410    }
2411
2412    pub async fn fetch_session_count(&self) -> FederationResult<u64> {
2413        self.api.session_count().await
2414    }
2415
2416    async fn fetch_and_update_config(
2417        &self,
2418        config: ClientConfig,
2419    ) -> (BTreeMap<PeerId, PublicKey>, ClientConfig) {
2420        let fetched_config = retry(
2421            "Fetching guardian public keys",
2422            backoff_util::background_backoff(),
2423            || async {
2424                Ok(self
2425                    .api
2426                    .request_current_consensus::<ClientConfig>(
2427                        CLIENT_CONFIG_ENDPOINT.to_owned(),
2428                        ApiRequestErased::default(),
2429                    )
2430                    .await?)
2431            },
2432        )
2433        .await
2434        .expect("Will never return on error");
2435
2436        let Some(guardian_pub_keys) = fetched_config.global.broadcast_public_keys else {
2437            warn!(
2438                target: LOG_CLIENT,
2439                "Guardian public keys not found in fetched config, server not updated to 0.4 yet"
2440            );
2441            pending::<()>().await;
2442            unreachable!("Pending will never return");
2443        };
2444
2445        let new_config = ClientConfig {
2446            global: GlobalClientConfig {
2447                broadcast_public_keys: Some(guardian_pub_keys.clone()),
2448                ..config.global
2449            },
2450            modules: config.modules,
2451        };
2452        (guardian_pub_keys, new_config)
2453    }
2454
2455    pub fn handle_global_rpc(
2456        &self,
2457        method: String,
2458        params: serde_json::Value,
2459    ) -> BoxStream<'_, anyhow::Result<serde_json::Value>> {
2460        Box::pin(try_stream! {
2461            match method.as_str() {
2462                "get_balance" => {
2463                    let balance = self.get_balance_for_btc().await.unwrap_or_default();
2464                    yield serde_json::to_value(balance)?;
2465                }
2466                "subscribe_balance_changes" => {
2467                    let req: GetBalanceChangesRequest= serde_json::from_value(params)?;
2468                    let mut stream = self.subscribe_balance_changes(req.unit).await;
2469                    while let Some(balance) = stream.next().await {
2470                        yield serde_json::to_value(balance)?;
2471                    }
2472                }
2473                "get_config" => {
2474                    let config = self.config().await;
2475                    yield serde_json::to_value(config)?;
2476                }
2477                "get_federation_id" => {
2478                    let federation_id = self.federation_id();
2479                    yield serde_json::to_value(federation_id)?;
2480                }
2481                "get_invite_code" => {
2482                    let req: GetInviteCodeRequest = serde_json::from_value(params)?;
2483                    let invite_code = self.invite_code(req.peer).await;
2484                    yield serde_json::to_value(invite_code)?;
2485                }
2486                "get_operation" => {
2487                    let req: GetOperationIdRequest = serde_json::from_value(params)?;
2488                    let operation = self.operation_log().get_operation(req.operation_id).await;
2489                    yield serde_json::to_value(operation)?;
2490                }
2491                "list_operations" => {
2492                    let req: ListOperationsParams = serde_json::from_value(params)?;
2493                    let limit = if req.limit.is_none() && req.last_seen.is_none() {
2494                        usize::MAX
2495                    } else {
2496                        req.limit.unwrap_or(usize::MAX)
2497                    };
2498                    let operations = self.operation_log()
2499                        .paginate_operations_rev(limit, req.last_seen)
2500                        .await;
2501                    yield serde_json::to_value(operations)?;
2502                }
2503                "get_event_log" => {
2504                    let req: GetEventLogRequest = serde_json::from_value(params)?;
2505                    let limit = req
2506                        .limit
2507                        .unwrap_or(DEFAULT_EVENT_LOG_PAGE_SIZE)
2508                        .min(MAX_EVENT_LOG_PAGE_SIZE);
2509                    let events = self.get_event_log(req.pos, limit).await;
2510                    yield serde_json::to_value(events)?;
2511                }
2512                "session_count" => {
2513                    let count = self.fetch_session_count().await?;
2514                    yield serde_json::to_value(count)?;
2515                }
2516                "has_pending_recoveries" => {
2517                    let has_pending = self.has_pending_recoveries();
2518                    yield serde_json::to_value(has_pending)?;
2519                }
2520                "wait_for_all_recoveries" => {
2521                    self.wait_for_all_recoveries().await?;
2522                    yield serde_json::Value::Null;
2523                }
2524                "subscribe_to_recovery_progress" => {
2525                    let mut stream = self.subscribe_to_recovery_progress();
2526                    while let Some((module_id, progress)) = stream.next().await {
2527                        yield serde_json::json!({
2528                            "module_id": module_id,
2529                            "progress": progress
2530                        });
2531                    }
2532                }
2533                #[allow(deprecated)]
2534                "backup_to_federation" => {
2535                    let metadata = if params.is_null() {
2536                        Metadata::from_json_serialized(serde_json::json!({}))
2537                    } else {
2538                        Metadata::from_json_serialized(params)
2539                    };
2540                    self.backup_to_federation(metadata).await?;
2541                    yield serde_json::Value::Null;
2542                }
2543                _ => {
2544                    Err(anyhow::format_err!("Unknown method: {}", method))?;
2545                    unreachable!()
2546                },
2547            }
2548        })
2549    }
2550
2551    pub async fn log_event<E>(&self, module_id: Option<ModuleInstanceId>, event: E)
2552    where
2553        E: Event + Send,
2554    {
2555        let mut dbtx = self.db.begin_transaction().await;
2556        self.log_event_dbtx(&mut dbtx, module_id, event).await;
2557        dbtx.commit_tx().await;
2558    }
2559
2560    pub async fn log_event_dbtx<E, Cap>(
2561        &self,
2562        dbtx: &mut DatabaseTransaction<'_, Cap>,
2563        module_id: Option<ModuleInstanceId>,
2564        event: E,
2565    ) where
2566        E: Event + Send,
2567        Cap: Send,
2568    {
2569        dbtx.log_event(self.log_ordering_wakeup_tx.clone(), module_id, event)
2570            .await;
2571    }
2572
2573    pub async fn log_event_raw_dbtx<Cap>(
2574        &self,
2575        dbtx: &mut DatabaseTransaction<'_, Cap>,
2576        kind: EventKind,
2577        module: Option<(ModuleKind, ModuleInstanceId)>,
2578        payload: Vec<u8>,
2579        persist: EventPersistence,
2580    ) where
2581        Cap: Send,
2582    {
2583        let module_id = module.as_ref().map(|m| m.1);
2584        let module_kind = module.map(|m| m.0);
2585        dbtx.log_event_raw(
2586            self.log_ordering_wakeup_tx.clone(),
2587            kind,
2588            module_kind,
2589            module_id,
2590            payload,
2591            persist,
2592        )
2593        .await;
2594    }
2595
2596    /// Built in event log (trimmable) tracker
2597    ///
2598    /// For the convenience of downstream applications, [`Client`] can store
2599    /// internally event log position for the main application using/driving it.
2600    ///
2601    /// Note that this position is a singleton, so this tracker should not be
2602    /// used for multiple purposes or applications, etc. at the same time.
2603    ///
2604    /// If the application has a need to follow log using multiple trackers, it
2605    /// should implement own [`DynEventLogTrimableTracker`] and store its
2606    /// persient data by itself.
2607    pub fn built_in_application_event_log_tracker(&self) -> DynEventLogTrimableTracker {
2608        struct BuiltInApplicationEventLogTracker;
2609
2610        #[apply(async_trait_maybe_send!)]
2611        impl EventLogTrimableTracker for BuiltInApplicationEventLogTracker {
2612            // Store position in the event log
2613            async fn store(
2614                &mut self,
2615                dbtx: &mut DatabaseTransaction<NonCommittable>,
2616                pos: EventLogTrimableId,
2617            ) -> anyhow::Result<()> {
2618                dbtx.insert_entry(&DefaultApplicationEventLogKey, &pos)
2619                    .await;
2620                Ok(())
2621            }
2622
2623            /// Load the last previous stored position (or None if never stored)
2624            async fn load(
2625                &mut self,
2626                dbtx: &mut DatabaseTransaction<NonCommittable>,
2627            ) -> anyhow::Result<Option<EventLogTrimableId>> {
2628                Ok(dbtx.get_value(&DefaultApplicationEventLogKey).await)
2629            }
2630        }
2631        Box::new(BuiltInApplicationEventLogTracker)
2632    }
2633
2634    /// Like [`Self::handle_events`] but for historical data.
2635    ///
2636    ///
2637    /// This function can be used to process subset of events
2638    /// that is infrequent and important enough to be persisted
2639    /// forever. Most applications should prefer to use [`Self::handle_events`]
2640    /// which emits *all* events.
2641    pub async fn handle_historical_events<F, R>(
2642        &self,
2643        tracker: fedimint_eventlog::DynEventLogTracker,
2644        handler_fn: F,
2645    ) -> anyhow::Result<()>
2646    where
2647        F: Fn(&mut DatabaseTransaction<NonCommittable>, EventLogEntry) -> R,
2648        R: Future<Output = anyhow::Result<()>>,
2649    {
2650        fedimint_eventlog::handle_events(
2651            self.db.clone(),
2652            tracker,
2653            self.log_event_added_rx.clone(),
2654            handler_fn,
2655        )
2656        .await
2657    }
2658
2659    /// Handle events emitted by the client
2660    ///
2661    /// This is a preferred method for reactive & asynchronous
2662    /// processing of events emitted by the client.
2663    ///
2664    /// It needs a `tracker` that will persist the position in the log
2665    /// as it is being handled. You can use the
2666    /// [`Client::built_in_application_event_log_tracker`] if this call is
2667    /// used for the single main application handling this instance of the
2668    /// [`Client`]. Otherwise you should implement your own tracker.
2669    ///
2670    /// This handler will call `handle_fn` with ever event emitted by
2671    /// [`Client`], including transient ones. The caller should atomically
2672    /// handle each event it is interested in and ignore other ones.
2673    ///
2674    /// This method returns only when client is shutting down or on internal
2675    /// error, so typically should be called in a background task dedicated
2676    /// to handling events.
2677    pub async fn handle_events<F, R>(
2678        &self,
2679        tracker: fedimint_eventlog::DynEventLogTrimableTracker,
2680        handler_fn: F,
2681    ) -> anyhow::Result<()>
2682    where
2683        F: Fn(&mut DatabaseTransaction<NonCommittable>, EventLogEntry) -> R,
2684        R: Future<Output = anyhow::Result<()>>,
2685    {
2686        fedimint_eventlog::handle_trimable_events(
2687            self.db.clone(),
2688            tracker,
2689            self.log_event_added_rx.clone(),
2690            handler_fn,
2691        )
2692        .await
2693    }
2694
2695    pub async fn get_event_log(
2696        &self,
2697        pos: Option<EventLogId>,
2698        limit: u64,
2699    ) -> Vec<PersistedLogEntry> {
2700        self.get_event_log_dbtx(&mut self.db.begin_transaction_nc().await, pos, limit)
2701            .await
2702    }
2703
2704    /// Returns the id that the next entry appended to the event log will be
2705    /// assigned, i.e. the position just past the current end of the log.
2706    pub async fn get_next_event_log_id(&self) -> EventLogId {
2707        self.db
2708            .begin_transaction_nc()
2709            .await
2710            .get_next_event_log_id()
2711            .await
2712    }
2713
2714    pub async fn get_event_log_trimable(
2715        &self,
2716        pos: Option<EventLogTrimableId>,
2717        limit: u64,
2718    ) -> Vec<PersistedLogEntry> {
2719        self.get_event_log_trimable_dbtx(&mut self.db.begin_transaction_nc().await, pos, limit)
2720            .await
2721    }
2722
2723    pub async fn get_event_log_dbtx<Cap>(
2724        &self,
2725        dbtx: &mut DatabaseTransaction<'_, Cap>,
2726        pos: Option<EventLogId>,
2727        limit: u64,
2728    ) -> Vec<PersistedLogEntry>
2729    where
2730        Cap: Send,
2731    {
2732        dbtx.get_event_log(pos, limit).await
2733    }
2734
2735    pub async fn get_event_log_trimable_dbtx<Cap>(
2736        &self,
2737        dbtx: &mut DatabaseTransaction<'_, Cap>,
2738        pos: Option<EventLogTrimableId>,
2739        limit: u64,
2740    ) -> Vec<PersistedLogEntry>
2741    where
2742        Cap: Send,
2743    {
2744        dbtx.get_event_log_trimable(pos, limit).await
2745    }
2746
2747    /// Register to receiver all new transient (unpersisted) events
2748    pub fn get_event_log_transient_receiver(&self) -> broadcast::Receiver<EventLogEntry> {
2749        self.log_event_added_transient_tx.subscribe()
2750    }
2751
2752    /// Get a receiver that signals when new events are added to the event log
2753    pub fn log_event_added_rx(&self) -> watch::Receiver<()> {
2754        self.log_event_added_rx.clone()
2755    }
2756
2757    pub fn iroh_enable_dht(&self) -> bool {
2758        self.iroh_enable_dht
2759    }
2760
2761    /// Whether compatible iroh-next endpoints from guardian metadata are
2762    /// preferred.
2763    pub fn iroh_enable_next(&self) -> bool {
2764        self.iroh_enable_next
2765    }
2766
2767    pub(crate) async fn run_core_migrations(
2768        db_no_decoders: &Database,
2769    ) -> Result<(), anyhow::Error> {
2770        let mut dbtx = db_no_decoders.begin_transaction().await;
2771        apply_migrations_core_client_dbtx(&mut dbtx.to_ref_nc(), "fedimint-client".to_string())
2772            .await?;
2773        if is_running_in_test_env() {
2774            verify_client_db_integrity_dbtx(&mut dbtx.to_ref_nc()).await;
2775        }
2776        dbtx.commit_tx_result().await?;
2777        Ok(())
2778    }
2779
2780    /// Iterator over primary modules for a given `unit`
2781    fn primary_modules_for_unit(
2782        &self,
2783        unit: AmountUnit,
2784    ) -> impl Iterator<Item = (ModuleInstanceId, &DynClientModule)> {
2785        self.primary_modules
2786            .iter()
2787            .flat_map(move |(_prio, candidates)| {
2788                candidates
2789                    .specific
2790                    .get(&unit)
2791                    .into_iter()
2792                    .flatten()
2793                    .copied()
2794                    // within same priority, wildcard matches come last
2795                    .chain(candidates.wildcard.iter().copied())
2796            })
2797            .map(|id| (id, self.modules.get_expect(id)))
2798    }
2799
2800    /// Primary module to use for `unit`
2801    ///
2802    /// Currently, just pick the first (highest priority) match
2803    pub fn primary_module_for_unit(
2804        &self,
2805        unit: AmountUnit,
2806    ) -> Option<(ModuleInstanceId, &DynClientModule)> {
2807        self.primary_modules_for_unit(unit).next()
2808    }
2809
2810    /// [`Self::primary_module_for_unit`] for Bitcoin
2811    pub fn primary_module_for_btc(&self) -> (ModuleInstanceId, &DynClientModule) {
2812        self.primary_module_for_unit(AmountUnit::BITCOIN)
2813            .expect("No primary module for Bitcoin")
2814    }
2815}
2816
2817#[apply(async_trait_maybe_send!)]
2818impl ClientContextIface for Client {
2819    fn get_module(&self, instance: ModuleInstanceId) -> &maybe_add_send_sync!(dyn IClientModule) {
2820        Client::get_module(self, instance)
2821    }
2822
2823    fn api_clone(&self) -> DynGlobalApi {
2824        Client::api_clone(self)
2825    }
2826    fn decoders(&self) -> &ModuleDecoderRegistry {
2827        Client::decoders(self)
2828    }
2829
2830    async fn finalize_and_submit_transaction(
2831        &self,
2832        operation_id: OperationId,
2833        operation_type: &str,
2834        operation_meta_gen: Box<maybe_add_send_sync!(dyn Fn(OutPointRange) -> serde_json::Value)>,
2835        tx_builder: TransactionBuilder,
2836    ) -> anyhow::Result<OutPointRange> {
2837        Client::finalize_and_submit_transaction(
2838            self,
2839            operation_id,
2840            operation_type,
2841            // |out_point_range| operation_meta_gen(out_point_range),
2842            &operation_meta_gen,
2843            tx_builder,
2844        )
2845        .await
2846    }
2847
2848    async fn finalize_and_submit_transaction_dbtx(
2849        &self,
2850        dbtx: &mut DatabaseTransaction<'_>,
2851        operation_id: OperationId,
2852        operation_type: &str,
2853        operation_meta_gen: Box<maybe_add_send_sync!(dyn Fn(OutPointRange) -> serde_json::Value)>,
2854        tx_builder: TransactionBuilder,
2855    ) -> anyhow::Result<OutPointRange> {
2856        Client::finalize_and_submit_transaction_dbtx(
2857            self,
2858            dbtx,
2859            operation_id,
2860            operation_type,
2861            &operation_meta_gen,
2862            tx_builder,
2863        )
2864        .await
2865    }
2866
2867    async fn finalize_and_submit_transaction_inner(
2868        &self,
2869        dbtx: &mut DatabaseTransaction<'_>,
2870        operation_id: OperationId,
2871        tx_builder: TransactionBuilder,
2872    ) -> anyhow::Result<OutPointRange> {
2873        Client::finalize_and_submit_transaction_inner(self, dbtx, operation_id, tx_builder).await
2874    }
2875
2876    async fn fee_quote(
2877        &self,
2878        operation_id: OperationId,
2879        request: FeeQuoteRequest,
2880    ) -> anyhow::Result<FeeQuote> {
2881        Client::fee_quote(self, operation_id, request).await
2882    }
2883
2884    async fn get_balance_for_unit(&self, unit: AmountUnit) -> anyhow::Result<Amount> {
2885        Client::get_balance_for_unit(self, unit).await
2886    }
2887
2888    async fn transaction_updates(&self, operation_id: OperationId) -> TransactionUpdates {
2889        Client::transaction_updates(self, operation_id).await
2890    }
2891
2892    async fn await_primary_module_outputs(
2893        &self,
2894        operation_id: OperationId,
2895        // TODO: make `impl Iterator<Item = ...>`
2896        outputs: Vec<OutPoint>,
2897    ) -> anyhow::Result<()> {
2898        Client::await_primary_bitcoin_module_outputs(self, operation_id, outputs).await
2899    }
2900
2901    fn operation_log(&self) -> &dyn IOperationLog {
2902        Client::operation_log(self)
2903    }
2904
2905    async fn has_active_states(&self, operation_id: OperationId) -> bool {
2906        Client::has_active_states(self, operation_id).await
2907    }
2908
2909    async fn operation_exists(&self, operation_id: OperationId) -> bool {
2910        Client::operation_exists(self, operation_id).await
2911    }
2912
2913    async fn config(&self) -> ClientConfig {
2914        Client::config(self).await
2915    }
2916
2917    fn db(&self) -> &Database {
2918        Client::db(self)
2919    }
2920
2921    fn executor(&self) -> &(maybe_add_send_sync!(dyn IExecutor + 'static)) {
2922        Client::executor(self)
2923    }
2924
2925    async fn invite_code(&self, peer: PeerId) -> Option<InviteCode> {
2926        Client::invite_code(self, peer).await
2927    }
2928
2929    fn get_internal_payment_markers(&self) -> anyhow::Result<(PublicKey, u64)> {
2930        Client::get_internal_payment_markers(self)
2931    }
2932
2933    async fn log_event_json(
2934        &self,
2935        dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
2936        module_kind: Option<ModuleKind>,
2937        module_id: ModuleInstanceId,
2938        kind: EventKind,
2939        payload: serde_json::Value,
2940        persist: EventPersistence,
2941    ) {
2942        dbtx.ensure_global()
2943            .expect("Must be called with global dbtx");
2944        self.log_event_raw_dbtx(
2945            dbtx,
2946            kind,
2947            module_kind.map(|kind| (kind, module_id)),
2948            serde_json::to_vec(&payload).expect("Serialization can't fail"),
2949            persist,
2950        )
2951        .await;
2952    }
2953
2954    async fn read_operation_active_states<'dbtx>(
2955        &self,
2956        operation_id: OperationId,
2957        module_id: ModuleInstanceId,
2958        dbtx: &'dbtx mut DatabaseTransaction<'_>,
2959    ) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (ActiveStateKey, ActiveStateMeta)> + 'dbtx)>>
2960    {
2961        Box::pin(
2962            dbtx.find_by_prefix(&ActiveModuleOperationStateKeyPrefix {
2963                operation_id,
2964                module_instance: module_id,
2965            })
2966            .await
2967            .map(move |(k, v)| (k.0, v)),
2968        )
2969    }
2970    async fn read_operation_inactive_states<'dbtx>(
2971        &self,
2972        operation_id: OperationId,
2973        module_id: ModuleInstanceId,
2974        dbtx: &'dbtx mut DatabaseTransaction<'_>,
2975    ) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (InactiveStateKey, InactiveStateMeta)> + 'dbtx)>>
2976    {
2977        Box::pin(
2978            dbtx.find_by_prefix(&InactiveModuleOperationStateKeyPrefix {
2979                operation_id,
2980                module_instance: module_id,
2981            })
2982            .await
2983            .map(move |(k, v)| (k.0, v)),
2984        )
2985    }
2986}
2987
2988// TODO: impl `Debug` for `Client` and derive here
2989impl fmt::Debug for Client {
2990    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2991        write!(f, "Client")
2992    }
2993}
2994
2995pub fn client_decoders<'a>(
2996    registry: &ModuleInitRegistry<DynClientModuleInit>,
2997    module_kinds: impl Iterator<Item = (ModuleInstanceId, &'a ModuleKind)>,
2998) -> ModuleDecoderRegistry {
2999    let mut modules = BTreeMap::new();
3000    for (id, kind) in module_kinds {
3001        let Some(init) = registry.get(kind) else {
3002            debug!("Detected configuration for unsupported module id: {id}, kind: {kind}");
3003            continue;
3004        };
3005
3006        modules.insert(
3007            id,
3008            (
3009                kind.clone(),
3010                IClientModuleInit::decoder(AsRef::<dyn IClientModuleInit + 'static>::as_ref(init)),
3011            ),
3012        );
3013    }
3014    ModuleDecoderRegistry::from(modules)
3015}