Skip to main content

fedimint_walletv2_client/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::missing_panics_doc)]
4#![allow(clippy::must_use_candidate)]
5#![allow(clippy::module_name_repetitions)]
6
7pub use fedimint_walletv2_common as common;
8pub use fedimint_walletv2_common::MempoolVisibility;
9
10mod api;
11#[cfg(feature = "cli")]
12mod cli;
13pub mod db;
14pub mod events;
15mod migrations;
16mod receive_sm;
17mod send_sm;
18
19use std::collections::{BTreeMap, BTreeSet};
20use std::sync::Arc;
21use std::time::Duration;
22
23use api::WalletFederationApi;
24use bitcoin::address::NetworkUnchecked;
25use bitcoin::{Address, ScriptBuf};
26use db::{
27    NextOutputIndexKey, ValidAddressIndexAccountPrefix, ValidAddressIndexKey,
28    ValidAddressIndexPrefix,
29};
30use events::{ReceivePaymentEvent, SendPaymentEvent};
31use fedimint_api_client::api::{DynModuleApi, FederationError, FederationResult};
32use fedimint_client::DynGlobalClientContext;
33use fedimint_client::transaction::{
34    ClientInput, ClientInputBundle, ClientInputSM, ClientOutput, ClientOutputBundle,
35    ClientOutputSM, FeeQuote, FeeQuoteRequest, TransactionBuilder, max_affordable_send_amount,
36};
37use fedimint_client_module::db::ClientModuleMigrationFn;
38use fedimint_client_module::error::{
39    ClientModuleError, OperationLookupError, TransactionSubmitError,
40};
41use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
42use fedimint_client_module::module::recovery::NoModuleBackup;
43use fedimint_client_module::module::{ClientContext, ClientModule, OutPointRange};
44use fedimint_client_module::secret::DeriveableSecretClientExt;
45use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
46use fedimint_client_module::sm_enum_variant_translation;
47use fedimint_core::core::{Account, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
48use fedimint_core::db::{
49    Database, DatabaseError, DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped,
50};
51use fedimint_core::encoding::{Decodable, Encodable};
52use fedimint_core::module::{
53    AmountUnit, Amounts, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
54};
55use fedimint_core::task::{TaskGroup, TaskHandle, sleep};
56use fedimint_core::{Amount, OutPoint, TransactionId, apply, async_trait_maybe_send};
57use fedimint_derive_secret::{ChildId, DerivableSecret};
58use fedimint_eventlog::{Event, EventLogId};
59use fedimint_logging::LOG_CLIENT_MODULE_WALLETV2;
60use fedimint_walletv2_common::config::WalletClientConfig;
61use fedimint_walletv2_common::{
62    BLOCK_COUNT_VOTE_DELAY, KIND, OutputInfo, PendingOutput, PendingOutputs, StandardScript,
63    TxInfo, WalletCommonInit, WalletInput, WalletInputV0, WalletModuleTypes, WalletOutput,
64    WalletOutputV0, descriptor, is_potential_receive,
65};
66use futures::StreamExt;
67use receive_sm::{ReceiveSMCommon, ReceiveSMState, ReceiveStateMachine};
68use secp256k1::Keypair;
69use send_sm::{SendSMCommon, SendSMState, SendStateMachine};
70use serde::{Deserialize, Serialize};
71use strum::IntoEnumIterator as _;
72use thiserror::Error;
73use tracing::{debug, warn};
74
75/// Number of output info entries to scan per batch.
76const SLICE_SIZE: u64 = 1000;
77
78/// Number of event log entries to read per batch.
79const EVENT_LOG_PAGE_SIZE: u64 = 1000;
80
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub enum WalletOperationMeta {
83    Send(SendMeta),
84    Receive(ReceiveMeta),
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct SendMeta {
89    pub change_outpoint_range: OutPointRange,
90    pub address: Address<NetworkUnchecked>,
91    pub value: bitcoin::Amount,
92    pub fee: bitcoin::Amount,
93    #[serde(default)]
94    pub custom_meta: serde_json::Value,
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct ReceiveMeta {
99    pub change_outpoint_range: OutPointRange,
100    pub value: bitcoin::Amount,
101    pub fee: bitcoin::Amount,
102    pub address: Option<Address<NetworkUnchecked>>,
103    pub outpoint: Option<bitcoin::OutPoint>,
104}
105
106/// The final state of an operation sending bitcoin onchain.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108pub enum FinalSendOperationState {
109    /// The transaction was successful.
110    Success(bitcoin::Txid),
111    /// The funding transaction was aborted.
112    Aborted,
113    /// A programming error has occurred or the federation is malicious.
114    Failure,
115}
116
117/// The final state of an operation receiving bitcoin onchain.
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119pub enum FinalReceiveOperationState {
120    /// The federation accepted the claiming transaction.
121    Success,
122    /// The federation rejected the claiming transaction.
123    Aborted,
124}
125
126/// Progress of a single incoming peg-in.
127///
128/// Each variant describes one deposit, identified by the outpoint it is looked
129/// up or paired with. An address that has been paid more than once has one of
130/// these per payment rather than a combined view, so nothing is aggregated
131/// away.
132///
133/// There is no "nothing has arrived" variant: a deposit no guardian has seen
134/// has no outpoint to describe it, so absence is expressed by
135/// [`WalletClientModule::address_receive_progress`] reporting no deposits.
136///
137/// Every variant is derived from advisory, non-consensus data reported by
138/// individual guardians, so none of them is authoritative and progress may move
139/// backwards: a reorg or an eviction can take a deposit back to being unseen
140/// entirely. No variant means money has been received - a deposit is only
141/// actually claimed once [`WalletClientModule::await_receive`] returns, and an
142/// output is deliberately still reported here for a short while after that.
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144pub enum ReceiveProgress {
145    /// The deposit is in a guardian's mempool but is not mined.
146    ///
147    /// The weakest signal there is: an unmined transaction can be replaced or
148    /// evicted, and a deposit in this state can disappear again. Treat it as
149    /// "we have seen your payment", never as money received.
150    ///
151    /// Only guardians whose bitcoin backend can enumerate a mempool report
152    /// these, so on a federation without one a deposit stays unseen until it is
153    /// mined.
154    Mempool { value: bitcoin::Amount },
155    /// The deposit has been mined but is not yet deep enough for the federation
156    /// to act on it.
157    Confirming {
158        value: bitcoin::Amount,
159        /// Height of the block that mined the deposit.
160        ///
161        /// Reported as the guardians saw it, so a reorg can move a deposit to a
162        /// different height or back to being unseen entirely.
163        height: u64,
164        /// Confirmations counting the block that mined the transaction as the
165        /// first, matching what a block explorer displays.
166        confirmations: u64,
167        /// Confirmations needed before the federation records the output.
168        required: u64,
169    },
170}
171
172/// What the federation currently reports about the deposits to one address.
173///
174/// Returned by [`WalletClientModule::address_receive_progress`]. The two fields
175/// are only meaningful together: they come from a single query, so the
176/// visibility flag describes exactly the view the deposits were read from.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct AddressReceiveProgress {
179    /// One entry per deposit the guardians can see, ordered by outpoint.
180    pub deposits: Vec<(bitcoin::OutPoint, ReceiveProgress)>,
181    /// The best mempool view any guardian had for this query.
182    ///
183    /// With [`MempoolVisibility::Complete`], empty `deposits` mean no
184    /// matching deposit was observed in the reported snapshot. That is not
185    /// proof that no payment was sent: a guardian only inspects its own
186    /// mempool, which a freshly broadcast transaction may not have reached
187    /// yet, and a deposit mined long enough ago has left the reported block
188    /// window. With [`MempoolVisibility::Partial`] the unmined deposits
189    /// reported are real, but one may also be missing because a guardian
190    /// failed to fetch its transaction or has not reached it yet while still
191    /// working through a large mempool, which is normal progress rather than
192    /// a backend fault; with
193    /// [`MempoolVisibility::Unavailable`] the federation is blind to a
194    /// payment until it is mined. One guardian that inspected its whole
195    /// mempool is enough to make this `Complete` for everyone.
196    ///
197    /// A wallet showing a receive screen wants this to choose between "we have
198    /// not seen your payment yet" and "waiting for the first confirmation",
199    /// which are very different things to tell a user who has just paid.
200    pub mempool_visibility: MempoolVisibility,
201}
202
203/// Deposits to this client's receive addresses, as the federation reports them.
204/// Both fields come from one query.
205///
206/// Returned by [`WalletClientModule::all_receive_progress`].
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct AllReceiveProgress {
209    /// One entry per deposit the guardians can see to an address of this
210    /// client, ordered by outpoint.
211    pub deposits: Vec<(Address, bitcoin::OutPoint, ReceiveProgress)>,
212    /// Best mempool view any guardian had for this query.
213    pub mempool_visibility: MempoolVisibility,
214}
215
216#[derive(Debug, Clone)]
217pub struct WalletClientModule {
218    /// Every account's derivation root, derived once so the address grind
219    /// pays a single child derivation per index.
220    account_secrets: [DerivableSecret; Account::ALL.len()],
221    cfg: WalletClientConfig,
222    notifier: ModuleNotifier<WalletClientStateMachines>,
223    client_ctx: ClientContext<Self>,
224    db: Database,
225    module_api: DynModuleApi,
226}
227
228#[derive(Debug, Clone)]
229pub struct WalletClientContext {
230    pub client_ctx: ClientContext<WalletClientModule>,
231}
232
233impl Context for WalletClientContext {
234    const KIND: Option<ModuleKind> = Some(KIND);
235}
236
237#[apply(async_trait_maybe_send!)]
238impl ClientModule for WalletClientModule {
239    type Init = WalletClientInit;
240    type Common = WalletModuleTypes;
241    type Backup = NoModuleBackup;
242    type ModuleStateMachineContext = WalletClientContext;
243    type States = WalletClientStateMachines;
244
245    fn context(&self) -> Self::ModuleStateMachineContext {
246        WalletClientContext {
247            client_ctx: self.client_ctx.clone(),
248        }
249    }
250
251    fn input_fee(
252        &self,
253        amount: &Amounts,
254        _input: &<Self::Common as ModuleCommon>::Input,
255    ) -> Option<Amounts> {
256        amount
257            .get(&AmountUnit::BITCOIN)
258            .map(|a| Amounts::new_bitcoin(self.cfg.fee_consensus.fee(*a)))
259    }
260
261    fn output_fee(
262        &self,
263        amount: &Amounts,
264        _output: &<Self::Common as ModuleCommon>::Output,
265    ) -> Option<Amounts> {
266        amount
267            .get(&AmountUnit::BITCOIN)
268            .map(|a| Amounts::new_bitcoin(self.cfg.fee_consensus.fee(*a)))
269    }
270
271    #[cfg(feature = "cli")]
272    async fn handle_cli_command(
273        &self,
274        args: &[std::ffi::OsString],
275    ) -> Result<serde_json::Value, ClientModuleError> {
276        cli::handle_cli_command(self, args)
277            .await
278            .map_err(ClientModuleError::other)
279    }
280}
281
282#[derive(Debug, Clone, Default)]
283pub struct WalletClientInit;
284
285impl ModuleInit for WalletClientInit {
286    type Common = WalletCommonInit;
287
288    async fn dump_database(
289        &self,
290        _dbtx: &mut DatabaseTransaction<'_>,
291        _prefix_names: Vec<String>,
292    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
293        Box::new(BTreeMap::new().into_iter())
294    }
295}
296
297#[apply(async_trait_maybe_send!)]
298impl ClientModuleInit for WalletClientInit {
299    type Module = WalletClientModule;
300
301    fn supported_api_versions(&self) -> MultiApiVersion {
302        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
303            .expect("no version conflicts")
304    }
305
306    fn get_database_migrations(&self) -> BTreeMap<DatabaseVersion, ClientModuleMigrationFn> {
307        let mut migrations: BTreeMap<DatabaseVersion, ClientModuleMigrationFn> = BTreeMap::new();
308
309        migrations.insert(DatabaseVersion(0), |dbtx, active, inactive| {
310            Box::pin(migrations::migrate_to_accounts_v1(dbtx, active, inactive))
311        });
312
313        migrations
314    }
315
316    async fn init(
317        &self,
318        args: &ClientModuleInitArgs<Self>,
319    ) -> Result<Self::Module, ClientModuleError> {
320        let module = WalletClientModule {
321            account_secrets: Account::ALL
322                .map(|account| args.module_root_secret().derive_account_secret(account)),
323            cfg: args.cfg().clone(),
324            notifier: args.notifier().clone(),
325            client_ctx: args.context(),
326            db: args.db().clone(),
327            module_api: args.module_api().clone(),
328        };
329
330        module.spawn_output_scanner(args.task_group(), args.client_span());
331
332        Ok(module)
333    }
334
335    fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
336        Some(db::DbKeyPrefix::iter().map(|p| p as u8).collect())
337    }
338}
339
340impl WalletClientModule {
341    /// Returns the Bitcoin network for this federation.
342    pub fn get_network(&self) -> bitcoin::Network {
343        self.cfg.network
344    }
345
346    /// Fetch the total value of bitcoin controlled by the federation.
347    pub async fn total_value(&self) -> FederationResult<bitcoin::Amount> {
348        self.module_api
349            .federation_wallet()
350            .await
351            .map(|tx_out| tx_out.map_or(bitcoin::Amount::ZERO, |tx_out| tx_out.value))
352    }
353
354    /// Fetch the consensus block count of the federation.
355    pub async fn block_count(&self) -> FederationResult<u64> {
356        self.module_api.consensus_block_count().await
357    }
358
359    /// Fetch the current consensus feerate.
360    pub async fn feerate(&self) -> FederationResult<Option<u64>> {
361        self.module_api.consensus_feerate().await
362    }
363
364    /// Fetch information on the chain of pending bitcoin transactions.
365    pub async fn pending_tx_chain(&self) -> FederationResult<Vec<TxInfo>> {
366        self.module_api.pending_tx_chain().await
367    }
368
369    /// Display log of bitcoin transactions.
370    pub async fn tx_chain(&self) -> FederationResult<Vec<TxInfo>> {
371        self.module_api.tx_chain().await
372    }
373
374    /// Fetch the current fee required to send an onchain payment.
375    pub async fn send_fee(&self) -> Result<bitcoin::Amount, SendError> {
376        self.module_api
377            .send_fee()
378            .await
379            .map_err(|e| SendError::Federation(Box::new(e)))?
380            .ok_or(SendError::NoConsensusFeerateAvailable)
381    }
382
383    /// Computes the federation fee an onchain send of an output worth `amount`
384    /// (the payment amount plus the on-chain miner fee) would incur, without
385    /// submitting anything.
386    ///
387    /// A send submits a single wallet output worth `amount`; the primary module
388    /// balances it by spending ecash to fund the output and minting any change.
389    /// This quotes the fee of that transaction — the wallet output fee, the
390    /// mint input fees on the funding notes, any mint change output fees,
391    /// and sub-denomination dust — via the shared, module-agnostic fee
392    /// quote.
393    ///
394    /// The on-chain Bitcoin miner fee is deliberately excluded: it is part of
395    /// the output `amount` (see [`Self::send_fee`]), not the on-federation
396    /// transaction fee.
397    pub async fn send_fee_quote(
398        &self,
399        account: Account,
400        amount: bitcoin::Amount,
401    ) -> Result<FeeQuote, TransactionSubmitError> {
402        let amount = Amount::from_sats(amount.to_sat());
403        self.client_ctx
404            .fee_quote(
405                OperationId::new_random(),
406                FeeQuoteRequest {
407                    input_amount: Amounts::ZERO,
408                    output_amount: Amounts::new_bitcoin(amount),
409                    input_fee: Amounts::ZERO,
410                    output_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.fee(amount)),
411                    account,
412                },
413            )
414            .await
415    }
416
417    /// Finds the largest value that can be sent on chain in full out of
418    /// `balance` — the amount a "send everything" sweep should use.
419    ///
420    /// Sending `value` costs `value + fee` (the on-chain miner fee is carried
421    /// inside the wallet output, see [`Self::send`]) *plus* the federation fee
422    /// of funding that output — the wallet output fee, the mint input fees on
423    /// the funding notes, any mint change output fees and sub-denomination
424    /// dust — as quoted by [`Self::send_fee_quote`]. This returns the largest
425    /// `value` satisfying
426    ///
427    /// ```text
428    /// value + fee + send_fee_quote(value + fee).total() <= balance
429    /// ```
430    ///
431    /// `balance` is the client's current Bitcoin balance (e.g. from
432    /// `Client::get_balance_for_btc`). `fee` is the on-chain fee from
433    /// [`Self::send_fee`]; pass the *same* value on to [`Self::send`], since
434    /// the required feerate rises with each pending federation transaction and
435    /// a value computed against a stale fee would be rejected.
436    ///
437    /// The maximum is found by binary search over the real fee quote (see
438    /// [`max_affordable_send_amount`]) rather than by subtracting a single
439    /// quote: the federation fee is charged per note, so note selection,
440    /// denomination rounding, change and dust move it in steps as the value
441    /// crosses thresholds, and a quote taken at the full balance would fail
442    /// outright — funding it is the very thing that is unaffordable.
443    ///
444    /// The quote is point-in-time and moves with the balance; [`Self::send`]
445    /// remains the source of truth. Note that it cannot account for the
446    /// federation's own on-chain constraints — a send whose change UTXO would
447    /// fall below the dust limit is still rejected by the guardians.
448    ///
449    /// Returns [`SendError::InsufficientFunds`] if the balance cannot cover
450    /// the dust limit plus fees, or [`SendError::Failed`] if the fee probe
451    /// itself failed.
452    pub async fn max_sendable_amount(
453        &self,
454        account: Account,
455        balance: Amount,
456        fee: bitcoin::Amount,
457    ) -> Result<bitcoin::Amount, SendError> {
458        let fee_msats = Amount::from_sats(fee.to_sat());
459
460        let max = max_affordable_send_amount(
461            balance,
462            Amount::from_sats(self.cfg.dust_limit.to_sat()),
463            balance,
464            // The solver searches millisatoshis, but a send funds a whole
465            // number of satoshis. Rounding the probe up to the next satoshi
466            // keeps the predicate conservative and makes the value handed to
467            // the quote below an exact satoshi multiple.
468            |value: Amount| Amount::from_sats(value.msats.div_ceil(1000)) + fee_msats,
469            |funded: Amount| {
470                self.send_fee_quote(account, bitcoin::Amount::from_sat(funded.msats / 1000))
471            },
472        )
473        .await
474        .map_err(SendError::Failed)?
475        .ok_or(SendError::InsufficientFunds)?;
476
477        // `gross_up` rounded up to whole satoshis, so the largest affordable
478        // amount already sits on a satoshi boundary; no value is lost here.
479        Ok(bitcoin::Amount::from_sat(max.msats.div_ceil(1000)))
480    }
481
482    /// Fetch the current fee required to claim an onchain deposit (peg-in).
483    pub async fn receive_fee(&self) -> Result<bitcoin::Amount, ReceiveError> {
484        self.module_api
485            .receive_fee()
486            .await
487            .map_err(|e| ReceiveError::Federation(Box::new(e)))?
488            .ok_or(ReceiveError::NoConsensusFeerateAvailable)
489    }
490
491    /// Send an onchain payment with the given fee.
492    pub async fn send(
493        &self,
494        account: Account,
495        address: Address<NetworkUnchecked>,
496        value: bitcoin::Amount,
497        fee: Option<bitcoin::Amount>,
498        custom_meta: serde_json::Value,
499    ) -> Result<OperationId, SendError> {
500        if !self
501            .client_ctx
502            .supports_account(AmountUnit::BITCOIN, account)
503        {
504            return Err(SendError::AccountNotSupported);
505        }
506
507        if !address.is_valid_for_network(self.cfg.network) {
508            return Err(SendError::WrongNetwork);
509        }
510
511        if value < self.cfg.dust_limit {
512            return Err(SendError::DustValue);
513        }
514
515        let fee = match fee {
516            Some(value) => value,
517            None => self
518                .module_api
519                .send_fee()
520                .await
521                .map_err(|e| SendError::Federation(Box::new(e)))?
522                .ok_or(SendError::NoConsensusFeerateAvailable)?,
523        };
524
525        let operation_id = OperationId::new_random();
526
527        let destination = StandardScript::from_address(&address.clone().assume_checked())
528            .ok_or(SendError::UnsupportedAddress)?;
529
530        let client_output = ClientOutput::<WalletOutput> {
531            output: WalletOutput::V0(WalletOutputV0 {
532                destination,
533                value,
534                fee,
535            }),
536            amounts: Amounts::new_bitcoin(Amount::from_sats((value + fee).to_sat())),
537        };
538
539        let client_output_sm = ClientOutputSM::<WalletClientStateMachines> {
540            state_machines: Arc::new(move |range: OutPointRange| {
541                vec![WalletClientStateMachines::Send(SendStateMachine {
542                    common: SendSMCommon {
543                        operation_id,
544                        outpoint: OutPoint {
545                            txid: range.txid(),
546                            out_idx: 0,
547                        },
548                        value,
549                        fee,
550                    },
551                    state: SendSMState::Funding,
552                })]
553            }),
554        };
555
556        let client_output_bundle = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
557            vec![client_output],
558            vec![client_output_sm],
559        ));
560
561        let address_clone = address.clone();
562
563        self.client_ctx
564            .finalize_and_submit_transaction_with_events(
565                operation_id,
566                WalletCommonInit::KIND.as_str(),
567                move |change_outpoint_range| {
568                    WalletOperationMeta::Send(SendMeta {
569                        change_outpoint_range,
570                        address: address_clone.clone(),
571                        value,
572                        fee,
573                        custom_meta: custom_meta.clone(),
574                    })
575                },
576                TransactionBuilder::new(account).with_outputs(client_output_bundle),
577                vec![self.client_ctx.make_event(SendPaymentEvent {
578                    operation_id,
579                    address,
580                    value,
581                    fee,
582                    account,
583                })],
584            )
585            .await
586            .map_err(|error| match error {
587                TransactionSubmitError::InsufficientFunds(_) => SendError::InsufficientFunds,
588                error => SendError::Failed(error),
589            })?;
590
591        Ok(operation_id)
592    }
593
594    /// Await the final state of the send operation.
595    pub async fn await_final_send_operation_state(
596        &self,
597        operation_id: OperationId,
598    ) -> Result<FinalSendOperationState, OperationLookupError> {
599        let operation = self.client_ctx.get_operation(operation_id).await?;
600        let mut stream = self.notifier.subscribe(operation_id).await;
601
602        let mut stream = self
603            .client_ctx
604            .outcome_or_updates(&operation, operation_id, |_| true, move || {
605                async_stream::stream! {
606                    loop {
607                        if let Some(WalletClientStateMachines::Send(state)) = stream.next().await {
608                            match state.state {
609                                SendSMState::Funding => {}
610                                SendSMState::Success(txid) => {
611                                    yield FinalSendOperationState::Success(txid);
612                                    return;
613                                }
614                                SendSMState::Aborted(..) => {
615                                    yield FinalSendOperationState::Aborted;
616                                    return;
617                                }
618                                SendSMState::Failure => {
619                                    yield FinalSendOperationState::Failure;
620                                    return;
621                                }
622                            }
623                        }
624                    }
625                }
626            })
627            .into_stream();
628
629        let mut final_state = None;
630
631        while let Some(state) = stream.next().await {
632            final_state = Some(state);
633        }
634
635        Ok(final_state.expect("Stream contains one final state"))
636    }
637
638    /// Await the final state of the receive operation.
639    pub async fn await_final_receive_operation_state(
640        &self,
641        operation_id: OperationId,
642    ) -> Result<FinalReceiveOperationState, OperationLookupError> {
643        let operation = self.client_ctx.get_operation(operation_id).await?;
644        let mut stream = self.notifier.subscribe(operation_id).await;
645
646        let mut stream = self
647            .client_ctx
648            .outcome_or_updates(&operation, operation_id, |_| true, move || {
649                async_stream::stream! {
650                    loop {
651                        if let Some(WalletClientStateMachines::Receive(state)) = stream.next().await {
652                            match state.state {
653                                ReceiveSMState::Funding => {}
654                                ReceiveSMState::Success => {
655                                    yield FinalReceiveOperationState::Success;
656                                    return;
657                                }
658                                ReceiveSMState::Aborted(..) => {
659                                    yield FinalReceiveOperationState::Aborted;
660                                    return;
661                                }
662                            }
663                        }
664                    }
665                }
666            })
667            .into_stream();
668
669        let mut final_state = None;
670
671        while let Some(state) = stream.next().await {
672            final_state = Some(state);
673        }
674
675        Ok(final_state.expect("Stream contains one final state"))
676    }
677
678    /// Resolves one of our receive addresses back to the index it was derived
679    /// at.
680    ///
681    /// Only addresses handed out by [`Self::receive`] resolve; the set of valid
682    /// indices is small, so this is a short scan rather than a stored reverse
683    /// index.
684    async fn address_index(&self, address: &Address) -> Option<(Account, u64)> {
685        let script = address.script_pubkey();
686
687        let indices: Vec<(Account, u64)> = self
688            .db
689            .begin_transaction_nc()
690            .await
691            .find_by_prefix(&ValidAddressIndexPrefix)
692            .await
693            .map(|entry| (entry.0.0, entry.0.1))
694            .collect()
695            .await;
696
697        indices.into_iter().find(|(account, index)| {
698            self.derive_address(*account, *index).script_pubkey() == script
699        })
700    }
701
702    /// The current progress of the deposit at `outpoint`.
703    ///
704    /// Reads only the guardians' pending view, which is advisory and may move
705    /// backwards, and which cannot tell a claimed deposit from a reorged one.
706    /// Use [`Self::await_receive`] to establish that a deposit has actually
707    /// been claimed.
708    ///
709    /// Each call queries the federation, so poll it sparingly.
710    ///
711    /// Errors if no deposit at `outpoint` is known to this client, which
712    /// includes one that has been reorged out or evicted since it was last
713    /// seen, and one paying an address this client did not derive.
714    pub async fn receive_progress(
715        &self,
716        outpoint: bitcoin::OutPoint,
717    ) -> Result<ReceiveProgress, ReceiveProgressError> {
718        let pending = self.module_api.pending_outputs().await;
719
720        // Guardians report every output passing the receive filter, most of
721        // which belong to other clients, so ownership is established by matching
722        // the script against our own addresses.
723        let ours = self.address_map().await;
724
725        pending
726            .outputs
727            .iter()
728            .find(|output| output.outpoint == outpoint && ours.contains_key(&output.script))
729            .map(|output| Self::pending_progress(output, pending.block_count))
730            .ok_or(ReceiveProgressError::UnknownDeposit)
731    }
732
733    /// The progress of every deposit to `address` the federation has seen,
734    /// ordered by outpoint.
735    ///
736    /// Empty deposits mean no guardian has reported a payment to the address
737    /// yet. Even when [`AddressReceiveProgress::mempool_visibility`] is
738    /// [`MempoolVisibility::Complete`], that only means no matching deposit
739    /// was observed in the reported snapshot, never proof that no payment was
740    /// sent: a broadcast transaction may not have reached the guardians'
741    /// mempools yet. Without `Complete` an unmined deposit may be invisible
742    /// to the federation altogether.
743    ///
744    /// Errors if `address` was not handed out by [`Self::receive`].
745    pub async fn address_receive_progress(
746        &self,
747        address: &Address,
748    ) -> Result<AddressReceiveProgress, ReceiveProgressError> {
749        self.address_index(address)
750            .await
751            .ok_or(ReceiveProgressError::UnknownAddress)?;
752
753        Ok(self.deposits_paying(&address.script_pubkey()).await)
754    }
755
756    /// The progress of every deposit to any address of this client, from a
757    /// single federation query, so that a wallet with many addresses does
758    /// not query the guardians once per address.
759    pub async fn all_receive_progress(&self) -> AllReceiveProgress {
760        let pending = self.module_api.pending_outputs().await;
761        let ours = self.address_map().await;
762
763        owned_receive_progress(&pending, &ours, |(account, index)| {
764            self.derive_address(*account, *index)
765        })
766    }
767
768    /// Every deposit the federation currently reports against `script`.
769    async fn deposits_paying(&self, script: &ScriptBuf) -> AddressReceiveProgress {
770        let pending = self.module_api.pending_outputs().await;
771
772        let mut deposits: Vec<(bitcoin::OutPoint, ReceiveProgress)> = pending
773            .outputs
774            .iter()
775            .filter(|output| output.script == *script)
776            .map(|output| {
777                (
778                    output.outpoint,
779                    Self::pending_progress(output, pending.block_count),
780                )
781            })
782            .collect();
783
784        deposits.sort_by_key(|(outpoint, _)| *outpoint);
785
786        AddressReceiveProgress {
787            deposits,
788            mempool_visibility: pending.mempool_visibility,
789        }
790    }
791
792    /// The scripts of every receive address derived so far, by account and
793    /// index.
794    async fn address_map(&self) -> BTreeMap<ScriptBuf, (Account, u64)> {
795        self.db
796            .begin_transaction_nc()
797            .await
798            .find_by_prefix(&ValidAddressIndexPrefix)
799            .await
800            .map(|entry| (entry.0.0, entry.0.1))
801            .map(|(account, index)| {
802                (
803                    self.derive_address(account, index).script_pubkey(),
804                    (account, index),
805                )
806            })
807            .collect()
808            .await
809    }
810
811    fn pending_progress(output: &PendingOutput, block_count: Option<u64>) -> ReceiveProgress {
812        // Block count votes trail the chain tip by the vote delay, and an output
813        // is only recorded once the consensus block count is past the block that
814        // mined it, so a peg-in is claimable one standard confirmation later than
815        // the vote delay itself.
816        let required = BLOCK_COUNT_VOTE_DELAY + 1;
817
818        match output.height {
819            Some(height) => ReceiveProgress::Confirming {
820                value: output.value,
821                height,
822                // Confirmations count the block that mined the deposit as the
823                // first, matching what a block explorer displays.
824                //
825                // Guardians keep reporting an output for a while after it turns
826                // final, so that progress does not blank out before the claim
827                // begins. Clamp so a progress display cannot run past its own
828                // target during that overlap.
829                confirmations: block_count
830                    .map_or(0, |count| count.saturating_sub(height))
831                    .min(required),
832                required,
833            },
834            None => ReceiveProgress::Mempool {
835                value: output.value,
836            },
837        }
838    }
839
840    /// Returns the highest valid receive address index that the background
841    /// scanner has derived so far, or `None` if it has not derived one yet.
842    /// All accounts share one table, so this reads the tail of the account's
843    /// own key prefix rather than the table's.
844    async fn valid_index(&self, account: Account) -> Option<u64> {
845        self.db
846            .begin_transaction_nc()
847            .await
848            .find_by_prefix_sorted_descending(&ValidAddressIndexAccountPrefix(account))
849            .await
850            .next()
851            .await
852            .map(|entry| entry.0.1)
853    }
854
855    /// Returns the next unused receive address.
856    ///
857    /// To wait for a payment to this address race-free, read the client's
858    /// current event log position (via the global `get_next_event_log_id`)
859    /// *before* calling this, then pass that position to
860    /// [`Self::await_receive`]; it will only consider payments received
861    /// after that position.
862    ///
863    /// If the background scanner has already derived a valid address index this
864    /// returns immediately. Otherwise it blocks, letting the scanner grind
865    /// until it finds the next valid index, and returns once one is
866    /// available.
867    ///
868    /// Refuses an account the primary module cannot hold a balance for before
869    /// handing out an address, since a deposit to it could never be claimed.
870    pub async fn receive(&self, account: Account) -> Result<Address, ReceiveError> {
871        if !self
872            .client_ctx
873            .supports_account(AmountUnit::BITCOIN, account)
874        {
875            return Err(ReceiveError::AccountNotSupported);
876        }
877
878        loop {
879            if let Some(index) = self.valid_index(account).await {
880                return Ok(self.derive_address(account, index));
881            }
882
883            sleep(Duration::from_secs(1)).await;
884        }
885    }
886
887    /// Block until the next on-chain payment recorded at or after `position` is
888    /// received and successfully claimed by the federation.
889    ///
890    /// Returns the peg-in's final state together with the event log position
891    /// just past it, so that a subsequent call can resume from there to wait
892    /// for the following receive.
893    ///
894    /// A peg-in attempt may be aborted (rejected by the federation), in which
895    /// case the still-unspent output is reprocessed into a new receive
896    /// operation; this keeps waiting until one succeeds.
897    pub async fn await_receive(
898        &self,
899        account: Account,
900        position: EventLogId,
901    ) -> Result<(FinalReceiveOperationState, EventLogId), AwaitReceiveError> {
902        let mut position = position;
903
904        loop {
905            let (operation_id, next_position) =
906                self.next_receive_operation(account, position).await;
907
908            position = next_position;
909
910            let state = self
911                .await_final_receive_operation_state(operation_id)
912                .await?;
913
914            // A successful peg-in is terminal; an aborted one is retried as a
915            // new receive operation, so keep waiting.
916            if state == FinalReceiveOperationState::Success {
917                // Reaching `Success` only means the peg-in claim transaction was
918                // accepted into consensus. The ecash it mints is issued
919                // asynchronously by the primary module, so wait for those
920                // outputs before returning; otherwise the freshly claimed funds
921                // may not yet be reflected in the client's balance.
922                let operation = self.client_ctx.get_operation(operation_id).await?;
923
924                if let WalletOperationMeta::Receive(ReceiveMeta {
925                    change_outpoint_range,
926                    ..
927                }) = operation.meta::<WalletOperationMeta>()
928                {
929                    self.client_ctx
930                        .await_primary_module_outputs(
931                            operation_id,
932                            change_outpoint_range.into_iter().collect(),
933                        )
934                        .await?;
935                }
936
937                return Ok((state, position));
938            }
939        }
940    }
941
942    /// Scan the event log from `position` for the next [`ReceivePaymentEvent`]
943    /// crediting `account`, blocking until one is found, and return its
944    /// operation id together with the event log position just past it.
945    ///
946    /// Every account's deposits land in the same log, so a waiter has to skip
947    /// the other accounts' receives rather than report the first one it sees
948    /// as its own.
949    async fn next_receive_operation(
950        &self,
951        account: Account,
952        position: EventLogId,
953    ) -> (OperationId, EventLogId) {
954        let mut position = position;
955
956        loop {
957            let events = self
958                .client_ctx
959                .get_event_log(Some(position), EVENT_LOG_PAGE_SIZE)
960                .await;
961
962            for entry in &events {
963                position = entry.id().saturating_add(1);
964
965                if entry.module_kind() == Some(&KIND)
966                    && entry.kind == ReceivePaymentEvent::KIND
967                    && let Some(event) = entry.to_event::<ReceivePaymentEvent>()
968                    && event.account == account
969                {
970                    return (event.operation_id, position);
971                }
972            }
973
974            if events.is_empty() {
975                // Caught up with the log; wait for new events to be written.
976                sleep(Duration::from_secs(1)).await;
977            }
978        }
979    }
980
981    fn derive_address(&self, account: Account, index: u64) -> Address {
982        descriptor(
983            &self.cfg.bitcoin_pks,
984            &self
985                .derive_tweak(account, index)
986                .public_key()
987                .consensus_hash(),
988        )
989        .address(self.cfg.network)
990    }
991
992    fn derive_tweak(&self, account: Account, index: u64) -> Keypair {
993        self.account_secrets[usize::from(account.index())]
994            .child_key(ChildId(index))
995            .to_secp_key(secp256k1::SECP256K1)
996    }
997
998    /// Find the next valid index starting from (and including) `start_index`.
999    ///
1000    /// Only ~1/65536 indices are valid, so the search is CPU-bound and may scan
1001    /// many indices before finding one. The scan runs in bounded batches and
1002    /// yields to the executor between them, so it does not stall the runtime —
1003    /// important on wasm, which is single-threaded. It stops and returns `None`
1004    /// once the task group begins shutting down.
1005    async fn next_valid_index(
1006        &self,
1007        account: Account,
1008        start_index: u64,
1009        handle: &TaskHandle,
1010    ) -> Option<u64> {
1011        /// Indices to scan per batch before yielding to the executor.
1012        const SCAN_BATCH: u64 = 256;
1013
1014        let pks_hash = self.cfg.bitcoin_pks.consensus_hash();
1015
1016        let mut index = start_index;
1017
1018        while !handle.is_shutting_down() {
1019            for _ in 0..SCAN_BATCH {
1020                if is_potential_receive(
1021                    &self.derive_address(account, index).script_pubkey(),
1022                    &pks_hash,
1023                ) {
1024                    return Some(index);
1025                }
1026
1027                index += 1;
1028            }
1029
1030            // Hand control back to the executor between batches.
1031            sleep(Duration::ZERO).await;
1032        }
1033
1034        None
1035    }
1036
1037    /// Issue ecash for an unspent output with a given fee.
1038    ///
1039    /// Returns `None` if the output value cannot cover the fee, or if the
1040    /// remainder is too small to fund the claim transaction's fees.
1041    async fn receive_output(
1042        &self,
1043        account: Account,
1044        output_index: u64,
1045        value: bitcoin::Amount,
1046        address_index: u64,
1047        fee: bitcoin::Amount,
1048        outpoint: Option<bitcoin::OutPoint>,
1049    ) -> Option<(OperationId, TransactionId)> {
1050        let operation_id = OperationId::new_random();
1051
1052        let client_input = ClientInput::<WalletInput> {
1053            input: WalletInput::V0(WalletInputV0 {
1054                output_index,
1055                fee,
1056                tweak: self.derive_tweak(account, address_index).public_key(),
1057            }),
1058            keys: vec![self.derive_tweak(account, address_index)],
1059            amounts: Amounts::new_bitcoin(Amount::from_sats(value.checked_sub(fee)?.to_sat())),
1060        };
1061
1062        let client_input_sm = ClientInputSM::<WalletClientStateMachines> {
1063            state_machines: Arc::new(move |range: OutPointRange| {
1064                vec![WalletClientStateMachines::Receive(ReceiveStateMachine {
1065                    common: ReceiveSMCommon {
1066                        operation_id,
1067                        txid: range.txid(),
1068                        value,
1069                        fee,
1070                    },
1071                    state: ReceiveSMState::Funding,
1072                })]
1073            }),
1074        };
1075
1076        let client_input_bundle = self.client_ctx.make_client_inputs(ClientInputBundle::new(
1077            vec![client_input],
1078            vec![client_input_sm],
1079        ));
1080
1081        let address = self
1082            .derive_address(account, address_index)
1083            .as_unchecked()
1084            .clone();
1085
1086        let meta_address = address.clone();
1087        let range = self
1088            .client_ctx
1089            .finalize_and_submit_transaction_with_events(
1090                operation_id,
1091                WalletCommonInit::KIND.as_str(),
1092                move |change_outpoint_range| {
1093                    WalletOperationMeta::Receive(ReceiveMeta {
1094                        change_outpoint_range,
1095                        value,
1096                        fee,
1097                        address: Some(meta_address.clone()),
1098                        outpoint,
1099                    })
1100                },
1101                TransactionBuilder::new(account).with_inputs(client_input_bundle),
1102                vec![self.client_ctx.make_event(ReceivePaymentEvent {
1103                    operation_id,
1104                    value,
1105                    fee,
1106                    address,
1107                    outpoint,
1108                    account,
1109                })],
1110            )
1111            .await
1112            .ok()?;
1113
1114        Some((operation_id, range.txid()))
1115    }
1116
1117    fn spawn_output_scanner(&self, task_group: &TaskGroup, client_span: &tracing::Span) {
1118        let module = self.clone();
1119        let handle = task_group.make_handle();
1120
1121        task_group.spawn_cancellable_with_span(client_span.clone(), "output-scanner", async move {
1122            // Every account is seeded, not just the ones the user has opened:
1123            // a restored seed may have been paid into any of them, and an
1124            // account whose frontier was never derived would never be scanned
1125            // for. Not filtered by what the primary module supports: this runs
1126            // from `init`, before the client handle the query needs is set.
1127            //
1128            // Each account reads its stored index with a short-lived transaction,
1129            // runs the search with no transaction open, and inserts the result in
1130            // its own short transaction. This avoids holding a transaction snapshot
1131            // across a long-running CPU-bound search that might outlive RocksDB's
1132            // retained write history, causing a SnapshotTooOld error and panic on
1133            // commit. See: https://github.com/fedimint/fedimint/issues/9202
1134            for account in Account::ALL {
1135                let address_index_exists = {
1136                    let mut dbtx = module.db.begin_transaction().await;
1137                    dbtx.find_by_prefix(&ValidAddressIndexAccountPrefix(account))
1138                        .await
1139                        .next()
1140                        .await
1141                        .is_some()
1142                };
1143
1144                if address_index_exists {
1145                    continue;
1146                }
1147
1148                let Some(index) = module.next_valid_index(account, 0, &handle).await else {
1149                    return;
1150                };
1151
1152                let mut dbtx = module.db.begin_transaction().await;
1153                dbtx.insert_new_entry(&ValidAddressIndexKey(account, index), &())
1154                    .await;
1155                dbtx.commit_tx().await;
1156            }
1157
1158            loop {
1159                match module.check_outputs(&handle).await {
1160                    Ok(skip_wait) => {
1161                        if skip_wait {
1162                            continue;
1163                        }
1164                    }
1165                    Err(e) => {
1166                        warn!(target: LOG_CLIENT_MODULE_WALLETV2, "Failed to fetch outputs: {e}");
1167                    }
1168                }
1169
1170                sleep(fedimint_walletv2_common::sleep_duration()).await;
1171            }
1172        });
1173    }
1174
1175    async fn check_outputs(&self, handle: &TaskHandle) -> Result<bool, CheckOutputsError> {
1176        let mut dbtx = self.db.begin_transaction_nc().await;
1177
1178        let next_output_index = dbtx.get_value(&NextOutputIndexKey).await.unwrap_or(0);
1179
1180        // Every account's indices come out of one prefix scan, already tagged
1181        // with the account they belong to.
1182        let valid_indices: Vec<(Account, u64)> = dbtx
1183            .find_by_prefix(&ValidAddressIndexPrefix)
1184            .await
1185            .map(|entry| (entry.0.0, entry.0.1))
1186            .collect()
1187            .await;
1188
1189        let mut address_map: BTreeMap<ScriptBuf, (Account, u64)> = valid_indices
1190            .iter()
1191            .map(|&(account, i)| {
1192                (
1193                    self.derive_address(account, i).script_pubkey(),
1194                    (account, i),
1195                )
1196            })
1197            .collect();
1198
1199        // Highest index reached per account, so a match on one account's
1200        // frontier extends that account rather than the whole table's.
1201        let mut frontier: BTreeMap<Account, u64> = BTreeMap::new();
1202
1203        for &(account, i) in &valid_indices {
1204            frontier
1205                .entry(account)
1206                .and_modify(|highest| *highest = (*highest).max(i))
1207                .or_insert(i);
1208        }
1209
1210        let outputs = self
1211            .module_api
1212            .output_info_slice(next_output_index, next_output_index + SLICE_SIZE)
1213            .await?;
1214
1215        let returned_num = outputs.len();
1216        let mut matched_num: usize = 0;
1217
1218        for output in &outputs {
1219            if let Some(&(account, address_index)) = address_map.get(&output.script) {
1220                matched_num += 1;
1221
1222                // Claim before extending the valid index list: the index search
1223                // below is CPU-bound and can take longer than a short-lived
1224                // client process (e.g. a cli invocation) lives. The claim is
1225                // quick and the extension can be retried on the next scan.
1226                if !output.spent
1227                    && !self
1228                        .process_unspent_output(account, output, address_index)
1229                        .await?
1230                {
1231                    return Ok(false);
1232                }
1233
1234                let next_address_index = *frontier
1235                    .get(&account)
1236                    .expect("every account in the map has a frontier");
1237
1238                // If we used this account's highest valid index, add its next
1239                if address_index == next_address_index {
1240                    let Some(index) = self
1241                        .next_valid_index(account, next_address_index + 1, handle)
1242                        .await
1243                    else {
1244                        return Ok(false);
1245                    };
1246
1247                    let mut dbtx = self.db.begin_transaction().await;
1248
1249                    dbtx.insert_entry(&ValidAddressIndexKey(account, index), &())
1250                        .await;
1251
1252                    dbtx.commit_tx_result().await?;
1253
1254                    frontier.insert(account, index);
1255
1256                    address_map.insert(
1257                        self.derive_address(account, index).script_pubkey(),
1258                        (account, index),
1259                    );
1260                }
1261            }
1262
1263            let mut dbtx = self.db.begin_transaction().await;
1264
1265            dbtx.insert_entry(&NextOutputIndexKey, &(output.index + 1))
1266                .await;
1267
1268            dbtx.commit_tx_result().await?;
1269        }
1270
1271        debug!(
1272            target: LOG_CLIENT_MODULE_WALLETV2,
1273            next_output_index,
1274            returned_num,
1275            matched_num,
1276            valid_indices_num = valid_indices.len(),
1277            "Scanning for outputs"
1278        );
1279
1280        Ok(!outputs.is_empty())
1281    }
1282
1283    async fn process_unspent_output(
1284        &self,
1285        account: Account,
1286        output: &OutputInfo,
1287        address_index: u64,
1288    ) -> Result<bool, ProcessOutputError> {
1289        debug!(
1290            target: LOG_CLIENT_MODULE_WALLETV2,
1291            output_index = output.index,
1292            value_sat = output.value.to_sat(),
1293            address_index,
1294            outpoint = ?output.outpoint,
1295            "Discovered unspent walletv2 receive output"
1296        );
1297
1298        // In order to not overpay on fees we choose to wait,
1299        // the congestion will clear up within a few blocks.
1300        let pending_tx_chain_len = self.module_api.pending_tx_chain().await?.len();
1301        if 3 <= pending_tx_chain_len {
1302            debug!(
1303                target: LOG_CLIENT_MODULE_WALLETV2,
1304                output_index = output.index,
1305                pending_tx_chain_len,
1306                "Delaying walletv2 receive claim because pending transaction chain is full"
1307            );
1308            return Ok(false);
1309        }
1310
1311        let receive_fee = self
1312            .module_api
1313            .receive_fee()
1314            .await?
1315            .ok_or(ProcessOutputError::NoFeerate)?;
1316
1317        if let Some((operation_id, txid)) = self
1318            .receive_output(
1319                account,
1320                output.index,
1321                output.value,
1322                address_index,
1323                receive_fee,
1324                output.outpoint,
1325            )
1326            .await
1327        {
1328            debug!(
1329                target: LOG_CLIENT_MODULE_WALLETV2,
1330                output_index = output.index,
1331                ?operation_id,
1332                %txid,
1333                "Waiting for walletv2 receive claim acceptance"
1334            );
1335            self.client_ctx
1336                .transaction_updates(operation_id)
1337                .await
1338                .await_tx_accepted(txid)
1339                .await
1340                .map_err(ProcessOutputError::ClaimRejected)?;
1341            debug!(
1342                target: LOG_CLIENT_MODULE_WALLETV2,
1343                output_index = output.index,
1344                ?operation_id,
1345                %txid,
1346                "Walletv2 receive claim accepted"
1347            );
1348        } else {
1349            debug!(
1350                target: LOG_CLIENT_MODULE_WALLETV2,
1351                output_index = output.index,
1352                value_sat = output.value.to_sat(),
1353                fee_sat = receive_fee.to_sat(),
1354                "Skipping walletv2 receive claim; value cannot cover the claim fees"
1355            );
1356        }
1357
1358        Ok(true)
1359    }
1360}
1361
1362/// A failure to send an on-chain payment.
1363#[derive(Error, Debug)]
1364#[non_exhaustive]
1365pub enum SendError {
1366    #[error("The primary module only holds a balance for the primary account")]
1367    AccountNotSupported,
1368    /// The destination address is not valid on the federation's network.
1369    #[error("Address is from a different network than the federation")]
1370    WrongNetwork,
1371
1372    /// The value to send is below the federation's dust limit.
1373    #[error("The value is too small")]
1374    DustValue,
1375
1376    /// The federation could not be asked for the current on-chain fee.
1377    #[error("The federation returned an error")]
1378    Federation(#[source] Box<FederationError>),
1379
1380    /// The guardians have not agreed a feerate yet, so no on-chain fee can be
1381    /// quoted.
1382    #[error("No consensus feerate is available at this time")]
1383    NoConsensusFeerateAvailable,
1384
1385    /// The client cannot fund the wallet output this send needs.
1386    #[error("The client does not have sufficient funds to send the payment")]
1387    InsufficientFunds,
1388
1389    /// The destination is not an address type the federation can pay.
1390    #[error("Unsupported address type")]
1391    UnsupportedAddress,
1392
1393    /// The send transaction could not be submitted for a reason that is not
1394    /// about funding.
1395    #[error("The send transaction could not be submitted")]
1396    Failed(#[source] TransactionSubmitError),
1397}
1398
1399/// A failure to quote the fee for claiming an on-chain deposit.
1400#[derive(Error, Debug)]
1401#[non_exhaustive]
1402pub enum ReceiveError {
1403    #[error("The primary module only holds a balance for the primary account")]
1404    AccountNotSupported,
1405    /// The federation could not be asked for the current claim fee.
1406    #[error("The federation returned an error")]
1407    Federation(#[source] Box<FederationError>),
1408
1409    /// The guardians have not agreed a feerate yet, so no claim fee can be
1410    /// quoted.
1411    #[error("No consensus feerate is available at this time")]
1412    NoConsensusFeerateAvailable,
1413}
1414
1415/// A failure to wait for the next on-chain payment to be received.
1416#[derive(Debug, Error)]
1417#[non_exhaustive]
1418pub enum AwaitReceiveError {
1419    /// The receive operation could not be looked up.
1420    #[error("The receive operation could not be looked up")]
1421    Operation(#[from] OperationLookupError),
1422
1423    /// The deposit was claimed, but the ecash it mints was never issued.
1424    #[error("The ecash for the claimed deposit could not be issued")]
1425    Issuance(#[from] TransactionSubmitError),
1426}
1427
1428/// The deposits in `pending` that pay one of `ours`, ordered by outpoint, with
1429/// the mempool visibility of the query that reported them.
1430fn owned_receive_progress<A>(
1431    pending: &PendingOutputs,
1432    ours: &BTreeMap<ScriptBuf, A>,
1433    address: impl Fn(&A) -> Address,
1434) -> AllReceiveProgress {
1435    let mut deposits: Vec<_> = pending
1436        .outputs
1437        .iter()
1438        .filter_map(|output| {
1439            Some((
1440                address(ours.get(&output.script)?),
1441                output.outpoint,
1442                WalletClientModule::pending_progress(output, pending.block_count),
1443            ))
1444        })
1445        .collect();
1446
1447    deposits.sort_by_key(|(_, outpoint, _)| *outpoint);
1448
1449    AllReceiveProgress {
1450        deposits,
1451        mempool_visibility: pending.mempool_visibility,
1452    }
1453}
1454
1455/// A failure to look up the progress of an incoming peg-in.
1456#[derive(Debug, Error)]
1457#[non_exhaustive]
1458pub enum ReceiveProgressError {
1459    /// No guardian reports a deposit at this outpoint to one of our addresses.
1460    /// This includes a deposit that was reorged out or evicted since it was
1461    /// last seen.
1462    #[error("No deposit of ours at this outpoint")]
1463    UnknownDeposit,
1464
1465    /// The address was not handed out by [`WalletClientModule::receive`].
1466    #[error("Address was not derived by this client")]
1467    UnknownAddress,
1468}
1469
1470/// A failure while scanning the federation's outputs for payments to this
1471/// client.
1472#[derive(Debug, Error)]
1473enum CheckOutputsError {
1474    /// The federation did not serve the scan.
1475    #[error(transparent)]
1476    Federation(#[from] FederationError),
1477
1478    /// The scan's progress could not be committed.
1479    #[error(transparent)]
1480    Database(#[from] DatabaseError),
1481
1482    /// An unspent output paid to this client could not be claimed.
1483    #[error(transparent)]
1484    ProcessOutput(#[from] ProcessOutputError),
1485}
1486
1487/// A failure to claim an unspent output paid to this client.
1488#[derive(Debug, Error)]
1489enum ProcessOutputError {
1490    /// The federation could not report its pending transactions or the
1491    /// receive fee.
1492    #[error(transparent)]
1493    Federation(#[from] FederationError),
1494
1495    /// The federation has no consensus feerate to price the claim with.
1496    #[error("No consensus feerate is available")]
1497    NoFeerate,
1498
1499    /// The claim transaction was rejected.
1500    #[error("Claim transaction was rejected: {0}")]
1501    ClaimRejected(String),
1502}
1503
1504#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1505pub enum WalletClientStateMachines {
1506    Send(send_sm::SendStateMachine),
1507    Receive(receive_sm::ReceiveStateMachine),
1508}
1509
1510impl State for WalletClientStateMachines {
1511    type ModuleContext = WalletClientContext;
1512
1513    fn transitions(
1514        &self,
1515        context: &Self::ModuleContext,
1516        global_context: &DynGlobalClientContext,
1517    ) -> Vec<StateTransition<Self>> {
1518        match self {
1519            WalletClientStateMachines::Send(sm) => sm_enum_variant_translation!(
1520                sm.transitions(context, global_context),
1521                WalletClientStateMachines::Send
1522            ),
1523            WalletClientStateMachines::Receive(sm) => sm_enum_variant_translation!(
1524                sm.transitions(context, global_context),
1525                WalletClientStateMachines::Receive
1526            ),
1527        }
1528    }
1529
1530    fn operation_id(&self) -> OperationId {
1531        match self {
1532            WalletClientStateMachines::Send(sm) => sm.operation_id(),
1533            WalletClientStateMachines::Receive(sm) => sm.operation_id(),
1534        }
1535    }
1536}
1537
1538impl IntoDynInstance for WalletClientStateMachines {
1539    type DynType = DynState;
1540
1541    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
1542        DynState::from_typed(instance_id, self)
1543    }
1544}
1545
1546#[cfg(test)]
1547mod tests;