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;
15mod deposit;
18pub mod error;
20pub mod events;
21use events::SendPaymentEvent;
22mod 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, MaxWithdrawableAmountError, PegInError,
97 PegOutError, SubscribeDepositError, SubscribeWithdrawError, WithdrawFeesError,
98};
99use crate::withdraw::{CreatedWithdrawState, WithdrawStateMachine, WithdrawStates};
100
101const WALLET_TWEAK_CHILD_ID: ChildId = ChildId(0);
102
103#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
104pub struct BitcoinTransactionData {
105 pub btc_transaction: bitcoin::Transaction,
108 pub out_idx: u32,
110}
111
112#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
113pub enum DepositStateV1 {
114 WaitingForTransaction,
115 WaitingForConfirmation(BitcoinTransactionData),
116 Confirmed(BitcoinTransactionData),
117 Claimed(BitcoinTransactionData),
118 Failed(String),
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
122pub enum DepositStateV2 {
123 WaitingForTransaction,
124 WaitingForConfirmation {
125 #[serde(with = "bitcoin::amount::serde::as_sat")]
126 btc_deposited: bitcoin::Amount,
127 btc_out_point: bitcoin::OutPoint,
128 },
129 Confirmed {
130 #[serde(with = "bitcoin::amount::serde::as_sat")]
131 btc_deposited: bitcoin::Amount,
132 btc_out_point: bitcoin::OutPoint,
133 },
134 Claimed {
135 #[serde(with = "bitcoin::amount::serde::as_sat")]
136 btc_deposited: bitcoin::Amount,
137 btc_out_point: bitcoin::OutPoint,
138 },
139 Failed(String),
140}
141
142#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct DepositAddressInfo {
145 pub operation_id: OperationId,
146 pub address: Address,
147 pub tweak_idx: TweakIdx,
148}
149
150#[allow(clippy::enum_variant_names)]
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub enum MaybeNewAddress {
158 NewAddress(DepositAddressInfo),
160 TooManyUnusedAddresses(Vec<DepositAddressInfo>),
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub enum AllocateDepositOutcome {
173 Fresh,
175 Reused { original_tweak_idx: TweakIdx },
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
182pub enum WithdrawState {
183 Created,
184 Succeeded(bitcoin::Txid),
185 Failed(String),
186 }
190
191async fn next_withdraw_state<S>(stream: &mut S) -> Option<WithdrawStates>
192where
193 S: Stream<Item = WalletClientStates> + Unpin,
194{
195 loop {
196 if let WalletClientStates::Withdraw(ds) = stream.next().await? {
197 return Some(ds.state);
198 }
199 tokio::task::yield_now().await;
200 }
201}
202
203#[derive(Debug, Clone, Default)]
204pub struct WalletClientInit(pub Option<DynBitcoindRpc>);
206
207const SLICE_SIZE: u64 = 1000;
208
209impl WalletClientInit {
210 pub fn new(rpc: DynBitcoindRpc) -> Self {
211 Self(Some(rpc))
212 }
213
214 async fn recover_from_slices(
215 &self,
216 args: &ClientModuleRecoverArgs<Self>,
217 total_items: u64,
218 ) -> Option<fedimint_core::Amount> {
219 let data = WalletClientModuleData {
220 cfg: args.cfg().clone(),
221 module_root_secret: args.module_root_secret().clone(),
222 };
223
224 let mut state = RecoveryStateV2::new();
225
226 state.refill_pending_pool_up_to(&data, TweakIdx(FEDERATION_RECOVER_MAX_GAP));
227
228 for start in (0..total_items).step_by(SLICE_SIZE as usize) {
229 let end = std::cmp::min(start + SLICE_SIZE, total_items);
230
231 let items = args.module_api().fetch_recovery_slice(start, end).await;
232
233 for item in &items {
234 match item {
235 RecoveryItem::Input { outpoint, script } => {
236 state.handle_item(*outpoint, script, &data);
237 }
238 }
239 }
240
241 args.update_recovery_progress(RecoveryProgress {
242 complete: end.try_into().unwrap_or(u32::MAX),
243 total: total_items.try_into().unwrap_or(u32::MAX),
244 });
245 }
246
247 let entries = (0..state.new_start_idx().0)
248 .map(|tweak_idx| {
249 let operation_id = data.derive_peg_in_script(TweakIdx(tweak_idx)).3;
250
251 let claimed = state
252 .claimed_outpoints
253 .get(&TweakIdx(tweak_idx))
254 .cloned()
255 .unwrap_or_default();
256
257 (
258 TweakIdx(tweak_idx),
259 PegInTweakIndexData {
260 operation_id,
261 creation_time: fedimint_core::time::now(),
262 last_check_time: None,
263 next_check_time: Some(fedimint_core::time::now()),
264 claimed,
265 },
266 )
267 })
268 .collect();
269
270 store_recovered_peg_in_indexes(args.db(), entries, state.new_start_idx()).await;
271
272 None
276 }
277}
278
279async fn recovery_already_finalized(db: &Database) -> bool {
290 let mut dbtx = db.begin_transaction_nc().await;
291 dbtx.get_value(&RecoveryFinalizedKey).await == Some(true)
292 || dbtx.get_value(&NextPegInTweakIndexKey).await.is_some()
293}
294
295async fn store_recovered_peg_in_indexes(
304 db: &Database,
305 entries: Vec<(TweakIdx, PegInTweakIndexData)>,
306 new_start_idx: TweakIdx,
307) -> bool {
308 let mut dbtx = db.begin_transaction().await;
309
310 if dbtx.get_value(&RecoveryFinalizedKey).await == Some(true)
311 || dbtx.get_value(&NextPegInTweakIndexKey).await.is_some()
312 {
313 return false;
314 }
315
316 for (tweak_idx, entry) in entries {
317 dbtx.insert_new_entry(&PegInTweakIndexKey(tweak_idx), &entry)
318 .await;
319 }
320
321 dbtx.insert_new_entry(&NextPegInTweakIndexKey, &new_start_idx)
322 .await;
323 dbtx.insert_entry(&RecoveryFinalizedKey, &true).await;
324
325 dbtx.commit_tx().await;
326
327 true
328}
329
330impl ModuleInit for WalletClientInit {
331 type Common = WalletCommonInit;
332
333 async fn dump_database(
334 &self,
335 dbtx: &mut DatabaseTransaction<'_>,
336 prefix_names: Vec<String>,
337 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
338 let mut wallet_client_items: BTreeMap<String, Box<dyn erased_serde::Serialize + Send>> =
339 BTreeMap::new();
340 let filtered_prefixes = DbKeyPrefix::iter().filter(|f| {
341 prefix_names.is_empty() || prefix_names.contains(&f.to_string().to_lowercase())
342 });
343
344 for table in filtered_prefixes {
345 match table {
346 DbKeyPrefix::NextPegInTweakIndex => {
347 if let Some(index) = dbtx.get_value(&NextPegInTweakIndexKey).await {
348 wallet_client_items
349 .insert("NextPegInTweakIndex".to_string(), Box::new(index));
350 }
351 }
352 DbKeyPrefix::PegInTweakIndex => {
353 push_db_pair_items!(
354 dbtx,
355 PegInTweakIndexPrefix,
356 PegInTweakIndexKey,
357 PegInTweakIndexData,
358 wallet_client_items,
359 "Peg-In Tweak Index"
360 );
361 }
362 DbKeyPrefix::ClaimedPegIn => {
363 push_db_pair_items!(
364 dbtx,
365 ClaimedPegInPrefix,
366 ClaimedPegInKey,
367 ClaimedPegInData,
368 wallet_client_items,
369 "Claimed Peg-In"
370 );
371 }
372 DbKeyPrefix::RecoveryFinalized => {
373 if let Some(val) = dbtx.get_value(&RecoveryFinalizedKey).await {
374 wallet_client_items.insert("RecoveryFinalized".to_string(), Box::new(val));
375 }
376 }
377 DbKeyPrefix::SupportsSafeDeposit => {
378 push_db_pair_items!(
379 dbtx,
380 SupportsSafeDepositPrefix,
381 SupportsSafeDepositKey,
382 (),
383 wallet_client_items,
384 "Supports Safe Deposit"
385 );
386 }
387 DbKeyPrefix::PegInPoolCursor => {
388 if let Some(cursor) = dbtx.get_value(&PegInPoolCursorKey).await {
389 wallet_client_items.insert("PegInPoolCursor".to_string(), Box::new(cursor));
390 }
391 }
392 DbKeyPrefix::RecoveryState
393 | DbKeyPrefix::ExternalReservedStart
394 | DbKeyPrefix::CoreInternalReservedStart
395 | DbKeyPrefix::CoreInternalReservedEnd => {}
396 }
397 }
398
399 Box::new(wallet_client_items.into_iter())
400 }
401}
402
403#[apply(async_trait_maybe_send!)]
404impl ClientModuleInit for WalletClientInit {
405 type Module = WalletClientModule;
406
407 fn supported_api_versions(&self) -> MultiApiVersion {
408 MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
409 .expect("no version conflicts")
410 }
411
412 async fn init(
413 &self,
414 args: &ClientModuleInitArgs<Self>,
415 ) -> Result<Self::Module, ClientModuleError> {
416 let data = WalletClientModuleData {
417 cfg: args.cfg().clone(),
418 module_root_secret: args.module_root_secret().clone(),
419 };
420
421 let db = args.db().clone();
422
423 let rpc_config = WalletClientModule::get_rpc_config(args.cfg());
424
425 let btc_rpc = if let Some(user_rpc) = args.user_bitcoind_rpc() {
432 user_rpc.clone()
433 } else if let Some(factory) = args.user_bitcoind_rpc_no_chain_id() {
434 if let Some(rpc) = factory(rpc_config.url.clone()).await {
435 rpc
436 } else {
437 self.0.clone().unwrap_or(
438 create_esplora_rpc(&rpc_config.url).map_err(ClientModuleError::other)?,
439 )
440 }
441 } else {
442 self.0
443 .clone()
444 .unwrap_or(create_esplora_rpc(&rpc_config.url).map_err(ClientModuleError::other)?)
445 };
446 let btc_rpc = BitcoindTracked::new(btc_rpc, "wallet-client").into_dyn();
447
448 let module_api = args.module_api().clone();
449
450 let (pegin_claimed_sender, pegin_claimed_receiver) = watch::channel(());
451 let (pegin_monitor_wakeup_sender, pegin_monitor_wakeup_receiver) = watch::channel(());
452
453 Ok(WalletClientModule {
454 db,
455 data,
456 module_api,
457 notifier: args.notifier().clone(),
458 rpc: btc_rpc,
459 client_ctx: args.context(),
460 pegin_monitor_wakeup_sender,
461 pegin_monitor_wakeup_receiver,
462 pegin_claimed_receiver,
463 pegin_claimed_sender,
464 task_group: args.task_group().clone(),
465 client_span: args.client_span().clone(),
466 admin_auth: args.admin_auth().cloned(),
467 })
468 }
469
470 fn recovery_mode(&self) -> RecoveryMode {
471 RecoveryMode::Unusable
472 }
473
474 async fn recover(
479 &self,
480 args: &ClientModuleRecoverArgs<Self>,
481 snapshot: Option<&<Self::Module as ClientModule>::Backup>,
482 ) -> Result<Option<fedimint_core::Amount>, ClientModuleError> {
483 if recovery_already_finalized(args.db()).await {
488 debug!(
489 target: LOG_CLIENT_MODULE_WALLET,
490 "Wallet recovery already finalized by an earlier run, nothing to redo"
491 );
492 return Ok(None);
493 }
494
495 if args
498 .db()
499 .begin_transaction_nc()
500 .await
501 .get_value(&RecoveryStateKey)
502 .await
503 .is_some()
504 {
505 return args
506 .recover_from_history::<WalletRecovery>(self, snapshot)
507 .await;
508 }
509
510 match args.module_api().fetch_recovery_count().await {
514 Ok(total_items) => Ok(self.recover_from_slices(args, total_items).await),
515 Err(_) => {
516 args.recover_from_history::<WalletRecovery>(self, snapshot)
517 .await
518 }
519 }
520 }
521
522 fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
523 Some(
524 DbKeyPrefix::iter()
525 .map(|p| p as u8)
526 .chain(
527 DbKeyPrefix::ExternalReservedStart as u8
528 ..=DbKeyPrefix::CoreInternalReservedEnd as u8,
529 )
530 .collect(),
531 )
532 }
533}
534
535#[derive(Debug, Clone, Serialize, Deserialize)]
536pub struct WalletOperationMeta {
537 pub variant: WalletOperationMetaVariant,
538 pub extra_meta: serde_json::Value,
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize)]
542#[serde(rename_all = "snake_case")]
543pub enum WalletOperationMetaVariant {
544 Deposit {
545 address: Address<NetworkUnchecked>,
546 #[serde(default)]
551 tweak_idx: Option<TweakIdx>,
552 #[serde(default, skip_serializing_if = "Option::is_none")]
553 expires_at: Option<SystemTime>,
554 },
555 Withdraw {
556 address: Address<NetworkUnchecked>,
557 #[serde(with = "bitcoin::amount::serde::as_sat")]
558 amount: bitcoin::Amount,
559 fee: PegOutFees,
560 change: Vec<OutPoint>,
561 },
562
563 RbfWithdraw {
564 rbf: Rbf,
565 change: Vec<OutPoint>,
566 },
567}
568
569#[derive(Debug, Clone)]
571pub struct WalletClientModuleData {
572 cfg: WalletClientConfig,
573 module_root_secret: DerivableSecret,
574}
575
576impl WalletClientModuleData {
577 fn derive_deposit_address(
578 &self,
579 idx: TweakIdx,
580 ) -> (Keypair, secp256k1::PublicKey, Address, OperationId) {
581 let idx = ChildId(idx.0);
582
583 let secret_tweak_key = self
584 .module_root_secret
585 .child_key(WALLET_TWEAK_CHILD_ID)
586 .child_key(idx)
587 .to_secp_key(fedimint_core::secp256k1::SECP256K1);
588
589 let public_tweak_key = secret_tweak_key.public_key();
590
591 let address = self
592 .cfg
593 .peg_in_descriptor
594 .tweak(&public_tweak_key, bitcoin::secp256k1::SECP256K1)
595 .address(self.cfg.network.0)
596 .unwrap();
597
598 let operation_id = OperationId(public_tweak_key.x_only_public_key().0.serialize());
600
601 (secret_tweak_key, public_tweak_key, address, operation_id)
602 }
603
604 fn derive_peg_in_script(
605 &self,
606 idx: TweakIdx,
607 ) -> (ScriptBuf, bitcoin::Address, Keypair, OperationId) {
608 let (secret_tweak_key, _, address, operation_id) = self.derive_deposit_address(idx);
609
610 (
611 self.cfg
612 .peg_in_descriptor
613 .tweak(&secret_tweak_key.public_key(), SECP256K1)
614 .script_pubkey(),
615 address,
616 secret_tweak_key,
617 operation_id,
618 )
619 }
620}
621
622#[derive(Debug)]
623pub struct WalletClientModule {
624 data: WalletClientModuleData,
625 db: Database,
626 module_api: DynModuleApi,
627 notifier: ModuleNotifier<WalletClientStates>,
628 rpc: DynBitcoindRpc,
629 client_ctx: ClientContext<Self>,
630 pegin_monitor_wakeup_sender: watch::Sender<()>,
632 pegin_monitor_wakeup_receiver: watch::Receiver<()>,
633 pegin_claimed_sender: watch::Sender<()>,
635 pegin_claimed_receiver: watch::Receiver<()>,
636 task_group: TaskGroup,
637 client_span: tracing::Span,
638 admin_auth: Option<ApiAuth>,
639}
640
641#[apply(async_trait_maybe_send!)]
642impl ClientModule for WalletClientModule {
643 type Init = WalletClientInit;
644 type Common = WalletModuleTypes;
645 type Backup = WalletModuleBackup;
646 type ModuleStateMachineContext = WalletClientContext;
647 type States = WalletClientStates;
648
649 fn context(&self) -> Self::ModuleStateMachineContext {
650 WalletClientContext {
651 rpc: self.rpc.clone(),
652 wallet_descriptor: self.cfg().peg_in_descriptor.clone(),
653 wallet_decoder: self.decoder(),
654 secp: Secp256k1::default(),
655 client_ctx: self.client_ctx.clone(),
656 }
657 }
658
659 async fn start(&self) {
660 self.task_group
661 .spawn_cancellable_with_span(self.client_span.clone(), "peg-in monitor", {
662 let client_ctx = self.client_ctx.clone();
663 let db = self.db.clone();
664 let btc_rpc = self.rpc.clone();
665 let module_api = self.module_api.clone();
666 let data = self.data.clone();
667 let pegin_claimed_sender = self.pegin_claimed_sender.clone();
668 let pegin_monitor_wakeup_receiver = self.pegin_monitor_wakeup_receiver.clone();
669 pegin_monitor::run_peg_in_monitor(
670 client_ctx,
671 db,
672 btc_rpc,
673 module_api,
674 data,
675 pegin_claimed_sender,
676 pegin_monitor_wakeup_receiver,
677 )
678 });
679
680 self.task_group.spawn_cancellable_with_span(
681 self.client_span.clone(),
682 "supports-safe-deposit-version",
683 {
684 let db = self.db.clone();
685 let module_api = self.module_api.clone();
686
687 poll_supports_safe_deposit_version(db, module_api)
688 },
689 );
690 }
691
692 fn supports_backup(&self) -> bool {
693 true
694 }
695
696 async fn backup(&self) -> Result<backup::WalletModuleBackup, ClientModuleError> {
697 let session_count = self
699 .client_ctx
700 .global_api()
701 .session_count()
702 .await
703 .map_err(ClientModuleError::other)?;
704
705 let mut dbtx = self.db.begin_transaction_nc().await;
706 let next_pegin_tweak_idx = dbtx
707 .get_value(&NextPegInTweakIndexKey)
708 .await
709 .unwrap_or_default();
710 let claimed = dbtx
711 .find_by_prefix(&PegInTweakIndexPrefix)
712 .await
713 .filter_map(|(k, v)| async move {
714 if v.claimed.is_empty() {
715 None
716 } else {
717 Some(k.0)
718 }
719 })
720 .collect()
721 .await;
722 Ok(backup::WalletModuleBackup::new_v1(
723 session_count,
724 next_pegin_tweak_idx,
725 claimed,
726 ))
727 }
728
729 fn input_fee(
730 &self,
731 _amount: &Amounts,
732 _input: &<Self::Common as ModuleCommon>::Input,
733 ) -> Option<Amounts> {
734 Some(Amounts::new_bitcoin(self.cfg().fee_consensus.peg_in_abs))
735 }
736
737 fn output_fee(
738 &self,
739 _amount: &Amounts,
740 _output: &<Self::Common as ModuleCommon>::Output,
741 ) -> Option<Amounts> {
742 Some(Amounts::new_bitcoin(self.cfg().fee_consensus.peg_out_abs))
743 }
744
745 async fn handle_rpc(
746 &self,
747 method: String,
748 request: serde_json::Value,
749 ) -> BoxStream<'_, Result<serde_json::Value, ClientModuleError>> {
750 let stream: BoxStream<'_, Result<serde_json::Value, RpcError>> = Box::pin(try_stream! {
751 match method.as_str() {
752 "get_wallet_summary" => {
753 let _req: WalletSummaryRequest = serde_json::from_value(request)?;
754 let wallet_summary = self.get_wallet_summary()
755 .await
756 .expect("Failed to fetch wallet summary");
757 let result = serde_json::to_value(&wallet_summary)
758 .expect("Serialization error");
759 yield result;
760 }
761 "get_block_count_local" => {
762 let block_count = self.get_block_count_local().await
763 .expect("Failed to fetch block count");
764 yield serde_json::to_value(block_count)?;
765 }
766 "peg_in" => {
767 let req: PegInRequest = serde_json::from_value(request)?;
768 let response = self.peg_in(req)
769 .await
770 .map_err(RpcError::PegIn)?;
771 let result = serde_json::to_value(&response)?;
772 yield result;
773 },
774 "peg_out" => {
775 let req: PegOutRequest = serde_json::from_value(request)?;
776 let response = self.peg_out(req)
777 .await
778 .map_err(RpcError::PegOut)?;
779 let result = serde_json::to_value(&response)?;
780 yield result;
781 },
782 "subscribe_deposit" => {
783 let req: SubscribeDepositRequest = serde_json::from_value(request)?;
784 for await state in self.subscribe_deposit(req.operation_id).await?.into_stream() {
785 yield serde_json::to_value(state)?;
786 }
787 },
788 "subscribe_withdraw" => {
789 let req: SubscribeWithdrawRequest = serde_json::from_value(request)?;
790 for await state in self.subscribe_withdraw_updates(req.operation_id).await?.into_stream(){
791 yield serde_json::to_value(state)?;
792 }
793 }
794 _ => {
795 Err(RpcError::UnknownMethod { method: method.clone() })?;
796 }
797 }
798 });
799 Box::pin(stream.map_err(ClientModuleError::other))
800 }
801
802 #[cfg(feature = "cli")]
803 async fn handle_cli_command(
804 &self,
805 args: &[std::ffi::OsString],
806 ) -> Result<serde_json::Value, ClientModuleError> {
807 cli::handle_cli_command(self, args)
808 .await
809 .map_err(ClientModuleError::other)
810 }
811}
812
813#[derive(Debug, thiserror::Error)]
815enum RpcError {
816 #[error(transparent)]
819 Json(#[from] serde_json::Error),
820
821 #[error("peg_in failed")]
823 PegIn(#[source] DepositAddressError),
824
825 #[error("peg_out failed")]
827 PegOut(#[source] PegOutError),
828
829 #[error(transparent)]
831 SubscribeDeposit(#[from] SubscribeDepositError),
832
833 #[error(transparent)]
835 SubscribeWithdraw(#[from] SubscribeWithdrawError),
836
837 #[error("Unknown method: {method}")]
839 UnknownMethod { method: String },
840}
841
842#[derive(Deserialize)]
843struct WalletSummaryRequest {}
844
845#[derive(Debug, Clone)]
846pub struct WalletClientContext {
847 rpc: DynBitcoindRpc,
848 wallet_descriptor: PegInDescriptor,
849 wallet_decoder: Decoder,
850 secp: Secp256k1<All>,
851 pub client_ctx: ClientContext<WalletClientModule>,
852}
853
854#[derive(Debug, Clone, Serialize, Deserialize)]
855pub struct PegInRequest {
856 pub extra_meta: serde_json::Value,
857}
858
859#[derive(Deserialize)]
860struct SubscribeDepositRequest {
861 operation_id: OperationId,
862}
863
864#[derive(Deserialize)]
865struct SubscribeWithdrawRequest {
866 operation_id: OperationId,
867}
868
869#[derive(Debug, Clone, Serialize, Deserialize)]
870pub struct PegInResponse {
871 pub deposit_address: Address<NetworkUnchecked>,
872 pub operation_id: OperationId,
873}
874
875#[derive(Debug, Clone, Serialize, Deserialize)]
876pub struct PegOutRequest {
877 pub amount_sat: u64,
878 pub destination_address: Address<NetworkUnchecked>,
879 pub extra_meta: serde_json::Value,
880}
881
882#[derive(Debug, Clone, Serialize, Deserialize)]
883pub struct PegOutResponse {
884 pub operation_id: OperationId,
885}
886
887impl Context for WalletClientContext {
888 const KIND: Option<ModuleKind> = Some(KIND);
889}
890
891impl WalletClientModule {
892 fn cfg(&self) -> &WalletClientConfig {
893 &self.data.cfg
894 }
895
896 fn get_rpc_config(cfg: &WalletClientConfig) -> BitcoinRpcConfig {
897 match BitcoinRpcConfig::get_defaults_from_env_vars() {
898 Ok(rpc_config) => {
899 if rpc_config.kind == "bitcoind" {
902 cfg.default_bitcoin_rpc.clone()
903 } else {
904 rpc_config
905 }
906 }
907 _ => cfg.default_bitcoin_rpc.clone(),
908 }
909 }
910
911 pub fn get_network(&self) -> Network {
912 self.cfg().network.0
913 }
914
915 pub fn get_finality_delay(&self) -> u32 {
916 self.cfg().finality_delay
917 }
918
919 pub fn get_fee_consensus(&self) -> FeeConsensus {
920 self.cfg().fee_consensus
921 }
922
923 async fn allocate_deposit_address_inner(
924 &self,
925 dbtx: &mut DatabaseTransaction<'_>,
926 ) -> DepositAddressInfo {
927 dbtx.ensure_isolated().expect("Must be isolated db");
928
929 let tweak_idx = get_next_peg_in_tweak_child_id(dbtx).await;
930 let (_secret_tweak_key, _, address, operation_id) =
931 self.data.derive_deposit_address(tweak_idx);
932
933 let now = fedimint_core::time::now();
934
935 dbtx.insert_new_entry(
936 &PegInTweakIndexKey(tweak_idx),
937 &PegInTweakIndexData {
938 creation_time: now,
939 next_check_time: Some(now),
940 last_check_time: None,
941 operation_id,
942 claimed: vec![],
943 },
944 )
945 .await;
946
947 DepositAddressInfo {
948 operation_id,
949 address,
950 tweak_idx,
951 }
952 }
953
954 pub async fn get_withdraw_fees(
961 &self,
962 address: &bitcoin::Address,
963 amount: bitcoin::Amount,
964 ) -> Result<PegOutFees, WithdrawFeesError> {
965 self.module_api
966 .fetch_peg_out_fees(address, amount)
967 .await?
968 .ok_or(WithdrawFeesError::NoQuote)
969 }
970
971 pub async fn send_fee_quote(
986 &self,
987 amount: bitcoin::Amount,
988 ) -> Result<FeeQuote, TransactionSubmitError> {
989 let amount = fedimint_core::Amount::from_sats(amount.to_sat());
990 self.client_ctx
991 .fee_quote(
992 OperationId::new_random(),
993 FeeQuoteRequest {
994 input_amount: Amounts::ZERO,
995 output_amount: Amounts::new_bitcoin(amount),
996 input_fee: Amounts::ZERO,
997 output_fee: Amounts::new_bitcoin(self.cfg().fee_consensus.peg_out_abs),
998 account: Account::Primary,
999 },
1000 )
1001 .await
1002 }
1003
1004 pub async fn max_withdrawable_amount(
1039 &self,
1040 address: &bitcoin::Address,
1041 balance: fedimint_core::Amount,
1042 ) -> Result<(bitcoin::Amount, PegOutFees), MaxWithdrawableAmountError> {
1043 let max_fees = self
1046 .get_withdraw_fees(
1047 address,
1048 bitcoin::Amount::from_sat(balance.sats_round_down()),
1049 )
1050 .await?;
1051 let max_fee_msats = fedimint_core::Amount::from_sats(max_fees.amount().to_sat());
1052 let dust_limit = address.script_pubkey().minimal_non_dust();
1053
1054 let max = max_affordable_send_amount(
1055 balance,
1056 fedimint_core::Amount::from_sats(dust_limit.to_sat()),
1057 balance,
1058 |amount: fedimint_core::Amount| {
1062 fedimint_core::Amount::from_sats(amount.msats.div_ceil(1000)) + max_fee_msats
1063 },
1064 |funded: fedimint_core::Amount| {
1065 self.send_fee_quote(bitcoin::Amount::from_sat(funded.msats / 1000))
1066 },
1067 )
1068 .await
1069 .map_err(MaxWithdrawableAmountError::Quote)?
1070 .ok_or(MaxWithdrawableAmountError::BalanceTooLow {
1071 balance,
1072 dust_limit,
1073 })?;
1074
1075 let amount = bitcoin::Amount::from_sat(max.msats.div_ceil(1000));
1078
1079 let fees = self.get_withdraw_fees(address, amount).await?;
1084
1085 Ok((amount, fees))
1086 }
1087
1088 pub async fn get_wallet_summary(&self) -> FederationResult<WalletSummary> {
1090 self.module_api.fetch_wallet_summary().await
1091 }
1092
1093 pub async fn get_block_count_local(&self) -> FederationResult<u32> {
1094 self.module_api.fetch_block_count_local().await
1095 }
1096
1097 pub fn create_withdraw_output(
1098 &self,
1099 operation_id: OperationId,
1100 address: bitcoin::Address,
1101 amount: bitcoin::Amount,
1102 fees: PegOutFees,
1103 ) -> ClientOutputBundle<WalletOutput, WalletClientStates> {
1104 let output = WalletOutput::new_v0_peg_out(address, amount, fees);
1105
1106 let amount = output.maybe_v0_ref().expect("v0 output").amount().into();
1107
1108 let sm_gen = move |out_point_range: OutPointRange| {
1109 assert_eq!(out_point_range.count(), 1);
1110 let out_idx = out_point_range.start_idx();
1111 vec![WalletClientStates::Withdraw(WithdrawStateMachine {
1112 operation_id,
1113 state: WithdrawStates::Created(CreatedWithdrawState {
1114 fm_outpoint: OutPoint {
1115 txid: out_point_range.txid(),
1116 out_idx,
1117 },
1118 }),
1119 })]
1120 };
1121
1122 ClientOutputBundle::new(
1123 vec![ClientOutput::<WalletOutput> {
1124 output,
1125 amounts: Amounts::new_bitcoin(amount),
1126 }],
1127 vec![ClientOutputSM::<WalletClientStates> {
1128 state_machines: Arc::new(sm_gen),
1129 }],
1130 )
1131 }
1132
1133 pub async fn peg_in(&self, req: PegInRequest) -> Result<PegInResponse, DepositAddressError> {
1134 let deposit_address = self.safe_allocate_deposit_address(req.extra_meta).await?;
1135
1136 Ok(PegInResponse {
1137 deposit_address: deposit_address.address.into_unchecked(),
1138 operation_id: deposit_address.operation_id,
1139 })
1140 }
1141
1142 pub async fn peg_out(&self, req: PegOutRequest) -> Result<PegOutResponse, PegOutError> {
1143 let amount = bitcoin::Amount::from_sat(req.amount_sat);
1144 let network = self.get_network();
1145 let destination = req
1146 .destination_address
1147 .require_network(network)
1148 .map_err(|_| PegOutError::WrongNetwork { expected: network })?;
1149
1150 let fees = self.get_withdraw_fees(&destination, amount).await?;
1151 let operation_id = self
1152 .withdraw(&destination, amount, fees, req.extra_meta)
1153 .await?;
1154
1155 Ok(PegOutResponse { operation_id })
1156 }
1157
1158 pub fn create_rbf_withdraw_output(
1159 &self,
1160 operation_id: OperationId,
1161 rbf: &Rbf,
1162 ) -> ClientOutputBundle<WalletOutput, WalletClientStates> {
1163 let output = WalletOutput::new_v0_rbf(rbf.fees, rbf.txid);
1164
1165 let amount = output.maybe_v0_ref().expect("v0 output").amount().into();
1166
1167 let sm_gen = move |out_point_range: OutPointRange| {
1168 assert_eq!(out_point_range.count(), 1);
1169 let out_idx = out_point_range.start_idx();
1170 vec![WalletClientStates::Withdraw(WithdrawStateMachine {
1171 operation_id,
1172 state: WithdrawStates::Created(CreatedWithdrawState {
1173 fm_outpoint: OutPoint {
1174 txid: out_point_range.txid(),
1175 out_idx,
1176 },
1177 }),
1178 })]
1179 };
1180
1181 ClientOutputBundle::new(
1182 vec![ClientOutput::<WalletOutput> {
1183 output,
1184 amounts: Amounts::new_bitcoin(amount),
1185 }],
1186 vec![ClientOutputSM::<WalletClientStates> {
1187 state_machines: Arc::new(sm_gen),
1188 }],
1189 )
1190 }
1191
1192 pub async fn btc_tx_has_no_size_limit(&self) -> FederationResult<bool> {
1193 Ok(self.module_api.module_consensus_version().await? >= ModuleConsensusVersion::new(2, 2))
1194 }
1195
1196 pub async fn supports_safe_deposit(&self) -> bool {
1205 if supports_safe_deposit_verified(&self.db).await {
1206 return true;
1207 }
1208
1209 verify_supports_safe_deposit(&self.db, &self.module_api)
1210 .await
1211 .unwrap_or(false)
1212 }
1213
1214 pub async fn safe_allocate_deposit_address<M>(
1222 &self,
1223 extra_meta: M,
1224 ) -> Result<DepositAddressInfo, DepositAddressError>
1225 where
1226 M: Serialize + MaybeSend + MaybeSync,
1227 {
1228 if !self.supports_safe_deposit().await {
1229 return Err(DepositAddressError::SafeDepositUnverified);
1230 }
1231
1232 self.allocate_deposit_address_expert_only(extra_meta).await
1233 }
1234
1235 pub async fn allocate_deposit_address_expert_only<M>(
1253 &self,
1254 extra_meta: M,
1255 ) -> Result<DepositAddressInfo, DepositAddressError>
1256 where
1257 M: Serialize + MaybeSend + MaybeSync,
1258 {
1259 let extra_meta_value =
1260 serde_json::to_value(extra_meta).expect("Failed to serialize extra meta");
1261 let deposit_address = self
1262 .db
1263 .autocommit(
1264 move |dbtx, _| {
1265 let extra_meta_value_inner = extra_meta_value.clone();
1266 Box::pin(async move {
1267 let deposit_address = self.allocate_deposit_address_inner(dbtx).await;
1268
1269 self.client_ctx
1270 .manual_operation_start_dbtx(
1271 dbtx,
1272 deposit_address.operation_id,
1273 Account::Primary,
1274 WalletCommonInit::KIND.as_str(),
1275 WalletOperationMeta {
1276 variant: WalletOperationMetaVariant::Deposit {
1277 address: deposit_address.address.clone().into_unchecked(),
1278 tweak_idx: Some(deposit_address.tweak_idx),
1279 expires_at: None,
1280 },
1281 extra_meta: extra_meta_value_inner,
1282 },
1283 vec![],
1284 )
1285 .await?;
1286
1287 debug!(
1288 target: LOG_CLIENT_MODULE_WALLET,
1289 tweak_idx = %deposit_address.tweak_idx,
1290 address = %deposit_address.address,
1291 "Derived a new deposit address"
1292 );
1293
1294 self.rpc
1296 .watch_script_history(&deposit_address.address.script_pubkey())
1297 .await?;
1298
1299 let sender = self.pegin_monitor_wakeup_sender.clone();
1300 dbtx.on_commit(move || {
1301 sender.send_replace(());
1302 });
1303
1304 Ok(deposit_address)
1305 })
1306 },
1307 Some(100),
1308 )
1309 .await?;
1310
1311 Ok(deposit_address)
1312 }
1313
1314 pub async fn allocate_deposit_address_pooled_stateless(
1352 &self,
1353 max_gap_size: usize,
1354 ) -> Result<MaybeNewAddress, DepositAddressError> {
1355 let max_gap_size_u64 = u64::try_from(max_gap_size).unwrap_or(u64::MAX);
1356 let extra_meta_value = serde_json::Value::Null;
1357 let result = self
1358 .db
1359 .autocommit(
1360 move |dbtx, _| {
1361 let extra_meta_value_inner = extra_meta_value.clone();
1362 Box::pin(async move {
1363 let unused = self.unused_pooled_deposit_addresses(dbtx).await;
1364
1365 if max_gap_size_u64 <= unused.len() as u64 && !unused.is_empty() {
1366 let addresses = unused
1367 .into_iter()
1368 .map(|(tweak_idx, data)| {
1369 let (_script, address, _key, operation_id) =
1370 self.data.derive_peg_in_script(tweak_idx);
1371
1372 debug_assert_eq!(operation_id, data.operation_id);
1373
1374 DepositAddressInfo {
1375 operation_id,
1376 address,
1377 tweak_idx,
1378 }
1379 })
1380 .collect();
1381
1382 return Ok::<_, DepositAddressError>(
1383 MaybeNewAddress::TooManyUnusedAddresses(addresses),
1384 );
1385 }
1386
1387 let deposit_address = self.allocate_deposit_address_inner(dbtx).await;
1388
1389 self.client_ctx
1390 .manual_operation_start_dbtx(
1391 dbtx,
1392 deposit_address.operation_id,
1393 Account::Primary,
1394 WalletCommonInit::KIND.as_str(),
1395 WalletOperationMeta {
1396 variant: WalletOperationMetaVariant::Deposit {
1397 address: deposit_address.address.clone().into_unchecked(),
1398 tweak_idx: Some(deposit_address.tweak_idx),
1399 expires_at: None,
1400 },
1401 extra_meta: extra_meta_value_inner,
1402 },
1403 vec![],
1404 )
1405 .await?;
1406
1407 debug!(
1408 target: LOG_CLIENT_MODULE_WALLET,
1409 tweak_idx = %deposit_address.tweak_idx,
1410 address = %deposit_address.address,
1411 "Derived a new pooled deposit address"
1412 );
1413
1414 self.rpc
1415 .watch_script_history(&deposit_address.address.script_pubkey())
1416 .await?;
1417
1418 let sender = self.pegin_monitor_wakeup_sender.clone();
1419 dbtx.on_commit(move || {
1420 sender.send_replace(());
1421 });
1422
1423 Ok(MaybeNewAddress::NewAddress(deposit_address))
1424 })
1425 },
1426 Some(100),
1427 )
1428 .await?;
1429
1430 Ok(result)
1431 }
1432
1433 async fn unused_pooled_deposit_addresses(
1434 &self,
1435 dbtx: &mut DatabaseTransaction<'_>,
1436 ) -> Vec<(TweakIdx, PegInTweakIndexData)> {
1437 let mut unused: Vec<(TweakIdx, PegInTweakIndexData)> = dbtx
1442 .find_by_prefix_sorted_descending(&PegInTweakIndexPrefix)
1443 .await
1444 .take_while(|(_, d)| std::future::ready(d.claimed.is_empty()))
1445 .map(|(k, v)| (k.0, v))
1446 .collect()
1447 .await;
1448
1449 unused.sort_by_key(|(t, d)| (d.creation_time, *t));
1452 unused
1453 }
1454
1455 #[allow(clippy::too_many_lines)]
1478 pub async fn allocate_deposit_address_pooled(
1479 &self,
1480 max_gap_size: usize,
1481 ) -> Result<(DepositAddressInfo, AllocateDepositOutcome), DepositAddressError> {
1482 let stateless = self
1483 .allocate_deposit_address_pooled_stateless(max_gap_size)
1484 .await?;
1485
1486 let reused_addresses = match stateless {
1487 MaybeNewAddress::NewAddress(deposit_address) => {
1488 return Ok((deposit_address, AllocateDepositOutcome::Fresh));
1489 }
1490 MaybeNewAddress::TooManyUnusedAddresses(addresses) => addresses,
1491 };
1492
1493 let result = self
1494 .db
1495 .autocommit(
1496 move |dbtx, _| {
1497 let reused_addresses = reused_addresses.clone();
1498 Box::pin(async move {
1499 let cursor = dbtx
1500 .get_value(&PegInPoolCursorKey)
1501 .await
1502 .unwrap_or(TweakIdx(0));
1503
1504 let pick_pos = reused_addresses
1505 .iter()
1506 .position(|a| cursor <= a.tweak_idx)
1507 .unwrap_or(0);
1508 let reused_address = reused_addresses[pick_pos].clone();
1509
1510 let existing_tweak_idx = reused_address.tweak_idx;
1511 let existing = dbtx
1512 .get_value(&PegInTweakIndexKey(reused_address.tweak_idx))
1513 .await
1514 .ok_or(DepositAddressError::PooledAddressDisappeared {
1515 tweak_idx: reused_address.tweak_idx,
1516 })?;
1517
1518 if !existing.claimed.is_empty() {
1519 return Err(DepositAddressError::PooledAddressUsed {
1520 tweak_idx: reused_address.tweak_idx,
1521 });
1522 }
1523
1524 dbtx.insert_entry(&PegInPoolCursorKey, &reused_address.tweak_idx.next())
1525 .await;
1526
1527 let now = fedimint_core::time::now();
1535 dbtx.insert_entry(
1536 &PegInTweakIndexKey(reused_address.tweak_idx),
1537 &PegInTweakIndexData {
1538 creation_time: now,
1539 last_check_time: None,
1540 next_check_time: Some(now),
1541 operation_id: existing.operation_id,
1542 claimed: existing.claimed,
1543 },
1544 )
1545 .await;
1546
1547 let sender = self.pegin_monitor_wakeup_sender.clone();
1548 dbtx.on_commit(move || {
1549 sender.send_replace(());
1550 });
1551
1552 Ok::<_, DepositAddressError>((
1553 reused_address,
1554 AllocateDepositOutcome::Reused {
1555 original_tweak_idx: existing_tweak_idx,
1556 },
1557 ))
1558 })
1559 },
1560 Some(100),
1561 )
1562 .await?;
1563
1564 Ok(result)
1565 }
1566
1567 pub async fn subscribe_deposit(
1573 &self,
1574 operation_id: OperationId,
1575 ) -> Result<UpdateStreamOrOutcome<DepositStateV2>, SubscribeDepositError> {
1576 let operation = self.client_ctx.get_operation(operation_id).await?;
1577
1578 let operation_meta = operation.meta::<WalletOperationMeta>();
1579
1580 let WalletOperationMetaVariant::Deposit {
1581 address, tweak_idx, ..
1582 } = operation_meta.variant
1583 else {
1584 return Err(SubscribeDepositError::NotADeposit);
1585 };
1586
1587 let network = self.cfg().network.0;
1588 let address = address
1589 .require_network(network)
1590 .map_err(|_| SubscribeDepositError::WrongNetwork { expected: network })?;
1591
1592 let Some(tweak_idx) = tweak_idx else {
1594 let outcome_v1 = operation
1598 .outcome::<DepositStateV1>()
1599 .ok_or(SubscribeDepositError::OldPendingDeposit)?;
1600
1601 let outcome_v2 = match outcome_v1 {
1602 DepositStateV1::Claimed(tx_info) => DepositStateV2::Claimed {
1603 btc_deposited: tx_info.btc_transaction.output[tx_info.out_idx as usize].value,
1604 btc_out_point: bitcoin::OutPoint {
1605 txid: tx_info.btc_transaction.compute_txid(),
1606 vout: tx_info.out_idx,
1607 },
1608 },
1609 DepositStateV1::Failed(error) => DepositStateV2::Failed(error),
1610 _ => return Err(SubscribeDepositError::NonFinalOutcome),
1611 };
1612
1613 return Ok(UpdateStreamOrOutcome::Outcome(outcome_v2));
1614 };
1615
1616 Ok(self.client_ctx.outcome_or_updates(
1617 &operation,
1618 operation_id,
1619 |state| match state {
1620 DepositStateV2::WaitingForTransaction
1621 | DepositStateV2::WaitingForConfirmation { .. }
1622 | DepositStateV2::Confirmed { .. } => false,
1623 DepositStateV2::Claimed { .. } | DepositStateV2::Failed(_) => true,
1624 },
1625 {
1626 let stream_rpc = self.rpc.clone();
1627 let stream_client_ctx = self.client_ctx.clone();
1628 let stream_script_pub_key = address.script_pubkey();
1629 move || {
1630
1631 stream! {
1632 yield DepositStateV2::WaitingForTransaction;
1633
1634 retry(
1635 "subscribe script history",
1636 background_backoff(),
1637 || stream_rpc.watch_script_history(&stream_script_pub_key)
1638 ).await.expect("Will never give up");
1639 let (btc_out_point, btc_deposited) = retry(
1640 "fetch history",
1641 background_backoff(),
1642 || async {
1643 let history = stream_rpc.get_script_history(&stream_script_pub_key).await?;
1644 history.first().and_then(|tx| {
1645 let (out_idx, amount) = tx.output
1646 .iter()
1647 .enumerate()
1648 .find_map(|(idx, output)| (output.script_pubkey == stream_script_pub_key).then_some((idx, output.value)))?;
1649 let txid = tx.compute_txid();
1650
1651 Some((
1652 bitcoin::OutPoint {
1653 txid,
1654 vout: out_idx as u32,
1655 },
1656 amount
1657 ))
1658 }).ok_or(FetchDepositTransactionError::NotFound)
1659 }
1660 ).await.expect("Will never give up");
1661
1662 yield DepositStateV2::WaitingForConfirmation {
1663 btc_deposited,
1664 btc_out_point
1665 };
1666
1667 let claim_data = stream_client_ctx.module_db().wait_key_exists(&ClaimedPegInKey {
1668 peg_in_index: tweak_idx,
1669 btc_out_point,
1670 }).await;
1671
1672 yield DepositStateV2::Confirmed {
1673 btc_deposited,
1674 btc_out_point
1675 };
1676
1677 match stream_client_ctx.await_primary_module_outputs(operation_id, claim_data.change).await {
1678 Ok(()) => yield DepositStateV2::Claimed {
1679 btc_deposited,
1680 btc_out_point
1681 },
1682 Err(e) => yield DepositStateV2::Failed(e.fmt_compact().to_string())
1683 }
1684 }
1685 }}))
1686 }
1687
1688 pub async fn list_peg_in_tweak_idxes(&self) -> BTreeMap<TweakIdx, PegInTweakIndexData> {
1689 self.client_ctx
1690 .module_db()
1691 .clone()
1692 .begin_transaction_nc()
1693 .await
1694 .find_by_prefix(&PegInTweakIndexPrefix)
1695 .await
1696 .map(|(key, data)| (key.0, data))
1697 .collect()
1698 .await
1699 }
1700
1701 pub async fn find_tweak_idx_by_address(
1702 &self,
1703 address: bitcoin::Address<NetworkUnchecked>,
1704 ) -> Result<TweakIdx, PegInError> {
1705 let data = self.data.clone();
1706 let Some((tweak_idx, _)) = self
1707 .db
1708 .begin_transaction_nc()
1709 .await
1710 .find_by_prefix(&PegInTweakIndexPrefix)
1711 .await
1712 .filter(|(k, _)| {
1713 let (_, derived_address, _tweak_key, _) = data.derive_peg_in_script(k.0);
1714 future::ready(derived_address.into_unchecked() == address)
1715 })
1716 .next()
1717 .await
1718 else {
1719 return Err(PegInError::AddressNotDerived);
1720 };
1721
1722 Ok(tweak_idx.0)
1723 }
1724 pub async fn find_tweak_idx_by_operation_id(
1725 &self,
1726 operation_id: OperationId,
1727 ) -> Result<TweakIdx, PegInError> {
1728 Ok(self
1729 .client_ctx
1730 .module_db()
1731 .clone()
1732 .begin_transaction_nc()
1733 .await
1734 .find_by_prefix(&PegInTweakIndexPrefix)
1735 .await
1736 .filter(|(_k, v)| future::ready(v.operation_id == operation_id))
1737 .next()
1738 .await
1739 .ok_or(PegInError::NoAddressForOperation { operation_id })?
1740 .0
1741 .0)
1742 }
1743
1744 pub async fn get_pegin_tweak_idx(
1745 &self,
1746 tweak_idx: TweakIdx,
1747 ) -> Result<PegInTweakIndexData, PegInError> {
1748 self.client_ctx
1749 .module_db()
1750 .clone()
1751 .begin_transaction_nc()
1752 .await
1753 .get_value(&PegInTweakIndexKey(tweak_idx))
1754 .await
1755 .ok_or(PegInError::TweakIdxNotFound { tweak_idx })
1756 }
1757
1758 pub async fn get_claimed_pegins(
1759 &self,
1760 dbtx: &mut DatabaseTransaction<'_>,
1761 tweak_idx: TweakIdx,
1762 ) -> Vec<(
1763 bitcoin::OutPoint,
1764 TransactionId,
1765 Vec<fedimint_core::OutPoint>,
1766 )> {
1767 let outpoints = dbtx
1768 .get_value(&PegInTweakIndexKey(tweak_idx))
1769 .await
1770 .map(|v| v.claimed)
1771 .unwrap_or_default();
1772
1773 let mut res = vec![];
1774
1775 for outpoint in outpoints {
1776 let claimed_peg_in_data = dbtx
1777 .get_value(&ClaimedPegInKey {
1778 peg_in_index: tweak_idx,
1779 btc_out_point: outpoint,
1780 })
1781 .await
1782 .expect("Must have a corresponding claim record");
1783 res.push((
1784 outpoint,
1785 claimed_peg_in_data.claim_txid,
1786 claimed_peg_in_data.change,
1787 ));
1788 }
1789
1790 res
1791 }
1792
1793 pub async fn recheck_pegin_address_by_op_id(
1795 &self,
1796 operation_id: OperationId,
1797 ) -> Result<(), PegInError> {
1798 let tweak_idx = self.find_tweak_idx_by_operation_id(operation_id).await?;
1799
1800 self.recheck_pegin_address(tweak_idx).await
1801 }
1802
1803 pub async fn recheck_pegin_address_by_address(
1805 &self,
1806 address: bitcoin::Address<NetworkUnchecked>,
1807 ) -> Result<(), PegInError> {
1808 self.recheck_pegin_address(self.find_tweak_idx_by_address(address).await?)
1809 .await
1810 }
1811
1812 pub async fn recheck_pegin_address(&self, tweak_idx: TweakIdx) -> Result<(), PegInError> {
1814 self.db
1815 .autocommit(
1816 |dbtx, _| {
1817 Box::pin(async {
1818 let db_key = PegInTweakIndexKey(tweak_idx);
1819 let db_val = dbtx
1820 .get_value(&db_key)
1821 .await
1822 .ok_or(PegInError::TweakIdxNotFound { tweak_idx })?;
1823
1824 dbtx.insert_entry(
1825 &db_key,
1826 &PegInTweakIndexData {
1827 next_check_time: Some(fedimint_core::time::now()),
1828 ..db_val
1829 },
1830 )
1831 .await;
1832
1833 let sender = self.pegin_monitor_wakeup_sender.clone();
1834 dbtx.on_commit(move || {
1835 sender.send_replace(());
1836 });
1837
1838 Ok::<_, PegInError>(())
1839 })
1840 },
1841 Some(100),
1842 )
1843 .await?;
1844
1845 Ok(())
1846 }
1847
1848 pub async fn await_num_deposits_by_operation_id(
1850 &self,
1851 operation_id: OperationId,
1852 num_deposits: usize,
1853 ) -> Result<(), PegInError> {
1854 let tweak_idx = self.find_tweak_idx_by_operation_id(operation_id).await?;
1855 self.await_num_deposits(tweak_idx, num_deposits).await
1856 }
1857
1858 pub async fn await_num_deposits_by_address(
1859 &self,
1860 address: bitcoin::Address<NetworkUnchecked>,
1861 num_deposits: usize,
1862 ) -> Result<(), PegInError> {
1863 self.await_num_deposits(self.find_tweak_idx_by_address(address).await?, num_deposits)
1864 .await
1865 }
1866
1867 #[instrument(target = LOG_CLIENT_MODULE_WALLET, skip_all, fields(tweak_idx=?tweak_idx, num_deposists=num_deposits))]
1868 pub async fn await_num_deposits(
1869 &self,
1870 tweak_idx: TweakIdx,
1871 num_deposits: usize,
1872 ) -> Result<(), PegInError> {
1873 let operation_id = self.get_pegin_tweak_idx(tweak_idx).await?.operation_id;
1874
1875 let mut receiver = self.pegin_claimed_receiver.clone();
1876 let mut backoff = backoff_util::aggressive_backoff();
1877
1878 loop {
1879 let pegins = self
1880 .get_claimed_pegins(
1881 &mut self.client_ctx.module_db().begin_transaction_nc().await,
1882 tweak_idx,
1883 )
1884 .await;
1885
1886 if pegins.len() < num_deposits {
1887 debug!(target: LOG_CLIENT_MODULE_WALLET, has=pegins.len(), "Not enough deposits");
1888 self.recheck_pegin_address(tweak_idx).await?;
1889 runtime::sleep(backoff.next().unwrap_or_default()).await;
1890 receiver
1891 .changed()
1892 .await
1893 .map_err(|_| PegInError::MonitorStopped)?;
1894 continue;
1895 }
1896
1897 debug!(target: LOG_CLIENT_MODULE_WALLET, has=pegins.len(), "Enough deposits detected");
1898
1899 for (_outpoint, transaction_id, change) in pegins {
1900 if transaction_id == TransactionId::from_byte_array([0; 32]) && change.is_empty() {
1901 debug!(target: LOG_CLIENT_MODULE_WALLET, "Deposited amount was too low, skipping");
1902 continue;
1903 }
1904
1905 debug!(target: LOG_CLIENT_MODULE_WALLET, out_points=?change, "Ensuring deposists claimed");
1906 let tx_subscriber = self.client_ctx.transaction_updates(operation_id).await;
1907
1908 if let Err(reason) = tx_subscriber.await_tx_accepted(transaction_id).await {
1909 return Err(PegInError::TransactionRejected { reason });
1910 }
1911
1912 debug!(target: LOG_CLIENT_MODULE_WALLET, out_points=?change, "Ensuring outputs claimed");
1913 self.client_ctx
1914 .await_primary_module_outputs(operation_id, change)
1915 .await
1916 .expect("Cannot fail if tx was accepted and federation is honest");
1917 }
1918
1919 return Ok(());
1920 }
1921 }
1922
1923 pub async fn withdraw<M: Serialize + MaybeSend + MaybeSync>(
1928 &self,
1929 address: &bitcoin::Address,
1930 amount: bitcoin::Amount,
1931 fee: PegOutFees,
1932 extra_meta: M,
1933 ) -> Result<OperationId, TransactionSubmitError> {
1934 {
1935 let operation_id = OperationId(thread_rng().r#gen());
1936
1937 let withdraw_output =
1938 self.create_withdraw_output(operation_id, address.clone(), amount, fee);
1939 let tx_builder = TransactionBuilder::new(Account::Primary)
1940 .with_outputs(self.client_ctx.make_client_outputs(withdraw_output));
1941
1942 let extra_meta =
1943 serde_json::to_value(extra_meta).expect("Failed to serialize extra meta");
1944 self.client_ctx
1945 .finalize_and_submit_transaction(
1946 operation_id,
1947 WalletCommonInit::KIND.as_str(),
1948 {
1949 let address = address.clone();
1950 move |change_range: OutPointRange| WalletOperationMeta {
1951 variant: WalletOperationMetaVariant::Withdraw {
1952 address: address.clone().into_unchecked(),
1953 amount,
1954 fee,
1955 change: change_range.into_iter().collect(),
1956 },
1957 extra_meta: extra_meta.clone(),
1958 }
1959 },
1960 tx_builder,
1961 )
1962 .await?;
1963
1964 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
1965
1966 self.client_ctx
1967 .log_event(
1968 &mut dbtx,
1969 SendPaymentEvent {
1970 operation_id,
1971 amount: amount + fee.amount(),
1972 fee: fee.amount(),
1973 },
1974 )
1975 .await;
1976
1977 dbtx.commit_tx().await;
1978
1979 Ok(operation_id)
1980 }
1981 }
1982
1983 #[deprecated(
1988 since = "0.4.0",
1989 note = "RBF withdrawals are rejected by the federation"
1990 )]
1991 pub async fn rbf_withdraw<M: Serialize + MaybeSync + MaybeSend>(
1992 &self,
1993 rbf: Rbf,
1994 extra_meta: M,
1995 ) -> Result<OperationId, TransactionSubmitError> {
1996 let operation_id = OperationId(thread_rng().r#gen());
1997
1998 let withdraw_output = self.create_rbf_withdraw_output(operation_id, &rbf);
1999 let tx_builder = TransactionBuilder::new(Account::Primary)
2000 .with_outputs(self.client_ctx.make_client_outputs(withdraw_output));
2001
2002 let extra_meta = serde_json::to_value(extra_meta).expect("Failed to serialize extra meta");
2003 self.client_ctx
2004 .finalize_and_submit_transaction(
2005 operation_id,
2006 WalletCommonInit::KIND.as_str(),
2007 move |change_range: OutPointRange| WalletOperationMeta {
2008 variant: WalletOperationMetaVariant::RbfWithdraw {
2009 rbf: rbf.clone(),
2010 change: change_range.into_iter().collect(),
2011 },
2012 extra_meta: extra_meta.clone(),
2013 },
2014 tx_builder,
2015 )
2016 .await?;
2017
2018 Ok(operation_id)
2019 }
2020
2021 pub async fn subscribe_withdraw_updates(
2022 &self,
2023 operation_id: OperationId,
2024 ) -> Result<UpdateStreamOrOutcome<WithdrawState>, SubscribeWithdrawError> {
2025 let operation = self.client_ctx.get_operation(operation_id).await?;
2026
2027 let operation_meta = operation.meta::<WalletOperationMeta>();
2028
2029 let (WalletOperationMetaVariant::Withdraw { change, .. }
2030 | WalletOperationMetaVariant::RbfWithdraw { change, .. }) = operation_meta.variant
2031 else {
2032 return Err(SubscribeWithdrawError::NotAWithdrawal);
2033 };
2034
2035 let mut operation_stream = self.notifier.subscribe(operation_id).await;
2036 let client_ctx = self.client_ctx.clone();
2037
2038 Ok(self.client_ctx.outcome_or_updates(
2039 &operation,
2040 operation_id,
2041 |state| match state {
2042 WithdrawState::Created => false,
2043 WithdrawState::Succeeded(_) | WithdrawState::Failed(_) => true,
2044 },
2045 move || {
2046 stream! {
2047 match next_withdraw_state(&mut operation_stream).await {
2048 Some(WithdrawStates::Created(_)) => {
2049 yield WithdrawState::Created;
2050 },
2051 Some(s) => {
2052 panic!("Unexpected state {s:?}")
2053 },
2054 None => return,
2055 }
2056
2057 let _ = client_ctx
2062 .await_primary_module_outputs(operation_id, change)
2063 .await;
2064
2065
2066 match next_withdraw_state(&mut operation_stream).await {
2067 Some(WithdrawStates::Aborted(inner)) => {
2068 yield WithdrawState::Failed(inner.error);
2069 },
2070 Some(WithdrawStates::Success(inner)) => {
2071 yield WithdrawState::Succeeded(inner.txid);
2072 },
2073 Some(s) => {
2074 panic!("Unexpected state {s:?}")
2075 },
2076 None => {},
2077 }
2078 }
2079 },
2080 ))
2081 }
2082
2083 fn admin_auth(&self) -> Result<ApiAuth, ConsensusVersionVotingError> {
2084 self.admin_auth
2085 .clone()
2086 .ok_or(ConsensusVersionVotingError::AdminAuthMissing)
2087 }
2088
2089 pub async fn activate_consensus_version_voting(
2090 &self,
2091 ) -> Result<(), ConsensusVersionVotingError> {
2092 self.module_api
2093 .activate_consensus_version_voting(self.admin_auth()?)
2094 .await?;
2095
2096 Ok(())
2097 }
2098}
2099
2100#[derive(Debug, thiserror::Error)]
2103enum FetchDepositTransactionError {
2104 #[error(transparent)]
2106 BitcoinRpc(#[from] BitcoinRpcError),
2107
2108 #[error("No deposit transaction found")]
2110 NotFound,
2111}
2112
2113async fn poll_supports_safe_deposit_version(db: Database, module_api: DynModuleApi) {
2116 loop {
2117 if supports_safe_deposit_verified(&db).await {
2118 break;
2119 }
2120
2121 module_api.wait_for_initialized_connections().await;
2122
2123 if verify_supports_safe_deposit(&db, &module_api).await == Some(true) {
2124 break;
2125 }
2126
2127 if is_running_in_test_env() {
2128 sleep(Duration::from_secs(10)).await;
2130 } else {
2131 sleep(Duration::from_hours(1)).await;
2132 }
2133 }
2134}
2135
2136async fn supports_safe_deposit_verified(db: &Database) -> bool {
2139 db.begin_transaction_nc()
2140 .await
2141 .get_value(&SupportsSafeDepositKey)
2142 .await
2143 .is_some()
2144}
2145
2146async fn verify_supports_safe_deposit(db: &Database, module_api: &DynModuleApi) -> Option<bool> {
2151 let module_consensus_version = match module_api.module_consensus_version().await {
2152 Ok(module_consensus_version) => module_consensus_version,
2153 Err(err) => {
2154 debug!(
2155 target: LOG_CLIENT_MODULE_WALLET,
2156 err = %err.fmt_compact(),
2157 "Could not fetch the wallet module consensus version"
2158 );
2159 return None;
2160 }
2161 };
2162
2163 let supported_version = SAFE_DEPOSIT_MODULE_CONSENSUS_VERSION <= module_consensus_version;
2164
2165 if supported_version {
2166 store_supports_safe_deposit(db.begin_transaction().await).await;
2167 }
2168
2169 Some(supported_version)
2170}
2171
2172async fn store_supports_safe_deposit(mut dbtx: DatabaseTransaction<'_, Committable>) {
2187 if dbtx.get_value(&SupportsSafeDepositKey).await.is_some() {
2188 return;
2190 }
2191
2192 dbtx.insert_entry(&SupportsSafeDepositKey, &()).await;
2193
2194 match dbtx.commit_tx_result().await {
2195 Ok(()) | Err(DatabaseError::WriteConflict) => {}
2196 Err(err) => {
2197 warn!(
2198 target: LOG_CLIENT_MODULE_WALLET,
2199 err = %err.fmt_compact(),
2200 "Failed to store the safe-deposit marker"
2201 );
2202 }
2203 }
2204}
2205
2206async fn get_next_peg_in_tweak_child_id(dbtx: &mut DatabaseTransaction<'_>) -> TweakIdx {
2208 let index = dbtx
2209 .get_value(&NextPegInTweakIndexKey)
2210 .await
2211 .unwrap_or_default();
2212 dbtx.insert_entry(&NextPegInTweakIndexKey, &(index.next()))
2213 .await;
2214 index
2215}
2216
2217#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
2218pub enum WalletClientStates {
2219 Deposit(DepositStateMachine),
2220 Withdraw(WithdrawStateMachine),
2221}
2222
2223impl IntoDynInstance for WalletClientStates {
2224 type DynType = DynState;
2225
2226 fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
2227 DynState::from_typed(instance_id, self)
2228 }
2229}
2230
2231impl State for WalletClientStates {
2232 type ModuleContext = WalletClientContext;
2233
2234 fn transitions(
2235 &self,
2236 context: &Self::ModuleContext,
2237 global_context: &DynGlobalClientContext,
2238 ) -> Vec<StateTransition<Self>> {
2239 match self {
2240 WalletClientStates::Deposit(sm) => {
2241 sm_enum_variant_translation!(
2242 sm.transitions(context, global_context),
2243 WalletClientStates::Deposit
2244 )
2245 }
2246 WalletClientStates::Withdraw(sm) => {
2247 sm_enum_variant_translation!(
2248 sm.transitions(context, global_context),
2249 WalletClientStates::Withdraw
2250 )
2251 }
2252 }
2253 }
2254
2255 fn operation_id(&self) -> OperationId {
2256 match self {
2257 WalletClientStates::Deposit(sm) => sm.operation_id(),
2258 WalletClientStates::Withdraw(sm) => sm.operation_id(),
2259 }
2260 }
2261}
2262
2263#[cfg(all(test, not(target_family = "wasm")))]
2264mod tests;