Skip to main content

fedimint_wallet_client/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::cast_possible_truncation)]
3#![allow(clippy::missing_errors_doc)]
4#![allow(clippy::missing_panics_doc)]
5#![allow(clippy::module_name_repetitions)]
6#![allow(clippy::must_use_candidate)]
7
8pub mod api;
9#[cfg(feature = "cli")]
10mod cli;
11
12mod backup;
13
14pub mod client_db;
15/// Legacy, state-machine based peg-ins, replaced by `pegin_monitor`
16/// but retained for time being to ensure existing peg-ins complete.
17mod deposit;
18/// Error types of the wallet client.
19pub mod error;
20pub mod events;
21use events::SendPaymentEvent;
22/// Peg-in monitor: a task monitoring deposit addresses for peg-ins.
23mod pegin_monitor;
24mod withdraw;
25
26use std::collections::{BTreeMap, BTreeSet};
27use std::future;
28use std::sync::Arc;
29use std::time::{Duration, SystemTime};
30
31use async_stream::{stream, try_stream};
32use backup::WalletModuleBackup;
33use bitcoin::address::NetworkUnchecked;
34use bitcoin::secp256k1::{All, SECP256K1, Secp256k1};
35use bitcoin::{Address, Network, ScriptBuf};
36use client_db::{DbKeyPrefix, PegInTweakIndexKey, SupportsSafeDepositKey, TweakIdx};
37use fedimint_api_client::api::{DynModuleApi, FederationResult};
38use fedimint_bitcoind::{
39    BitcoinRpcError, BitcoindTracked, DynBitcoindRpc, IBitcoindRpc, create_esplora_rpc,
40};
41use fedimint_client_module::error::{ClientModuleError, TransactionSubmitError};
42use fedimint_client_module::module::init::{
43    ClientModuleInit, ClientModuleInitArgs, ClientModuleRecoverArgs, RecoveryMode,
44};
45use fedimint_client_module::module::recovery::RecoveryProgress;
46use fedimint_client_module::module::{ClientContext, ClientModule, IClientModule, OutPointRange};
47use fedimint_client_module::oplog::UpdateStreamOrOutcome;
48use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
49use fedimint_client_module::transaction::{
50    ClientOutput, ClientOutputBundle, ClientOutputSM, FeeQuote, FeeQuoteRequest,
51    TransactionBuilder, max_affordable_send_amount,
52};
53use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
54use fedimint_core::core::{
55    Account, Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId,
56};
57use fedimint_core::db::{
58    Committable, Database, DatabaseError, DatabaseTransaction, IDatabaseTransactionOpsCoreTyped,
59};
60use fedimint_core::encoding::{Decodable, Encodable};
61use fedimint_core::envs::{BitcoinRpcConfig, is_running_in_test_env};
62use fedimint_core::module::{
63    Amounts, ApiAuth, ApiVersion, CommonModuleInit, ModuleCommon, ModuleConsensusVersion,
64    ModuleInit, MultiApiVersion,
65};
66use fedimint_core::task::{MaybeSend, MaybeSync, TaskGroup, sleep};
67use fedimint_core::util::backoff_util::background_backoff;
68use fedimint_core::util::{BoxStream, FmtCompact as _, backoff_util, retry};
69use fedimint_core::{
70    BitcoinHash, OutPoint, TransactionId, apply, async_trait_maybe_send, push_db_pair_items,
71    runtime, secp256k1,
72};
73use fedimint_derive_secret::{ChildId, DerivableSecret};
74use fedimint_logging::LOG_CLIENT_MODULE_WALLET;
75pub use fedimint_wallet_common as common;
76use fedimint_wallet_common::config::{FeeConsensus, WalletClientConfig};
77use fedimint_wallet_common::tweakable::Tweakable;
78pub use fedimint_wallet_common::*;
79use futures::{Stream, StreamExt, TryStreamExt as _};
80use rand::{Rng, thread_rng};
81use secp256k1::Keypair;
82use serde::{Deserialize, Serialize};
83use strum::IntoEnumIterator;
84use tokio::sync::watch;
85use tracing::{debug, instrument, warn};
86
87use crate::api::WalletFederationApi;
88use crate::backup::{FEDERATION_RECOVER_MAX_GAP, RecoveryStateV2, WalletRecovery};
89use crate::client_db::{
90    ClaimedPegInData, ClaimedPegInKey, ClaimedPegInPrefix, NextPegInTweakIndexKey,
91    PegInPoolCursorKey, PegInTweakIndexData, PegInTweakIndexPrefix, RecoveryFinalizedKey,
92    RecoveryStateKey, SupportsSafeDepositPrefix,
93};
94use crate::deposit::DepositStateMachine;
95pub use crate::error::{
96    ConsensusVersionVotingError, DepositAddressError, DepositProgressError,
97    MaxWithdrawableAmountError, PegInError, PegOutError, SubscribeDepositError,
98    SubscribeWithdrawError, WithdrawFeesError,
99};
100use crate::withdraw::{CreatedWithdrawState, WithdrawStateMachine, WithdrawStates};
101
102const WALLET_TWEAK_CHILD_ID: ChildId = ChildId(0);
103
104#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
105pub struct BitcoinTransactionData {
106    /// The bitcoin transaction is saved as soon as we see it so the transaction
107    /// can be re-transmitted if it's evicted from the mempool.
108    pub btc_transaction: bitcoin::Transaction,
109    /// Index of the deposit output
110    pub out_idx: u32,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
114pub enum DepositStateV1 {
115    WaitingForTransaction,
116    WaitingForConfirmation(BitcoinTransactionData),
117    Confirmed(BitcoinTransactionData),
118    Claimed(BitcoinTransactionData),
119    Failed(String),
120}
121
122/// How far an unclaimed deposit is from being claimable, as reported by
123/// [`WalletClientModule::deposit_progress`].
124#[derive(Debug, Clone, Eq, PartialEq)]
125pub struct DepositProgress {
126    pub outpoint: bitcoin::OutPoint,
127    pub value: bitcoin::Amount,
128    /// Zero while unmined. Reaches `required` exactly when the deposit can be
129    /// claimed and stays there.
130    pub confirmations: u64,
131    /// Confirmations at which the deposit becomes claimable. A deposit that
132    /// does not cover the peg-in fee is never claimed.
133    pub required: u64,
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
137pub enum DepositStateV2 {
138    WaitingForTransaction,
139    WaitingForConfirmation {
140        #[serde(with = "bitcoin::amount::serde::as_sat")]
141        btc_deposited: bitcoin::Amount,
142        btc_out_point: bitcoin::OutPoint,
143    },
144    Confirmed {
145        #[serde(with = "bitcoin::amount::serde::as_sat")]
146        btc_deposited: bitcoin::Amount,
147        btc_out_point: bitcoin::OutPoint,
148    },
149    Claimed {
150        #[serde(with = "bitcoin::amount::serde::as_sat")]
151        btc_deposited: bitcoin::Amount,
152        btc_out_point: bitcoin::OutPoint,
153    },
154    Failed(String),
155}
156
157/// Deposit address allocated by this client.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct DepositAddressInfo {
160    pub operation_id: OperationId,
161    pub address: Address,
162    pub tweak_idx: TweakIdx,
163}
164
165/// Result of [`WalletClientModule::allocate_deposit_address_pooled_stateless`].
166///
167/// Callers that need a custom address-picking strategy can use
168/// [`MaybeNewAddress::TooManyUnusedAddresses`] to see all currently reusable
169/// addresses instead of relying on this crate's round-robin policy.
170#[allow(clippy::enum_variant_names)]
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub enum MaybeNewAddress {
173    /// A new tweak/operation was created on this call.
174    NewAddress(DepositAddressInfo),
175    /// The unused-address gap is full. No new address was allocated.
176    ///
177    /// Reusable unused addresses are ordered by `creation_time` ascending.
178    TooManyUnusedAddresses(Vec<DepositAddressInfo>),
179}
180
181/// Outcome of [`WalletClientModule::allocate_deposit_address_pooled`], so
182/// callers can decide whether to perform per-operation initialization (notes,
183/// fee bookkeeping, metadata writes) — for `Reused` returns, that work was
184/// already done at the time of the original `Fresh` allocation and must not be
185/// repeated.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub enum AllocateDepositOutcome {
188    /// A new tweak/operation was created on this call.
189    Fresh,
190    /// An existing unused address was returned. The carried `TweakIdx` is the
191    /// same as the one returned in the tuple and refers to the original
192    /// allocation; it's exposed here as well for explicit diagnostic use.
193    Reused { original_tweak_idx: TweakIdx },
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
197pub enum WithdrawState {
198    Created,
199    Succeeded(bitcoin::Txid),
200    Failed(String),
201    // TODO: track refund
202    // Refunded,
203    // RefundFailed(String),
204}
205
206async fn next_withdraw_state<S>(stream: &mut S) -> Option<WithdrawStates>
207where
208    S: Stream<Item = WalletClientStates> + Unpin,
209{
210    loop {
211        if let WalletClientStates::Withdraw(ds) = stream.next().await? {
212            return Some(ds.state);
213        }
214        tokio::task::yield_now().await;
215    }
216}
217
218#[derive(Debug, Clone, Default)]
219// TODO: should probably move to DB
220pub struct WalletClientInit(pub Option<DynBitcoindRpc>);
221
222const SLICE_SIZE: u64 = 1000;
223
224impl WalletClientInit {
225    pub fn new(rpc: DynBitcoindRpc) -> Self {
226        Self(Some(rpc))
227    }
228
229    async fn recover_from_slices(
230        &self,
231        args: &ClientModuleRecoverArgs<Self>,
232        total_items: u64,
233    ) -> Option<fedimint_core::Amount> {
234        let data = WalletClientModuleData {
235            cfg: args.cfg().clone(),
236            module_root_secret: args.module_root_secret().clone(),
237        };
238
239        let mut state = RecoveryStateV2::new();
240
241        state.refill_pending_pool_up_to(&data, TweakIdx(FEDERATION_RECOVER_MAX_GAP));
242
243        for start in (0..total_items).step_by(SLICE_SIZE as usize) {
244            let end = std::cmp::min(start + SLICE_SIZE, total_items);
245
246            let items = args.module_api().fetch_recovery_slice(start, end).await;
247
248            for item in &items {
249                match item {
250                    RecoveryItem::Input { outpoint, script } => {
251                        state.handle_item(*outpoint, script, &data);
252                    }
253                }
254            }
255
256            args.update_recovery_progress(RecoveryProgress {
257                complete: end.try_into().unwrap_or(u32::MAX),
258                total: total_items.try_into().unwrap_or(u32::MAX),
259            });
260        }
261
262        let entries = (0..state.new_start_idx().0)
263            .map(|tweak_idx| {
264                let operation_id = data.derive_peg_in_script(TweakIdx(tweak_idx)).3;
265
266                let claimed = state
267                    .claimed_outpoints
268                    .get(&TweakIdx(tweak_idx))
269                    .cloned()
270                    .unwrap_or_default();
271
272                (
273                    TweakIdx(tweak_idx),
274                    PegInTweakIndexData {
275                        operation_id,
276                        creation_time: fedimint_core::time::now(),
277                        last_check_time: None,
278                        next_check_time: Some(fedimint_core::time::now()),
279                        claimed,
280                    },
281                )
282            })
283            .collect();
284
285        store_recovered_peg_in_indexes(args.db(), entries, state.new_start_idx()).await;
286
287        // The wallet only discovers which on-chain outputs belonged to the
288        // client during recovery; their value isn't known until the deposits
289        // are later claimed, so no amount is reported here.
290        None
291    }
292}
293
294/// Whether an earlier recovery run already committed its results.
295///
296/// The marker is the same one the history-based recovery stores through
297/// `store_finalized`. Older slices recoveries wrote no marker, but both
298/// recovery paths commit the next tweak index atomically with the recovered
299/// entries.
300///
301/// This is only a completion check during pending recovery: ordinary deposit
302/// address allocation also writes the cursor, but requires an initialized
303/// wallet. The wallet is unusable until recovery finishes.
304async fn recovery_already_finalized(db: &Database) -> bool {
305    let mut dbtx = db.begin_transaction_nc().await;
306    dbtx.get_value(&RecoveryFinalizedKey).await == Some(true)
307        || dbtx.get_value(&NextPegInTweakIndexKey).await.is_some()
308}
309
310/// Writes what a recovery run found together with the marker saying it
311/// finished, in one transaction, and reports whether it wrote anything.
312///
313/// Returns false without writing when a previous run already finalized.
314/// That case is reachable because the client only records a module's
315/// recovery as done after `recover()` returns, so a crash in between
316/// reruns this with the keys already present, and `insert_new_entry`
317/// panics on an existing key, on that open and every open after it.
318async fn store_recovered_peg_in_indexes(
319    db: &Database,
320    entries: Vec<(TweakIdx, PegInTweakIndexData)>,
321    new_start_idx: TweakIdx,
322) -> bool {
323    let mut dbtx = db.begin_transaction().await;
324
325    if dbtx.get_value(&RecoveryFinalizedKey).await == Some(true)
326        || dbtx.get_value(&NextPegInTweakIndexKey).await.is_some()
327    {
328        return false;
329    }
330
331    for (tweak_idx, entry) in entries {
332        dbtx.insert_new_entry(&PegInTweakIndexKey(tweak_idx), &entry)
333            .await;
334    }
335
336    dbtx.insert_new_entry(&NextPegInTweakIndexKey, &new_start_idx)
337        .await;
338    dbtx.insert_entry(&RecoveryFinalizedKey, &true).await;
339
340    dbtx.commit_tx().await;
341
342    true
343}
344
345impl ModuleInit for WalletClientInit {
346    type Common = WalletCommonInit;
347
348    async fn dump_database(
349        &self,
350        dbtx: &mut DatabaseTransaction<'_>,
351        prefix_names: Vec<String>,
352    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
353        let mut wallet_client_items: BTreeMap<String, Box<dyn erased_serde::Serialize + Send>> =
354            BTreeMap::new();
355        let filtered_prefixes = DbKeyPrefix::iter().filter(|f| {
356            prefix_names.is_empty() || prefix_names.contains(&f.to_string().to_lowercase())
357        });
358
359        for table in filtered_prefixes {
360            match table {
361                DbKeyPrefix::NextPegInTweakIndex => {
362                    if let Some(index) = dbtx.get_value(&NextPegInTweakIndexKey).await {
363                        wallet_client_items
364                            .insert("NextPegInTweakIndex".to_string(), Box::new(index));
365                    }
366                }
367                DbKeyPrefix::PegInTweakIndex => {
368                    push_db_pair_items!(
369                        dbtx,
370                        PegInTweakIndexPrefix,
371                        PegInTweakIndexKey,
372                        PegInTweakIndexData,
373                        wallet_client_items,
374                        "Peg-In Tweak Index"
375                    );
376                }
377                DbKeyPrefix::ClaimedPegIn => {
378                    push_db_pair_items!(
379                        dbtx,
380                        ClaimedPegInPrefix,
381                        ClaimedPegInKey,
382                        ClaimedPegInData,
383                        wallet_client_items,
384                        "Claimed Peg-In"
385                    );
386                }
387                DbKeyPrefix::RecoveryFinalized => {
388                    if let Some(val) = dbtx.get_value(&RecoveryFinalizedKey).await {
389                        wallet_client_items.insert("RecoveryFinalized".to_string(), Box::new(val));
390                    }
391                }
392                DbKeyPrefix::SupportsSafeDeposit => {
393                    push_db_pair_items!(
394                        dbtx,
395                        SupportsSafeDepositPrefix,
396                        SupportsSafeDepositKey,
397                        (),
398                        wallet_client_items,
399                        "Supports Safe Deposit"
400                    );
401                }
402                DbKeyPrefix::PegInPoolCursor => {
403                    if let Some(cursor) = dbtx.get_value(&PegInPoolCursorKey).await {
404                        wallet_client_items.insert("PegInPoolCursor".to_string(), Box::new(cursor));
405                    }
406                }
407                DbKeyPrefix::RecoveryState
408                | DbKeyPrefix::ExternalReservedStart
409                | DbKeyPrefix::CoreInternalReservedStart
410                | DbKeyPrefix::CoreInternalReservedEnd => {}
411            }
412        }
413
414        Box::new(wallet_client_items.into_iter())
415    }
416}
417
418#[apply(async_trait_maybe_send!)]
419impl ClientModuleInit for WalletClientInit {
420    type Module = WalletClientModule;
421
422    fn supported_api_versions(&self) -> MultiApiVersion {
423        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
424            .expect("no version conflicts")
425    }
426
427    async fn init(
428        &self,
429        args: &ClientModuleInitArgs<Self>,
430    ) -> Result<Self::Module, ClientModuleError> {
431        let data = WalletClientModuleData {
432            cfg: args.cfg().clone(),
433            module_root_secret: args.module_root_secret().clone(),
434        };
435
436        let db = args.db().clone();
437
438        let rpc_config = WalletClientModule::get_rpc_config(args.cfg());
439
440        // Priority:
441        // 1. user-provided bitcoind RPC from ClientBuilder::with_bitcoind_rpc
442        // 2. user-provided no-chain-id factory from
443        //    ClientBuilder::with_bitcoind_rpc_no_chain_id
444        // 3. WalletClientInit constructor
445        // 4. create from config (esplora)
446        let btc_rpc = if let Some(user_rpc) = args.user_bitcoind_rpc() {
447            user_rpc.clone()
448        } else if let Some(factory) = args.user_bitcoind_rpc_no_chain_id() {
449            if let Some(rpc) = factory(rpc_config.url.clone()).await {
450                rpc
451            } else {
452                self.0.clone().unwrap_or(
453                    create_esplora_rpc(&rpc_config.url).map_err(ClientModuleError::other)?,
454                )
455            }
456        } else {
457            self.0
458                .clone()
459                .unwrap_or(create_esplora_rpc(&rpc_config.url).map_err(ClientModuleError::other)?)
460        };
461        let btc_rpc = BitcoindTracked::new(btc_rpc, "wallet-client").into_dyn();
462
463        let module_api = args.module_api().clone();
464
465        let (pegin_claimed_sender, pegin_claimed_receiver) = watch::channel(());
466        let (pegin_monitor_wakeup_sender, pegin_monitor_wakeup_receiver) = watch::channel(());
467
468        Ok(WalletClientModule {
469            db,
470            data,
471            module_api,
472            notifier: args.notifier().clone(),
473            rpc: btc_rpc,
474            client_ctx: args.context(),
475            pegin_monitor_wakeup_sender,
476            pegin_monitor_wakeup_receiver,
477            pegin_claimed_receiver,
478            pegin_claimed_sender,
479            task_group: args.task_group().clone(),
480            client_span: args.client_span().clone(),
481            admin_auth: args.admin_auth().cloned(),
482        })
483    }
484
485    fn recovery_mode(&self) -> RecoveryMode {
486        RecoveryMode::Unusable
487    }
488
489    /// Wallet recovery
490    ///
491    /// Uses slice-based recovery if supported by the federation, otherwise
492    /// falls back to session-based history recovery.
493    async fn recover(
494        &self,
495        args: &ClientModuleRecoverArgs<Self>,
496        snapshot: Option<&<Self::Module as ClientModule>::Backup>,
497    ) -> Result<Option<fedimint_core::Amount>, ClientModuleError> {
498        // The client records completion only after this method returns. A prior
499        // run may have committed wallet data before being interrupted. Check
500        // before resuming history recovery or making any federation requests,
501        // including for older slices recoveries that did not write a marker.
502        if recovery_already_finalized(args.db()).await {
503            debug!(
504                target: LOG_CLIENT_MODULE_WALLET,
505                "Wallet recovery already finalized by an earlier run, nothing to redo"
506            );
507            return Ok(None);
508        }
509
510        // Check if V1 (session-based) recovery state exists (resuming interrupted
511        // recovery)
512        if args
513            .db()
514            .begin_transaction_nc()
515            .await
516            .get_value(&RecoveryStateKey)
517            .await
518            .is_some()
519        {
520            return args
521                .recover_from_history::<WalletRecovery>(self, snapshot)
522                .await;
523        }
524
525        // Determine which method to use based on endpoint availability. The
526        // count fetched here is reused by the slice recovery so that it is not
527        // requested a second time (and cannot transiently fail there).
528        match args.module_api().fetch_recovery_count().await {
529            Ok(total_items) => Ok(self.recover_from_slices(args, total_items).await),
530            Err(_) => {
531                args.recover_from_history::<WalletRecovery>(self, snapshot)
532                    .await
533            }
534        }
535    }
536
537    fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
538        Some(
539            DbKeyPrefix::iter()
540                .map(|p| p as u8)
541                .chain(
542                    DbKeyPrefix::ExternalReservedStart as u8
543                        ..=DbKeyPrefix::CoreInternalReservedEnd as u8,
544                )
545                .collect(),
546        )
547    }
548}
549
550#[derive(Debug, Clone, Serialize, Deserialize)]
551pub struct WalletOperationMeta {
552    pub variant: WalletOperationMetaVariant,
553    pub extra_meta: serde_json::Value,
554}
555
556#[derive(Debug, Clone, Serialize, Deserialize)]
557#[serde(rename_all = "snake_case")]
558pub enum WalletOperationMetaVariant {
559    Deposit {
560        address: Address<NetworkUnchecked>,
561        /// Added in 0.4.2, can be `None` for old deposits or `Some` for ones
562        /// using the pegin monitor. The value is the child index of the key
563        /// used to generate the address, so we can re-generate the secret key
564        /// from our root secret.
565        #[serde(default)]
566        tweak_idx: Option<TweakIdx>,
567        #[serde(default, skip_serializing_if = "Option::is_none")]
568        expires_at: Option<SystemTime>,
569    },
570    Withdraw {
571        address: Address<NetworkUnchecked>,
572        #[serde(with = "bitcoin::amount::serde::as_sat")]
573        amount: bitcoin::Amount,
574        fee: PegOutFees,
575        change: Vec<OutPoint>,
576    },
577
578    RbfWithdraw {
579        rbf: Rbf,
580        change: Vec<OutPoint>,
581    },
582}
583
584/// The non-resource, just plain-data parts of [`WalletClientModule`]
585#[derive(Debug, Clone)]
586pub struct WalletClientModuleData {
587    cfg: WalletClientConfig,
588    module_root_secret: DerivableSecret,
589}
590
591impl WalletClientModuleData {
592    fn derive_deposit_address(
593        &self,
594        idx: TweakIdx,
595    ) -> (Keypair, secp256k1::PublicKey, Address, OperationId) {
596        let idx = ChildId(idx.0);
597
598        let secret_tweak_key = self
599            .module_root_secret
600            .child_key(WALLET_TWEAK_CHILD_ID)
601            .child_key(idx)
602            .to_secp_key(fedimint_core::secp256k1::SECP256K1);
603
604        let public_tweak_key = secret_tweak_key.public_key();
605
606        let address = self
607            .cfg
608            .peg_in_descriptor
609            .tweak(&public_tweak_key, bitcoin::secp256k1::SECP256K1)
610            .address(self.cfg.network.0)
611            .unwrap();
612
613        // TODO: make hash?
614        let operation_id = OperationId(public_tweak_key.x_only_public_key().0.serialize());
615
616        (secret_tweak_key, public_tweak_key, address, operation_id)
617    }
618
619    fn derive_peg_in_script(
620        &self,
621        idx: TweakIdx,
622    ) -> (ScriptBuf, bitcoin::Address, Keypair, OperationId) {
623        let (secret_tweak_key, _, address, operation_id) = self.derive_deposit_address(idx);
624
625        (
626            self.cfg
627                .peg_in_descriptor
628                .tweak(&secret_tweak_key.public_key(), SECP256K1)
629                .script_pubkey(),
630            address,
631            secret_tweak_key,
632            operation_id,
633        )
634    }
635}
636
637#[derive(Debug)]
638pub struct WalletClientModule {
639    data: WalletClientModuleData,
640    db: Database,
641    module_api: DynModuleApi,
642    notifier: ModuleNotifier<WalletClientStates>,
643    rpc: DynBitcoindRpc,
644    client_ctx: ClientContext<Self>,
645    /// Updated to wake up pegin monitor
646    pegin_monitor_wakeup_sender: watch::Sender<()>,
647    pegin_monitor_wakeup_receiver: watch::Receiver<()>,
648    /// Called every time a peg-in was claimed
649    pegin_claimed_sender: watch::Sender<()>,
650    pegin_claimed_receiver: watch::Receiver<()>,
651    task_group: TaskGroup,
652    client_span: tracing::Span,
653    admin_auth: Option<ApiAuth>,
654}
655
656#[apply(async_trait_maybe_send!)]
657impl ClientModule for WalletClientModule {
658    type Init = WalletClientInit;
659    type Common = WalletModuleTypes;
660    type Backup = WalletModuleBackup;
661    type ModuleStateMachineContext = WalletClientContext;
662    type States = WalletClientStates;
663
664    fn context(&self) -> Self::ModuleStateMachineContext {
665        WalletClientContext {
666            rpc: self.rpc.clone(),
667            wallet_descriptor: self.cfg().peg_in_descriptor.clone(),
668            wallet_decoder: self.decoder(),
669            secp: Secp256k1::default(),
670            client_ctx: self.client_ctx.clone(),
671        }
672    }
673
674    async fn start(&self) {
675        self.task_group
676            .spawn_cancellable_with_span(self.client_span.clone(), "peg-in monitor", {
677                let client_ctx = self.client_ctx.clone();
678                let db = self.db.clone();
679                let btc_rpc = self.rpc.clone();
680                let module_api = self.module_api.clone();
681                let data = self.data.clone();
682                let pegin_claimed_sender = self.pegin_claimed_sender.clone();
683                let pegin_monitor_wakeup_receiver = self.pegin_monitor_wakeup_receiver.clone();
684                pegin_monitor::run_peg_in_monitor(
685                    client_ctx,
686                    db,
687                    btc_rpc,
688                    module_api,
689                    data,
690                    pegin_claimed_sender,
691                    pegin_monitor_wakeup_receiver,
692                )
693            });
694
695        self.task_group.spawn_cancellable_with_span(
696            self.client_span.clone(),
697            "supports-safe-deposit-version",
698            {
699                let db = self.db.clone();
700                let module_api = self.module_api.clone();
701
702                poll_supports_safe_deposit_version(db, module_api)
703            },
704        );
705    }
706
707    fn supports_backup(&self) -> bool {
708        true
709    }
710
711    async fn backup(&self) -> Result<backup::WalletModuleBackup, ClientModuleError> {
712        // fetch consensus height first
713        let session_count = self
714            .client_ctx
715            .global_api()
716            .session_count()
717            .await
718            .map_err(ClientModuleError::other)?;
719
720        let mut dbtx = self.db.begin_transaction_nc().await;
721        let next_pegin_tweak_idx = dbtx
722            .get_value(&NextPegInTweakIndexKey)
723            .await
724            .unwrap_or_default();
725        let claimed = dbtx
726            .find_by_prefix(&PegInTweakIndexPrefix)
727            .await
728            .filter_map(|(k, v)| async move {
729                if v.claimed.is_empty() {
730                    None
731                } else {
732                    Some(k.0)
733                }
734            })
735            .collect()
736            .await;
737        Ok(backup::WalletModuleBackup::new_v1(
738            session_count,
739            next_pegin_tweak_idx,
740            claimed,
741        ))
742    }
743
744    fn input_fee(
745        &self,
746        _amount: &Amounts,
747        _input: &<Self::Common as ModuleCommon>::Input,
748    ) -> Option<Amounts> {
749        Some(Amounts::new_bitcoin(self.cfg().fee_consensus.peg_in_abs))
750    }
751
752    fn output_fee(
753        &self,
754        _amount: &Amounts,
755        _output: &<Self::Common as ModuleCommon>::Output,
756    ) -> Option<Amounts> {
757        Some(Amounts::new_bitcoin(self.cfg().fee_consensus.peg_out_abs))
758    }
759
760    async fn handle_rpc(
761        &self,
762        method: String,
763        request: serde_json::Value,
764    ) -> BoxStream<'_, Result<serde_json::Value, ClientModuleError>> {
765        let stream: BoxStream<'_, Result<serde_json::Value, RpcError>> = Box::pin(try_stream! {
766            match method.as_str() {
767                "get_wallet_summary" => {
768                    let _req: WalletSummaryRequest = serde_json::from_value(request)?;
769                    let wallet_summary = self.get_wallet_summary()
770                        .await
771                        .expect("Failed to fetch wallet summary");
772                    let result = serde_json::to_value(&wallet_summary)
773                        .expect("Serialization error");
774                    yield result;
775                }
776                "get_block_count_local" => {
777                    let block_count = self.get_block_count_local().await
778                        .expect("Failed to fetch block count");
779                    yield serde_json::to_value(block_count)?;
780                }
781                "peg_in" => {
782                    let req: PegInRequest = serde_json::from_value(request)?;
783                    let response = self.peg_in(req)
784                        .await
785                        .map_err(RpcError::PegIn)?;
786                    let result = serde_json::to_value(&response)?;
787                    yield result;
788                },
789                "peg_out" => {
790                    let req: PegOutRequest = serde_json::from_value(request)?;
791                    let response = self.peg_out(req)
792                        .await
793                        .map_err(RpcError::PegOut)?;
794                    let result = serde_json::to_value(&response)?;
795                    yield result;
796                },
797                "subscribe_deposit" => {
798                    let req: SubscribeDepositRequest = serde_json::from_value(request)?;
799                    for await state in self.subscribe_deposit(req.operation_id).await?.into_stream() {
800                        yield serde_json::to_value(state)?;
801                    }
802                },
803                "subscribe_withdraw" => {
804                    let req: SubscribeWithdrawRequest = serde_json::from_value(request)?;
805                    for await state in self.subscribe_withdraw_updates(req.operation_id).await?.into_stream(){
806                        yield serde_json::to_value(state)?;
807                    }
808                }
809                _ => {
810                    Err(RpcError::UnknownMethod { method: method.clone() })?;
811                }
812            }
813        });
814        Box::pin(stream.map_err(ClientModuleError::other))
815    }
816
817    #[cfg(feature = "cli")]
818    async fn handle_cli_command(
819        &self,
820        args: &[std::ffi::OsString],
821    ) -> Result<serde_json::Value, ClientModuleError> {
822        cli::handle_cli_command(self, args)
823            .await
824            .map_err(ClientModuleError::other)
825    }
826}
827
828/// A failure of a wallet module RPC request.
829#[derive(Debug, thiserror::Error)]
830enum RpcError {
831    /// The request's parameters do not fit the method, or its response could
832    /// not be serialized.
833    #[error(transparent)]
834    Json(#[from] serde_json::Error),
835
836    /// The peg-in could not be started.
837    #[error("peg_in failed")]
838    PegIn(#[source] DepositAddressError),
839
840    /// The peg-out could not be started.
841    #[error("peg_out failed")]
842    PegOut(#[source] PegOutError),
843
844    /// The deposit's updates could not be followed.
845    #[error(transparent)]
846    SubscribeDeposit(#[from] SubscribeDepositError),
847
848    /// The withdrawal's updates could not be followed.
849    #[error(transparent)]
850    SubscribeWithdraw(#[from] SubscribeWithdrawError),
851
852    /// The request names a method the module does not have.
853    #[error("Unknown method: {method}")]
854    UnknownMethod { method: String },
855}
856
857#[derive(Deserialize)]
858struct WalletSummaryRequest {}
859
860#[derive(Debug, Clone)]
861pub struct WalletClientContext {
862    rpc: DynBitcoindRpc,
863    wallet_descriptor: PegInDescriptor,
864    wallet_decoder: Decoder,
865    secp: Secp256k1<All>,
866    pub client_ctx: ClientContext<WalletClientModule>,
867}
868
869#[derive(Debug, Clone, Serialize, Deserialize)]
870pub struct PegInRequest {
871    pub extra_meta: serde_json::Value,
872}
873
874#[derive(Deserialize)]
875struct SubscribeDepositRequest {
876    operation_id: OperationId,
877}
878
879#[derive(Deserialize)]
880struct SubscribeWithdrawRequest {
881    operation_id: OperationId,
882}
883
884#[derive(Debug, Clone, Serialize, Deserialize)]
885pub struct PegInResponse {
886    pub deposit_address: Address<NetworkUnchecked>,
887    pub operation_id: OperationId,
888}
889
890#[derive(Debug, Clone, Serialize, Deserialize)]
891pub struct PegOutRequest {
892    pub amount_sat: u64,
893    pub destination_address: Address<NetworkUnchecked>,
894    pub extra_meta: serde_json::Value,
895}
896
897#[derive(Debug, Clone, Serialize, Deserialize)]
898pub struct PegOutResponse {
899    pub operation_id: OperationId,
900}
901
902impl Context for WalletClientContext {
903    const KIND: Option<ModuleKind> = Some(KIND);
904}
905
906impl WalletClientModule {
907    fn cfg(&self) -> &WalletClientConfig {
908        &self.data.cfg
909    }
910
911    fn get_rpc_config(cfg: &WalletClientConfig) -> BitcoinRpcConfig {
912        match BitcoinRpcConfig::get_defaults_from_env_vars() {
913            Ok(rpc_config) => {
914                // TODO: Wallet client cannot support bitcoind RPC until the bitcoin dep is
915                // updated to 0.30
916                if rpc_config.kind == "bitcoind" {
917                    cfg.default_bitcoin_rpc.clone()
918                } else {
919                    rpc_config
920                }
921            }
922            _ => cfg.default_bitcoin_rpc.clone(),
923        }
924    }
925
926    pub fn get_network(&self) -> Network {
927        self.cfg().network.0
928    }
929
930    pub fn get_finality_delay(&self) -> u32 {
931        self.cfg().finality_delay
932    }
933
934    /// Confirmations a deposit needs before this client can claim it.
935    pub fn required_confirmations(&self) -> u64 {
936        pegin_monitor::required_confirmations(self.cfg().finality_delay)
937    }
938
939    pub fn get_fee_consensus(&self) -> FeeConsensus {
940        self.cfg().fee_consensus
941    }
942
943    async fn allocate_deposit_address_inner(
944        &self,
945        dbtx: &mut DatabaseTransaction<'_>,
946    ) -> DepositAddressInfo {
947        dbtx.ensure_isolated().expect("Must be isolated db");
948
949        let tweak_idx = get_next_peg_in_tweak_child_id(dbtx).await;
950        let (_secret_tweak_key, _, address, operation_id) =
951            self.data.derive_deposit_address(tweak_idx);
952
953        let now = fedimint_core::time::now();
954
955        dbtx.insert_new_entry(
956            &PegInTweakIndexKey(tweak_idx),
957            &PegInTweakIndexData {
958                creation_time: now,
959                next_check_time: Some(now),
960                last_check_time: None,
961                operation_id,
962                claimed: vec![],
963            },
964        )
965        .await;
966
967        DepositAddressInfo {
968            operation_id,
969            address,
970            tweak_idx,
971        }
972    }
973
974    /// Fetches the fees that would need to be paid to make the withdraw request
975    /// using [`Self::withdraw`] work *right now*.
976    ///
977    /// Note that we do not receive a guarantee that these fees will be valid in
978    /// the future, thus even the next second using these fees *may* fail.
979    /// The caller should be prepared to retry with a new fee estimate.
980    pub async fn get_withdraw_fees(
981        &self,
982        address: &bitcoin::Address,
983        amount: bitcoin::Amount,
984    ) -> Result<PegOutFees, WithdrawFeesError> {
985        self.module_api
986            .fetch_peg_out_fees(address, amount)
987            .await?
988            .ok_or(WithdrawFeesError::NoQuote)
989    }
990
991    /// Computes the federation fee a peg-out of an on-chain output worth
992    /// `amount` (the withdrawal amount plus the on-chain miner fee) would
993    /// incur, without submitting anything.
994    ///
995    /// A peg-out submits a single wallet output worth `amount`; the primary
996    /// module balances it by spending ecash to fund the output and minting any
997    /// change. This quotes the fee of that transaction — the wallet (peg-out)
998    /// output fee, the mint input fees on the funding notes, any mint change
999    /// output fees, and sub-denomination dust — via the shared, module-agnostic
1000    /// fee quote.
1001    ///
1002    /// The on-chain Bitcoin miner fee is deliberately excluded: it is part of
1003    /// the output `amount` (see [`Self::get_withdraw_fees`]), not the
1004    /// on-federation transaction fee.
1005    pub async fn send_fee_quote(
1006        &self,
1007        amount: bitcoin::Amount,
1008    ) -> Result<FeeQuote, TransactionSubmitError> {
1009        let amount = fedimint_core::Amount::from_sats(amount.to_sat());
1010        self.client_ctx
1011            .fee_quote(
1012                OperationId::new_random(),
1013                FeeQuoteRequest {
1014                    input_amount: Amounts::ZERO,
1015                    output_amount: Amounts::new_bitcoin(amount),
1016                    input_fee: Amounts::ZERO,
1017                    output_fee: Amounts::new_bitcoin(self.cfg().fee_consensus.peg_out_abs),
1018                    account: Account::Primary,
1019                },
1020            )
1021            .await
1022    }
1023
1024    /// Finds the largest amount that can be withdrawn in full out of
1025    /// `balance` — the amount a "withdraw everything" sweep should use —
1026    /// together with the peg-out fees to submit it with.
1027    ///
1028    /// Withdrawing `amount` submits a peg-out output worth `amount +
1029    /// peg_out_fees` (the on-chain miner fee is carried inside the output, see
1030    /// [`WalletOutputV0::amount`]) and funding that output costs an additional
1031    /// federation fee — the peg-out output fee, the mint input fees on the
1032    /// funding notes, any mint change output fees and sub-denomination dust —
1033    /// as quoted by [`Self::send_fee_quote`].
1034    ///
1035    /// Both returned values must be passed to [`Self::withdraw`] together. The
1036    /// federation rebuilds the peg-out for the exact amount submitted and
1037    /// rejects it unless the declared `total_weight` matches what it computed
1038    /// (`WalletOutputError::TxWeightIncorrect`), so the fees are re-quoted here
1039    /// at the amount being returned rather than at the balance.
1040    ///
1041    /// This costs exactly two [`Self::get_withdraw_fees`] round trips. The
1042    /// first, at the full balance, is an upper bound on the miner fee — the
1043    /// federation selects UTXOs until they cover the amount, so the weight is
1044    /// monotone in it — and sizing the withdrawal against that upper bound can
1045    /// only leave the result more affordable once the true, smaller fee
1046    /// replaces it. The maximum itself is then found by binary search over the
1047    /// real fee quote (see [`max_affordable_send_amount`]), which needs no
1048    /// further round trips because [`Self::send_fee_quote`] is a local dry-run.
1049    ///
1050    /// Sizing against the upper bound means a sweep may leave a small
1051    /// remainder behind. The quote is point-in-time: if the federation's UTXO
1052    /// set or feerate moves before the peg-out is processed it is rejected, and
1053    /// the caller should retry with a fresh quote.
1054    ///
1055    /// Returns [`MaxWithdrawableAmountError::BalanceTooLow`] if the balance
1056    /// cannot cover the destination's dust limit plus fees, or
1057    /// [`MaxWithdrawableAmountError::Quote`] if the fee probe itself failed.
1058    pub async fn max_withdrawable_amount(
1059        &self,
1060        address: &bitcoin::Address,
1061        balance: fedimint_core::Amount,
1062    ) -> Result<(bitcoin::Amount, PegOutFees), MaxWithdrawableAmountError> {
1063        // Upper bound on the miner fee: the weight only grows as the federation
1064        // has to reach for more UTXOs, so no smaller withdrawal costs more.
1065        let max_fees = self
1066            .get_withdraw_fees(
1067                address,
1068                bitcoin::Amount::from_sat(balance.sats_round_down()),
1069            )
1070            .await?;
1071        let max_fee_msats = fedimint_core::Amount::from_sats(max_fees.amount().to_sat());
1072        let dust_limit = address.script_pubkey().minimal_non_dust();
1073
1074        let max = max_affordable_send_amount(
1075            balance,
1076            fedimint_core::Amount::from_sats(dust_limit.to_sat()),
1077            balance,
1078            // A peg-out funds a whole number of sats, so round the probe up to
1079            // the next sat before adding the miner fee; the solver searches
1080            // millisatoshis.
1081            |amount: fedimint_core::Amount| {
1082                fedimint_core::Amount::from_sats(amount.msats.div_ceil(1000)) + max_fee_msats
1083            },
1084            |funded: fedimint_core::Amount| {
1085                self.send_fee_quote(bitcoin::Amount::from_sat(funded.msats / 1000))
1086            },
1087        )
1088        .await
1089        .map_err(MaxWithdrawableAmountError::Quote)?
1090        .ok_or(MaxWithdrawableAmountError::BalanceTooLow {
1091            balance,
1092            dust_limit,
1093        })?;
1094
1095        // `gross_up` rounded up to whole satoshis, so the largest affordable
1096        // amount already sits on a satoshi boundary; no value is lost here.
1097        let amount = bitcoin::Amount::from_sat(max.msats.div_ceil(1000));
1098
1099        // Re-quote at the amount actually being withdrawn. This is the fee the
1100        // federation recomputes for that amount, so the declared weight
1101        // matches; it is at most `max_fees`, which is what keeps `amount`
1102        // affordable.
1103        let fees = self.get_withdraw_fees(address, amount).await?;
1104
1105        Ok((amount, fees))
1106    }
1107
1108    /// Returns a summary of the wallet's coins
1109    pub async fn get_wallet_summary(&self) -> FederationResult<WalletSummary> {
1110        self.module_api.fetch_wallet_summary().await
1111    }
1112
1113    pub async fn get_block_count_local(&self) -> FederationResult<u32> {
1114        self.module_api.fetch_block_count_local().await
1115    }
1116
1117    pub fn create_withdraw_output(
1118        &self,
1119        operation_id: OperationId,
1120        address: bitcoin::Address,
1121        amount: bitcoin::Amount,
1122        fees: PegOutFees,
1123    ) -> ClientOutputBundle<WalletOutput, WalletClientStates> {
1124        let output = WalletOutput::new_v0_peg_out(address, amount, fees);
1125
1126        let amount = output.maybe_v0_ref().expect("v0 output").amount().into();
1127
1128        let sm_gen = move |out_point_range: OutPointRange| {
1129            assert_eq!(out_point_range.count(), 1);
1130            let out_idx = out_point_range.start_idx();
1131            vec![WalletClientStates::Withdraw(WithdrawStateMachine {
1132                operation_id,
1133                state: WithdrawStates::Created(CreatedWithdrawState {
1134                    fm_outpoint: OutPoint {
1135                        txid: out_point_range.txid(),
1136                        out_idx,
1137                    },
1138                }),
1139            })]
1140        };
1141
1142        ClientOutputBundle::new(
1143            vec![ClientOutput::<WalletOutput> {
1144                output,
1145                amounts: Amounts::new_bitcoin(amount),
1146            }],
1147            vec![ClientOutputSM::<WalletClientStates> {
1148                state_machines: Arc::new(sm_gen),
1149            }],
1150        )
1151    }
1152
1153    pub async fn peg_in(&self, req: PegInRequest) -> Result<PegInResponse, DepositAddressError> {
1154        let deposit_address = self.safe_allocate_deposit_address(req.extra_meta).await?;
1155
1156        Ok(PegInResponse {
1157            deposit_address: deposit_address.address.into_unchecked(),
1158            operation_id: deposit_address.operation_id,
1159        })
1160    }
1161
1162    pub async fn peg_out(&self, req: PegOutRequest) -> Result<PegOutResponse, PegOutError> {
1163        let amount = bitcoin::Amount::from_sat(req.amount_sat);
1164        let network = self.get_network();
1165        let destination = req
1166            .destination_address
1167            .require_network(network)
1168            .map_err(|_| PegOutError::WrongNetwork { expected: network })?;
1169
1170        let fees = self.get_withdraw_fees(&destination, amount).await?;
1171        let operation_id = self
1172            .withdraw(&destination, amount, fees, req.extra_meta)
1173            .await?;
1174
1175        Ok(PegOutResponse { operation_id })
1176    }
1177
1178    pub fn create_rbf_withdraw_output(
1179        &self,
1180        operation_id: OperationId,
1181        rbf: &Rbf,
1182    ) -> ClientOutputBundle<WalletOutput, WalletClientStates> {
1183        let output = WalletOutput::new_v0_rbf(rbf.fees, rbf.txid);
1184
1185        let amount = output.maybe_v0_ref().expect("v0 output").amount().into();
1186
1187        let sm_gen = move |out_point_range: OutPointRange| {
1188            assert_eq!(out_point_range.count(), 1);
1189            let out_idx = out_point_range.start_idx();
1190            vec![WalletClientStates::Withdraw(WithdrawStateMachine {
1191                operation_id,
1192                state: WithdrawStates::Created(CreatedWithdrawState {
1193                    fm_outpoint: OutPoint {
1194                        txid: out_point_range.txid(),
1195                        out_idx,
1196                    },
1197                }),
1198            })]
1199        };
1200
1201        ClientOutputBundle::new(
1202            vec![ClientOutput::<WalletOutput> {
1203                output,
1204                amounts: Amounts::new_bitcoin(amount),
1205            }],
1206            vec![ClientOutputSM::<WalletClientStates> {
1207                state_machines: Arc::new(sm_gen),
1208            }],
1209        )
1210    }
1211
1212    pub async fn btc_tx_has_no_size_limit(&self) -> FederationResult<bool> {
1213        Ok(self.module_api.module_consensus_version().await? >= ModuleConsensusVersion::new(2, 2))
1214    }
1215
1216    /// Returns true if the federation's wallet module consensus version
1217    /// supports processing all deposits.
1218    ///
1219    /// This method is safe to call offline, since it first attempts to read a
1220    /// key from the db that represents the client has previously been able to
1221    /// verify the wallet module consensus version. If the client has not
1222    /// verified the version, it must be online to fetch the latest wallet
1223    /// module consensus version.
1224    pub async fn supports_safe_deposit(&self) -> bool {
1225        if supports_safe_deposit_verified(&self.db).await {
1226            return true;
1227        }
1228
1229        verify_supports_safe_deposit(&self.db, &self.module_api)
1230            .await
1231            .unwrap_or(false)
1232    }
1233
1234    /// Allocates a deposit address controlled by the federation, guaranteeing
1235    /// safe handling of all deposits, including on-chain transactions exceeding
1236    /// `ALEPH_BFT_UNIT_BYTE_LIMIT`.
1237    ///
1238    /// Returns an error if the client has never been online to verify the
1239    /// federation's wallet module consensus version supports processing all
1240    /// deposits.
1241    pub async fn safe_allocate_deposit_address<M>(
1242        &self,
1243        extra_meta: M,
1244    ) -> Result<DepositAddressInfo, DepositAddressError>
1245    where
1246        M: Serialize + MaybeSend + MaybeSync,
1247    {
1248        if !self.supports_safe_deposit().await {
1249            return Err(DepositAddressError::SafeDepositUnverified);
1250        }
1251
1252        self.allocate_deposit_address_expert_only(extra_meta).await
1253    }
1254
1255    /// Allocates a deposit address that is controlled by the federation.
1256    ///
1257    /// This is an EXPERT ONLY method intended for power users such as Lightning
1258    /// gateways allocating liquidity, and we discourage exposing peg-in
1259    /// functionality to everyday users of a Fedimint wallet due to the
1260    /// following two limitations:
1261    ///
1262    /// The transaction sending to this address needs to be smaller than 40KB in
1263    /// order for the peg-in to be claimable. If the transaction is too large,
1264    /// funds will be lost.
1265    ///
1266    /// In the future, federations will also enforce a minimum peg-in amount to
1267    /// prevent accumulation of dust UTXOs. Peg-ins under this minimum cannot be
1268    /// claimed and funds will be lost.
1269    ///
1270    /// Everyday users should rely on Lightning to move funds into the
1271    /// federation.
1272    pub async fn allocate_deposit_address_expert_only<M>(
1273        &self,
1274        extra_meta: M,
1275    ) -> Result<DepositAddressInfo, DepositAddressError>
1276    where
1277        M: Serialize + MaybeSend + MaybeSync,
1278    {
1279        let extra_meta_value =
1280            serde_json::to_value(extra_meta).expect("Failed to serialize extra meta");
1281        let deposit_address = self
1282            .db
1283            .autocommit(
1284                move |dbtx, _| {
1285                    let extra_meta_value_inner = extra_meta_value.clone();
1286                    Box::pin(async move {
1287                        let deposit_address = self.allocate_deposit_address_inner(dbtx).await;
1288
1289                        self.client_ctx
1290                            .manual_operation_start_dbtx(
1291                                dbtx,
1292                                deposit_address.operation_id,
1293                                Account::Primary,
1294                                WalletCommonInit::KIND.as_str(),
1295                                WalletOperationMeta {
1296                                    variant: WalletOperationMetaVariant::Deposit {
1297                                        address: deposit_address.address.clone().into_unchecked(),
1298                                        tweak_idx: Some(deposit_address.tweak_idx),
1299                                        expires_at: None,
1300                                    },
1301                                    extra_meta: extra_meta_value_inner,
1302                                },
1303                                vec![],
1304                            )
1305                            .await?;
1306
1307                        debug!(
1308                            target: LOG_CLIENT_MODULE_WALLET,
1309                            tweak_idx = %deposit_address.tweak_idx,
1310                            address = %deposit_address.address,
1311                            "Derived a new deposit address"
1312                        );
1313
1314                        // Begin watching the script address
1315                        self.rpc
1316                            .watch_script_history(&deposit_address.address.script_pubkey())
1317                            .await?;
1318
1319                        let sender = self.pegin_monitor_wakeup_sender.clone();
1320                        dbtx.on_commit(move || {
1321                            sender.send_replace(());
1322                        });
1323
1324                        Ok(deposit_address)
1325                    })
1326                },
1327                Some(100),
1328            )
1329            .await?;
1330
1331        Ok(deposit_address)
1332    }
1333
1334    /// Allocate a deposit address, bounding the gap of consecutive unused
1335    /// addresses past the last-used one, without selecting a reusable address.
1336    ///
1337    /// "Unused" here means `PegInTweakIndexData::claimed.is_empty()` — the
1338    /// `pegin_monitor` has not yet successfully claimed any deposit on this
1339    /// address. There is a small race window where a deposit has been
1340    /// observed in the mempool / awaiting confirmations but not yet claimed,
1341    /// in which case the address still looks unused. Reusing such an address
1342    /// is benign in practice: `pegin_monitor` claims any number of deposits
1343    /// per address.
1344    ///
1345    /// Let `gap` be the count of unused tweak indices strictly greater than
1346    /// the highest used index (or the count of all allocated tweaks if none
1347    /// have been used yet). Semantics:
1348    ///   - If `gap >= max_gap_size` and there is at least one unused address,
1349    ///     returns all those addresses with
1350    ///     [`MaybeNewAddress::TooManyUnusedAddresses`].
1351    ///   - Otherwise, allocates a new address (equivalent to
1352    ///     [`Self::allocate_deposit_address_expert_only`]) and returns it with
1353    ///     [`MaybeNewAddress::NewAddress`].
1354    ///
1355    /// `max_gap_size == 0` therefore means "only allocate fresh when the
1356    /// previous address was already used". The very first call still
1357    /// allocates fresh because there are no addresses to reuse.
1358    ///
1359    /// `max_gap_size == usize::MAX` makes this method behave like
1360    /// [`Self::allocate_deposit_address_expert_only`] — always allocating a new
1361    /// address.
1362    ///
1363    /// Reusable addresses are ordered by `creation_time` ascending. This lets
1364    /// callers that need a custom selection strategy choose from all available
1365    /// candidates.
1366    ///
1367    /// Caveats inherited from
1368    /// [`Self::allocate_deposit_address_expert_only`] (40KB tx limit, future
1369    /// minimum peg-in amount) apply equally to newly allocated and reused
1370    /// addresses.
1371    pub async fn allocate_deposit_address_pooled_stateless(
1372        &self,
1373        max_gap_size: usize,
1374    ) -> Result<MaybeNewAddress, DepositAddressError> {
1375        let max_gap_size_u64 = u64::try_from(max_gap_size).unwrap_or(u64::MAX);
1376        let extra_meta_value = serde_json::Value::Null;
1377        let result = self
1378            .db
1379            .autocommit(
1380                move |dbtx, _| {
1381                    let extra_meta_value_inner = extra_meta_value.clone();
1382                    Box::pin(async move {
1383                        let unused = self.unused_pooled_deposit_addresses(dbtx).await;
1384
1385                        if max_gap_size_u64 <= unused.len() as u64 && !unused.is_empty() {
1386                            let addresses = unused
1387                                .into_iter()
1388                                .map(|(tweak_idx, data)| {
1389                                    let (_script, address, _key, operation_id) =
1390                                        self.data.derive_peg_in_script(tweak_idx);
1391
1392                                    debug_assert_eq!(operation_id, data.operation_id);
1393
1394                                    DepositAddressInfo {
1395                                        operation_id,
1396                                        address,
1397                                        tweak_idx,
1398                                    }
1399                                })
1400                                .collect();
1401
1402                            return Ok::<_, DepositAddressError>(
1403                                MaybeNewAddress::TooManyUnusedAddresses(addresses),
1404                            );
1405                        }
1406
1407                        let deposit_address = self.allocate_deposit_address_inner(dbtx).await;
1408
1409                        self.client_ctx
1410                            .manual_operation_start_dbtx(
1411                                dbtx,
1412                                deposit_address.operation_id,
1413                                Account::Primary,
1414                                WalletCommonInit::KIND.as_str(),
1415                                WalletOperationMeta {
1416                                    variant: WalletOperationMetaVariant::Deposit {
1417                                        address: deposit_address.address.clone().into_unchecked(),
1418                                        tweak_idx: Some(deposit_address.tweak_idx),
1419                                        expires_at: None,
1420                                    },
1421                                    extra_meta: extra_meta_value_inner,
1422                                },
1423                                vec![],
1424                            )
1425                            .await?;
1426
1427                        debug!(
1428                            target: LOG_CLIENT_MODULE_WALLET,
1429                            tweak_idx = %deposit_address.tweak_idx,
1430                            address = %deposit_address.address,
1431                            "Derived a new pooled deposit address"
1432                        );
1433
1434                        self.rpc
1435                            .watch_script_history(&deposit_address.address.script_pubkey())
1436                            .await?;
1437
1438                        let sender = self.pegin_monitor_wakeup_sender.clone();
1439                        dbtx.on_commit(move || {
1440                            sender.send_replace(());
1441                        });
1442
1443                        Ok(MaybeNewAddress::NewAddress(deposit_address))
1444                    })
1445                },
1446                Some(100),
1447            )
1448            .await?;
1449
1450        Ok(result)
1451    }
1452
1453    async fn unused_pooled_deposit_addresses(
1454        &self,
1455        dbtx: &mut DatabaseTransaction<'_>,
1456    ) -> Vec<(TweakIdx, PegInTweakIndexData)> {
1457        // Walk peg-in tweaks in descending order, taking unused ones
1458        // (`claimed.is_empty()`) until we hit a used one. That gives us exactly
1459        // the trailing gap — `gap + 1` reads regardless of total tweak count.
1460        // No RPC and no separately-maintained `last_used` index needed.
1461        let mut unused: Vec<(TweakIdx, PegInTweakIndexData)> = dbtx
1462            .find_by_prefix_sorted_descending(&PegInTweakIndexPrefix)
1463            .await
1464            .take_while(|(_, d)| std::future::ready(d.claimed.is_empty()))
1465            .map(|(k, v)| (k.0, v))
1466            .collect()
1467            .await;
1468
1469        // Order by `creation_time` ascending for caller selection and stable
1470        // wraparound after stateful reuse mutates `creation_time`.
1471        unused.sort_by_key(|(t, d)| (d.creation_time, *t));
1472        unused
1473    }
1474
1475    /// Allocate a deposit address, bounding the gap of consecutive unused
1476    /// addresses past the last-used one.
1477    ///
1478    /// This is a stateful wrapper over
1479    /// [`Self::allocate_deposit_address_pooled_stateless`]. If the stateless
1480    /// method returns [`MaybeNewAddress::TooManyUnusedAddresses`], this method
1481    /// picks one of those addresses with a persisted round-robin cursor and
1482    /// returns it with [`AllocateDepositOutcome::Reused`].
1483    ///
1484    /// Selection policy when reusing: round-robin over unused addresses
1485    /// ordered by `creation_time` ascending, with the cursor persisted
1486    /// per-client in the wallet module's DB. The cursor stores the next
1487    /// tweak index to consider; after picking idx X it advances to X+1, and
1488    /// when no candidate has `tweak_idx >= cursor` it wraps to the
1489    /// oldest-by-`creation_time` candidate. This gives the caller the
1490    /// predictable "cycle through the unused addresses" behavior.
1491    ///
1492    /// On reuse the `creation_time` and check-schedule fields of the
1493    /// underlying tweak entry are reset to "now", so `pegin_monitor`'s
1494    /// age-proportional polling delay restarts from zero. Without this an
1495    /// old entry would keep its long stale next-check delay and a user
1496    /// sending to it could wait a long time before the client noticed.
1497    #[allow(clippy::too_many_lines)]
1498    pub async fn allocate_deposit_address_pooled(
1499        &self,
1500        max_gap_size: usize,
1501    ) -> Result<(DepositAddressInfo, AllocateDepositOutcome), DepositAddressError> {
1502        let stateless = self
1503            .allocate_deposit_address_pooled_stateless(max_gap_size)
1504            .await?;
1505
1506        let reused_addresses = match stateless {
1507            MaybeNewAddress::NewAddress(deposit_address) => {
1508                return Ok((deposit_address, AllocateDepositOutcome::Fresh));
1509            }
1510            MaybeNewAddress::TooManyUnusedAddresses(addresses) => addresses,
1511        };
1512
1513        let result = self
1514            .db
1515            .autocommit(
1516                move |dbtx, _| {
1517                    let reused_addresses = reused_addresses.clone();
1518                    Box::pin(async move {
1519                        let cursor = dbtx
1520                            .get_value(&PegInPoolCursorKey)
1521                            .await
1522                            .unwrap_or(TweakIdx(0));
1523
1524                        let pick_pos = reused_addresses
1525                            .iter()
1526                            .position(|a| cursor <= a.tweak_idx)
1527                            .unwrap_or(0);
1528                        let reused_address = reused_addresses[pick_pos].clone();
1529
1530                        let existing_tweak_idx = reused_address.tweak_idx;
1531                        let existing = dbtx
1532                            .get_value(&PegInTweakIndexKey(reused_address.tweak_idx))
1533                            .await
1534                            .ok_or(DepositAddressError::PooledAddressDisappeared {
1535                                tweak_idx: reused_address.tweak_idx,
1536                            })?;
1537
1538                        if !existing.claimed.is_empty() {
1539                            return Err(DepositAddressError::PooledAddressUsed {
1540                                tweak_idx: reused_address.tweak_idx,
1541                            });
1542                        }
1543
1544                        dbtx.insert_entry(&PegInPoolCursorKey, &reused_address.tweak_idx.next())
1545                            .await;
1546
1547                        // Reset the monitoring schedule so the reused address
1548                        // gets checked as aggressively as a freshly-allocated
1549                        // one. Without this, an old entry would retain its
1550                        // `age/10` next-check delay from `pegin_monitor`,
1551                        // meaning a user who sends to a long-idle pool address
1552                        // could wait hours before the client polls for the
1553                        // deposit.
1554                        let now = fedimint_core::time::now();
1555                        dbtx.insert_entry(
1556                            &PegInTweakIndexKey(reused_address.tweak_idx),
1557                            &PegInTweakIndexData {
1558                                creation_time: now,
1559                                last_check_time: None,
1560                                next_check_time: Some(now),
1561                                operation_id: existing.operation_id,
1562                                claimed: existing.claimed,
1563                            },
1564                        )
1565                        .await;
1566
1567                        let sender = self.pegin_monitor_wakeup_sender.clone();
1568                        dbtx.on_commit(move || {
1569                            sender.send_replace(());
1570                        });
1571
1572                        Ok::<_, DepositAddressError>((
1573                            reused_address,
1574                            AllocateDepositOutcome::Reused {
1575                                original_tweak_idx: existing_tweak_idx,
1576                            },
1577                        ))
1578                    })
1579                },
1580                Some(100),
1581            )
1582            .await?;
1583
1584        Ok(result)
1585    }
1586
1587    /// Returns a stream of updates about an ongoing deposit operation created
1588    /// with [`WalletClientModule::allocate_deposit_address_expert_only`].
1589    /// Returns an error for old deposit operations created prior to the 0.4
1590    /// release and not driven to completion yet. This should be rare enough
1591    /// that an indeterminate state is ok here.
1592    pub async fn subscribe_deposit(
1593        &self,
1594        operation_id: OperationId,
1595    ) -> Result<UpdateStreamOrOutcome<DepositStateV2>, SubscribeDepositError> {
1596        let operation = self.client_ctx.get_operation(operation_id).await?;
1597
1598        let operation_meta = operation.meta::<WalletOperationMeta>();
1599
1600        let WalletOperationMetaVariant::Deposit {
1601            address, tweak_idx, ..
1602        } = operation_meta.variant
1603        else {
1604            return Err(SubscribeDepositError::NotADeposit);
1605        };
1606
1607        let network = self.cfg().network.0;
1608        let address = address
1609            .require_network(network)
1610            .map_err(|_| SubscribeDepositError::WrongNetwork { expected: network })?;
1611
1612        // The old deposit operations don't have tweak_idx set
1613        let Some(tweak_idx) = tweak_idx else {
1614            // In case we are dealing with an old deposit that still uses state machines we
1615            // don't have the logic here anymore to subscribe to updates. We can still read
1616            // the final state though if it reached any.
1617            let outcome_v1 = operation
1618                .outcome::<DepositStateV1>()
1619                .ok_or(SubscribeDepositError::OldPendingDeposit)?;
1620
1621            let outcome_v2 = match outcome_v1 {
1622                DepositStateV1::Claimed(tx_info) => DepositStateV2::Claimed {
1623                    btc_deposited: tx_info.btc_transaction.output[tx_info.out_idx as usize].value,
1624                    btc_out_point: bitcoin::OutPoint {
1625                        txid: tx_info.btc_transaction.compute_txid(),
1626                        vout: tx_info.out_idx,
1627                    },
1628                },
1629                DepositStateV1::Failed(error) => DepositStateV2::Failed(error),
1630                _ => return Err(SubscribeDepositError::NonFinalOutcome),
1631            };
1632
1633            return Ok(UpdateStreamOrOutcome::Outcome(outcome_v2));
1634        };
1635
1636        Ok(self.client_ctx.outcome_or_updates(
1637            &operation,
1638            operation_id,
1639            |state| match state {
1640                DepositStateV2::WaitingForTransaction
1641                | DepositStateV2::WaitingForConfirmation { .. }
1642                | DepositStateV2::Confirmed { .. } => false,
1643                DepositStateV2::Claimed { .. } | DepositStateV2::Failed(_) => true,
1644            },
1645            {
1646            let stream_rpc = self.rpc.clone();
1647            let stream_client_ctx = self.client_ctx.clone();
1648            let stream_script_pub_key = address.script_pubkey();
1649            move || {
1650
1651            stream! {
1652                yield DepositStateV2::WaitingForTransaction;
1653
1654                retry(
1655                    "subscribe script history",
1656                    background_backoff(),
1657                    || stream_rpc.watch_script_history(&stream_script_pub_key)
1658                ).await.expect("Will never give up");
1659                let (btc_out_point, btc_deposited) = retry(
1660                    "fetch history",
1661                    background_backoff(),
1662                    || async {
1663                        let history = stream_rpc.get_script_history(&stream_script_pub_key).await?;
1664                        history.first().and_then(|tx| {
1665                            let (out_idx, amount) = tx.output
1666                                .iter()
1667                                .enumerate()
1668                                .find_map(|(idx, output)| (output.script_pubkey == stream_script_pub_key).then_some((idx, output.value)))?;
1669                            let txid = tx.compute_txid();
1670
1671                            Some((
1672                                bitcoin::OutPoint {
1673                                    txid,
1674                                    vout: out_idx as u32,
1675                                },
1676                                amount
1677                            ))
1678                        }).ok_or(FetchDepositTransactionError::NotFound)
1679                    }
1680                ).await.expect("Will never give up");
1681
1682                yield DepositStateV2::WaitingForConfirmation {
1683                    btc_deposited,
1684                    btc_out_point
1685                };
1686
1687                let claim_data = stream_client_ctx.module_db().wait_key_exists(&ClaimedPegInKey {
1688                    peg_in_index: tweak_idx,
1689                    btc_out_point,
1690                }).await;
1691
1692                yield DepositStateV2::Confirmed {
1693                    btc_deposited,
1694                    btc_out_point
1695                };
1696
1697                match stream_client_ctx.await_primary_module_outputs(operation_id, claim_data.change).await {
1698                    Ok(()) => yield DepositStateV2::Claimed {
1699                        btc_deposited,
1700                        btc_out_point
1701                    },
1702                    Err(e) => yield DepositStateV2::Failed(e.fmt_compact().to_string())
1703                }
1704            }
1705        }}))
1706    }
1707
1708    /// The progress of every output the bitcoin backend reports paying the
1709    /// address of this deposit operation that this client has no claim record
1710    /// for, re-read from the backend and the federation on each call, so poll
1711    /// it sparingly. An entry with no confirmations is not proof that its
1712    /// transaction is in a mempool, and a reorged or replaced deposit stays
1713    /// listed for as long as the backend keeps reporting it.
1714    ///
1715    /// Only for display: claiming stays with the peg-in monitor.
1716    pub async fn deposit_progress(
1717        &self,
1718        operation_id: OperationId,
1719    ) -> Result<Vec<DepositProgress>, DepositProgressError> {
1720        let tweak_idx = self.find_tweak_idx_by_operation_id(operation_id).await?;
1721        pegin_monitor::deposit_progress(
1722            &self.data,
1723            tweak_idx,
1724            &self.rpc,
1725            &self.module_api,
1726            &self.db,
1727        )
1728        .await
1729    }
1730
1731    pub async fn list_peg_in_tweak_idxes(&self) -> BTreeMap<TweakIdx, PegInTweakIndexData> {
1732        self.client_ctx
1733            .module_db()
1734            .clone()
1735            .begin_transaction_nc()
1736            .await
1737            .find_by_prefix(&PegInTweakIndexPrefix)
1738            .await
1739            .map(|(key, data)| (key.0, data))
1740            .collect()
1741            .await
1742    }
1743
1744    pub async fn find_tweak_idx_by_address(
1745        &self,
1746        address: bitcoin::Address<NetworkUnchecked>,
1747    ) -> Result<TweakIdx, PegInError> {
1748        let data = self.data.clone();
1749        let Some((tweak_idx, _)) = self
1750            .db
1751            .begin_transaction_nc()
1752            .await
1753            .find_by_prefix(&PegInTweakIndexPrefix)
1754            .await
1755            .filter(|(k, _)| {
1756                let (_, derived_address, _tweak_key, _) = data.derive_peg_in_script(k.0);
1757                future::ready(derived_address.into_unchecked() == address)
1758            })
1759            .next()
1760            .await
1761        else {
1762            return Err(PegInError::AddressNotDerived);
1763        };
1764
1765        Ok(tweak_idx.0)
1766    }
1767    pub async fn find_tweak_idx_by_operation_id(
1768        &self,
1769        operation_id: OperationId,
1770    ) -> Result<TweakIdx, PegInError> {
1771        Ok(self
1772            .client_ctx
1773            .module_db()
1774            .clone()
1775            .begin_transaction_nc()
1776            .await
1777            .find_by_prefix(&PegInTweakIndexPrefix)
1778            .await
1779            .filter(|(_k, v)| future::ready(v.operation_id == operation_id))
1780            .next()
1781            .await
1782            .ok_or(PegInError::NoAddressForOperation { operation_id })?
1783            .0
1784            .0)
1785    }
1786
1787    pub async fn get_pegin_tweak_idx(
1788        &self,
1789        tweak_idx: TweakIdx,
1790    ) -> Result<PegInTweakIndexData, PegInError> {
1791        self.client_ctx
1792            .module_db()
1793            .clone()
1794            .begin_transaction_nc()
1795            .await
1796            .get_value(&PegInTweakIndexKey(tweak_idx))
1797            .await
1798            .ok_or(PegInError::TweakIdxNotFound { tweak_idx })
1799    }
1800
1801    pub async fn get_claimed_pegins(
1802        &self,
1803        dbtx: &mut DatabaseTransaction<'_>,
1804        tweak_idx: TweakIdx,
1805    ) -> Vec<(
1806        bitcoin::OutPoint,
1807        TransactionId,
1808        Vec<fedimint_core::OutPoint>,
1809    )> {
1810        let outpoints = dbtx
1811            .get_value(&PegInTweakIndexKey(tweak_idx))
1812            .await
1813            .map(|v| v.claimed)
1814            .unwrap_or_default();
1815
1816        let mut res = vec![];
1817
1818        for outpoint in outpoints {
1819            let claimed_peg_in_data = dbtx
1820                .get_value(&ClaimedPegInKey {
1821                    peg_in_index: tweak_idx,
1822                    btc_out_point: outpoint,
1823                })
1824                .await
1825                .expect("Must have a corresponding claim record");
1826            res.push((
1827                outpoint,
1828                claimed_peg_in_data.claim_txid,
1829                claimed_peg_in_data.change,
1830            ));
1831        }
1832
1833        res
1834    }
1835
1836    /// Like [`Self::recheck_pegin_address`] but by `operation_id`
1837    pub async fn recheck_pegin_address_by_op_id(
1838        &self,
1839        operation_id: OperationId,
1840    ) -> Result<(), PegInError> {
1841        let tweak_idx = self.find_tweak_idx_by_operation_id(operation_id).await?;
1842
1843        self.recheck_pegin_address(tweak_idx).await
1844    }
1845
1846    /// Schedule given address for immediate re-check for deposits
1847    pub async fn recheck_pegin_address_by_address(
1848        &self,
1849        address: bitcoin::Address<NetworkUnchecked>,
1850    ) -> Result<(), PegInError> {
1851        self.recheck_pegin_address(self.find_tweak_idx_by_address(address).await?)
1852            .await
1853    }
1854
1855    /// Schedule given address for immediate re-check for deposits
1856    pub async fn recheck_pegin_address(&self, tweak_idx: TweakIdx) -> Result<(), PegInError> {
1857        self.db
1858            .autocommit(
1859                |dbtx, _| {
1860                    Box::pin(async {
1861                        let db_key = PegInTweakIndexKey(tweak_idx);
1862                        let db_val = dbtx
1863                            .get_value(&db_key)
1864                            .await
1865                            .ok_or(PegInError::TweakIdxNotFound { tweak_idx })?;
1866
1867                        dbtx.insert_entry(
1868                            &db_key,
1869                            &PegInTweakIndexData {
1870                                next_check_time: Some(fedimint_core::time::now()),
1871                                ..db_val
1872                            },
1873                        )
1874                        .await;
1875
1876                        let sender = self.pegin_monitor_wakeup_sender.clone();
1877                        dbtx.on_commit(move || {
1878                            sender.send_replace(());
1879                        });
1880
1881                        Ok::<_, PegInError>(())
1882                    })
1883                },
1884                Some(100),
1885            )
1886            .await?;
1887
1888        Ok(())
1889    }
1890
1891    /// Await for num deposit by [`OperationId`]
1892    pub async fn await_num_deposits_by_operation_id(
1893        &self,
1894        operation_id: OperationId,
1895        num_deposits: usize,
1896    ) -> Result<(), PegInError> {
1897        let tweak_idx = self.find_tweak_idx_by_operation_id(operation_id).await?;
1898        self.await_num_deposits(tweak_idx, num_deposits).await
1899    }
1900
1901    pub async fn await_num_deposits_by_address(
1902        &self,
1903        address: bitcoin::Address<NetworkUnchecked>,
1904        num_deposits: usize,
1905    ) -> Result<(), PegInError> {
1906        self.await_num_deposits(self.find_tweak_idx_by_address(address).await?, num_deposits)
1907            .await
1908    }
1909
1910    #[instrument(target = LOG_CLIENT_MODULE_WALLET, skip_all, fields(tweak_idx=?tweak_idx, num_deposists=num_deposits))]
1911    pub async fn await_num_deposits(
1912        &self,
1913        tweak_idx: TweakIdx,
1914        num_deposits: usize,
1915    ) -> Result<(), PegInError> {
1916        let operation_id = self.get_pegin_tweak_idx(tweak_idx).await?.operation_id;
1917
1918        let mut receiver = self.pegin_claimed_receiver.clone();
1919        let mut backoff = backoff_util::aggressive_backoff();
1920
1921        loop {
1922            let pegins = self
1923                .get_claimed_pegins(
1924                    &mut self.client_ctx.module_db().begin_transaction_nc().await,
1925                    tweak_idx,
1926                )
1927                .await;
1928
1929            if pegins.len() < num_deposits {
1930                debug!(target: LOG_CLIENT_MODULE_WALLET, has=pegins.len(), "Not enough deposits");
1931                self.recheck_pegin_address(tweak_idx).await?;
1932                runtime::sleep(backoff.next().unwrap_or_default()).await;
1933                receiver
1934                    .changed()
1935                    .await
1936                    .map_err(|_| PegInError::MonitorStopped)?;
1937                continue;
1938            }
1939
1940            debug!(target: LOG_CLIENT_MODULE_WALLET, has=pegins.len(), "Enough deposits detected");
1941
1942            for (_outpoint, transaction_id, change) in pegins {
1943                if transaction_id == TransactionId::from_byte_array([0; 32]) && change.is_empty() {
1944                    debug!(target: LOG_CLIENT_MODULE_WALLET, "Deposited amount was too low, skipping");
1945                    continue;
1946                }
1947
1948                debug!(target: LOG_CLIENT_MODULE_WALLET, out_points=?change, "Ensuring deposists claimed");
1949                let tx_subscriber = self.client_ctx.transaction_updates(operation_id).await;
1950
1951                if let Err(reason) = tx_subscriber.await_tx_accepted(transaction_id).await {
1952                    return Err(PegInError::TransactionRejected { reason });
1953                }
1954
1955                debug!(target: LOG_CLIENT_MODULE_WALLET, out_points=?change, "Ensuring outputs claimed");
1956                self.client_ctx
1957                    .await_primary_module_outputs(operation_id, change)
1958                    .await
1959                    .expect("Cannot fail if tx was accepted and federation is honest");
1960            }
1961
1962            return Ok(());
1963        }
1964    }
1965
1966    /// Attempt to withdraw a given `amount` of Bitcoin to a destination
1967    /// `address`. The caller has to supply the fee rate to be used which can be
1968    /// fetched using [`Self::get_withdraw_fees`] and should be
1969    /// acknowledged by the user since it can be unexpectedly high.
1970    pub async fn withdraw<M: Serialize + MaybeSend + MaybeSync>(
1971        &self,
1972        address: &bitcoin::Address,
1973        amount: bitcoin::Amount,
1974        fee: PegOutFees,
1975        extra_meta: M,
1976    ) -> Result<OperationId, TransactionSubmitError> {
1977        {
1978            let operation_id = OperationId(thread_rng().r#gen());
1979
1980            let withdraw_output =
1981                self.create_withdraw_output(operation_id, address.clone(), amount, fee);
1982            let tx_builder = TransactionBuilder::new(Account::Primary)
1983                .with_outputs(self.client_ctx.make_client_outputs(withdraw_output));
1984
1985            let extra_meta =
1986                serde_json::to_value(extra_meta).expect("Failed to serialize extra meta");
1987            self.client_ctx
1988                .finalize_and_submit_transaction_with_events(
1989                    operation_id,
1990                    WalletCommonInit::KIND.as_str(),
1991                    {
1992                        let address = address.clone();
1993                        move |change_range: OutPointRange| WalletOperationMeta {
1994                            variant: WalletOperationMetaVariant::Withdraw {
1995                                address: address.clone().into_unchecked(),
1996                                amount,
1997                                fee,
1998                                change: change_range.into_iter().collect(),
1999                            },
2000                            extra_meta: extra_meta.clone(),
2001                        }
2002                    },
2003                    tx_builder,
2004                    vec![self.client_ctx.make_event(SendPaymentEvent {
2005                        operation_id,
2006                        amount: amount + fee.amount(),
2007                        fee: fee.amount(),
2008                    })],
2009                )
2010                .await?;
2011
2012            Ok(operation_id)
2013        }
2014    }
2015
2016    /// Attempt to increase the fee of a onchain withdraw transaction using
2017    /// replace by fee (RBF).
2018    /// This can prevent transactions from getting stuck
2019    /// in the mempool
2020    #[deprecated(
2021        since = "0.4.0",
2022        note = "RBF withdrawals are rejected by the federation"
2023    )]
2024    pub async fn rbf_withdraw<M: Serialize + MaybeSync + MaybeSend>(
2025        &self,
2026        rbf: Rbf,
2027        extra_meta: M,
2028    ) -> Result<OperationId, TransactionSubmitError> {
2029        let operation_id = OperationId(thread_rng().r#gen());
2030
2031        let withdraw_output = self.create_rbf_withdraw_output(operation_id, &rbf);
2032        let tx_builder = TransactionBuilder::new(Account::Primary)
2033            .with_outputs(self.client_ctx.make_client_outputs(withdraw_output));
2034
2035        let extra_meta = serde_json::to_value(extra_meta).expect("Failed to serialize extra meta");
2036        self.client_ctx
2037            .finalize_and_submit_transaction(
2038                operation_id,
2039                WalletCommonInit::KIND.as_str(),
2040                move |change_range: OutPointRange| WalletOperationMeta {
2041                    variant: WalletOperationMetaVariant::RbfWithdraw {
2042                        rbf: rbf.clone(),
2043                        change: change_range.into_iter().collect(),
2044                    },
2045                    extra_meta: extra_meta.clone(),
2046                },
2047                tx_builder,
2048            )
2049            .await?;
2050
2051        Ok(operation_id)
2052    }
2053
2054    pub async fn subscribe_withdraw_updates(
2055        &self,
2056        operation_id: OperationId,
2057    ) -> Result<UpdateStreamOrOutcome<WithdrawState>, SubscribeWithdrawError> {
2058        let operation = self.client_ctx.get_operation(operation_id).await?;
2059
2060        let operation_meta = operation.meta::<WalletOperationMeta>();
2061
2062        let (WalletOperationMetaVariant::Withdraw { change, .. }
2063        | WalletOperationMetaVariant::RbfWithdraw { change, .. }) = operation_meta.variant
2064        else {
2065            return Err(SubscribeWithdrawError::NotAWithdrawal);
2066        };
2067
2068        let mut operation_stream = self.notifier.subscribe(operation_id).await;
2069        let client_ctx = self.client_ctx.clone();
2070
2071        Ok(self.client_ctx.outcome_or_updates(
2072            &operation,
2073            operation_id,
2074            |state| match state {
2075                WithdrawState::Created => false,
2076                WithdrawState::Succeeded(_) | WithdrawState::Failed(_) => true,
2077            },
2078            move || {
2079                stream! {
2080                    match next_withdraw_state(&mut operation_stream).await {
2081                        Some(WithdrawStates::Created(_)) => {
2082                            yield WithdrawState::Created;
2083                        },
2084                        Some(s) => {
2085                            panic!("Unexpected state {s:?}")
2086                        },
2087                        None => return,
2088                    }
2089
2090                    // TODO: get rid of awaiting change here, there has to be a better way to make tests deterministic
2091
2092                        // Swallowing potential errors since the transaction failing  is handled by
2093                        // output outcome fetching already
2094                        let _ = client_ctx
2095                            .await_primary_module_outputs(operation_id, change)
2096                            .await;
2097
2098
2099                    match next_withdraw_state(&mut operation_stream).await {
2100                        Some(WithdrawStates::Aborted(inner)) => {
2101                            yield WithdrawState::Failed(inner.error);
2102                        },
2103                        Some(WithdrawStates::Success(inner)) => {
2104                            yield WithdrawState::Succeeded(inner.txid);
2105                        },
2106                        Some(s) => {
2107                            panic!("Unexpected state {s:?}")
2108                        },
2109                        None => {},
2110                    }
2111                }
2112            },
2113        ))
2114    }
2115
2116    fn admin_auth(&self) -> Result<ApiAuth, ConsensusVersionVotingError> {
2117        self.admin_auth
2118            .clone()
2119            .ok_or(ConsensusVersionVotingError::AdminAuthMissing)
2120    }
2121
2122    pub async fn activate_consensus_version_voting(
2123        &self,
2124    ) -> Result<(), ConsensusVersionVotingError> {
2125        self.module_api
2126            .activate_consensus_version_voting(self.admin_auth()?)
2127            .await?;
2128
2129        Ok(())
2130    }
2131}
2132
2133/// Why a deposit address's funding transaction was not found, so that it is
2134/// looked up again.
2135#[derive(Debug, thiserror::Error)]
2136enum FetchDepositTransactionError {
2137    /// The Bitcoin backend could not report the address's history.
2138    #[error(transparent)]
2139    BitcoinRpc(#[from] BitcoinRpcError),
2140
2141    /// The address's history holds no transaction paying to it yet.
2142    #[error("No deposit transaction found")]
2143    NotFound,
2144}
2145
2146/// Polls the federation checking if the activated module consensus version
2147/// supports safe deposits, saving the result in the db once it does.
2148async fn poll_supports_safe_deposit_version(db: Database, module_api: DynModuleApi) {
2149    loop {
2150        if supports_safe_deposit_verified(&db).await {
2151            break;
2152        }
2153
2154        module_api.wait_for_initialized_connections().await;
2155
2156        if verify_supports_safe_deposit(&db, &module_api).await == Some(true) {
2157            break;
2158        }
2159
2160        if is_running_in_test_env!() {
2161            // Even in tests we don't want to spam the federation with requests about it
2162            sleep(Duration::from_secs(10)).await;
2163        } else {
2164            sleep(Duration::from_hours(1)).await;
2165        }
2166    }
2167}
2168
2169/// Whether the federation's wallet module consensus version was already
2170/// verified to support safe deposits.
2171async fn supports_safe_deposit_verified(db: &Database) -> bool {
2172    db.begin_transaction_nc()
2173        .await
2174        .get_value(&SupportsSafeDepositKey)
2175        .await
2176        .is_some()
2177}
2178
2179/// Fetches the federation's wallet module consensus version and records the
2180/// marker if it supports safe deposits.
2181///
2182/// Returns `None` if the version could not be fetched, e.g. while offline.
2183async fn verify_supports_safe_deposit(db: &Database, module_api: &DynModuleApi) -> Option<bool> {
2184    let module_consensus_version = match module_api.module_consensus_version().await {
2185        Ok(module_consensus_version) => module_consensus_version,
2186        Err(err) => {
2187            debug!(
2188                target: LOG_CLIENT_MODULE_WALLET,
2189                err = %err.fmt_compact(),
2190                "Could not fetch the wallet module consensus version"
2191            );
2192            return None;
2193        }
2194    };
2195
2196    let supported_version = SAFE_DEPOSIT_MODULE_CONSENSUS_VERSION <= module_consensus_version;
2197
2198    if supported_version {
2199        store_supports_safe_deposit(db.begin_transaction().await).await;
2200    }
2201
2202    Some(supported_version)
2203}
2204
2205/// Records in `dbtx` that the federation's wallet module consensus version
2206/// was verified to support safe deposits, and commits it.
2207///
2208/// The marker is written by both the background version poller and
2209/// [`WalletClientModule::supports_safe_deposit`], which race right after
2210/// joining a federation. The loser's commit fails with a write conflict, but
2211/// the winner stored the very same marker and nothing ever removes it, so the
2212/// conflict is treated as success. That is only sound for a fresh `dbtx` whose
2213/// sole write is the marker: any other write in it would be lost as well.
2214///
2215/// Any other commit error is logged rather than escalated: the marker only
2216/// lets future checks skip re-verifying the version, callers already have
2217/// their answer, and the next verification simply writes it again — an
2218/// optional write is not worth crashing over.
2219async fn store_supports_safe_deposit(mut dbtx: DatabaseTransaction<'_, Committable>) {
2220    if dbtx.get_value(&SupportsSafeDepositKey).await.is_some() {
2221        // The other writer won before this transaction started.
2222        return;
2223    }
2224
2225    dbtx.insert_entry(&SupportsSafeDepositKey, &()).await;
2226
2227    match dbtx.commit_tx_result().await {
2228        Ok(()) | Err(DatabaseError::WriteConflict) => {}
2229        Err(err) => {
2230            warn!(
2231                target: LOG_CLIENT_MODULE_WALLET,
2232                err = %err.fmt_compact(),
2233                "Failed to store the safe-deposit marker"
2234            );
2235        }
2236    }
2237}
2238
2239/// Returns the child index to derive the next peg-in tweak key from.
2240async fn get_next_peg_in_tweak_child_id(dbtx: &mut DatabaseTransaction<'_>) -> TweakIdx {
2241    let index = dbtx
2242        .get_value(&NextPegInTweakIndexKey)
2243        .await
2244        .unwrap_or_default();
2245    dbtx.insert_entry(&NextPegInTweakIndexKey, &(index.next()))
2246        .await;
2247    index
2248}
2249
2250#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
2251pub enum WalletClientStates {
2252    Deposit(DepositStateMachine),
2253    Withdraw(WithdrawStateMachine),
2254}
2255
2256impl IntoDynInstance for WalletClientStates {
2257    type DynType = DynState;
2258
2259    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
2260        DynState::from_typed(instance_id, self)
2261    }
2262}
2263
2264impl State for WalletClientStates {
2265    type ModuleContext = WalletClientContext;
2266
2267    fn transitions(
2268        &self,
2269        context: &Self::ModuleContext,
2270        global_context: &DynGlobalClientContext,
2271    ) -> Vec<StateTransition<Self>> {
2272        match self {
2273            WalletClientStates::Deposit(sm) => {
2274                sm_enum_variant_translation!(
2275                    sm.transitions(context, global_context),
2276                    WalletClientStates::Deposit
2277                )
2278            }
2279            WalletClientStates::Withdraw(sm) => {
2280                sm_enum_variant_translation!(
2281                    sm.transitions(context, global_context),
2282                    WalletClientStates::Withdraw
2283                )
2284            }
2285        }
2286    }
2287
2288    fn operation_id(&self) -> OperationId {
2289        match self {
2290            WalletClientStates::Deposit(sm) => sm.operation_id(),
2291            WalletClientStates::Withdraw(sm) => sm.operation_id(),
2292        }
2293    }
2294}
2295
2296#[cfg(all(test, not(target_family = "wasm")))]
2297mod tests;