Skip to main content

fedimint_client/
client.rs

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