1#![deny(clippy::pedantic)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::missing_panics_doc)]
4#![allow(clippy::must_use_candidate)]
5#![allow(clippy::module_name_repetitions)]
6
7pub use fedimint_walletv2_common as common;
8pub use fedimint_walletv2_common::MempoolVisibility;
9
10mod api;
11#[cfg(feature = "cli")]
12mod cli;
13pub mod db;
14pub mod events;
15mod migrations;
16mod receive_sm;
17mod send_sm;
18
19use std::collections::{BTreeMap, BTreeSet};
20use std::sync::Arc;
21use std::time::Duration;
22
23use api::WalletFederationApi;
24use bitcoin::address::NetworkUnchecked;
25use bitcoin::{Address, ScriptBuf};
26use db::{
27 NextOutputIndexKey, ValidAddressIndexAccountPrefix, ValidAddressIndexKey,
28 ValidAddressIndexPrefix,
29};
30use events::{ReceivePaymentEvent, SendPaymentEvent};
31use fedimint_api_client::api::{DynModuleApi, FederationError, FederationResult};
32use fedimint_client::DynGlobalClientContext;
33use fedimint_client::transaction::{
34 ClientInput, ClientInputBundle, ClientInputSM, ClientOutput, ClientOutputBundle,
35 ClientOutputSM, FeeQuote, FeeQuoteRequest, TransactionBuilder, max_affordable_send_amount,
36};
37use fedimint_client_module::db::ClientModuleMigrationFn;
38use fedimint_client_module::error::{
39 ClientModuleError, OperationLookupError, TransactionSubmitError,
40};
41use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
42use fedimint_client_module::module::recovery::NoModuleBackup;
43use fedimint_client_module::module::{ClientContext, ClientModule, OutPointRange};
44use fedimint_client_module::secret::DeriveableSecretClientExt;
45use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
46use fedimint_client_module::sm_enum_variant_translation;
47use fedimint_core::core::{Account, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
48use fedimint_core::db::{
49 Database, DatabaseError, DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped,
50};
51use fedimint_core::encoding::{Decodable, Encodable};
52use fedimint_core::module::{
53 AmountUnit, Amounts, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
54};
55use fedimint_core::task::{TaskGroup, TaskHandle, sleep};
56use fedimint_core::{Amount, OutPoint, TransactionId, apply, async_trait_maybe_send};
57use fedimint_derive_secret::{ChildId, DerivableSecret};
58use fedimint_eventlog::{Event, EventLogId};
59use fedimint_logging::LOG_CLIENT_MODULE_WALLETV2;
60use fedimint_walletv2_common::config::WalletClientConfig;
61use fedimint_walletv2_common::{
62 BLOCK_COUNT_VOTE_DELAY, KIND, OutputInfo, PendingOutput, PendingOutputs, StandardScript,
63 TxInfo, WalletCommonInit, WalletInput, WalletInputV0, WalletModuleTypes, WalletOutput,
64 WalletOutputV0, descriptor, is_potential_receive,
65};
66use futures::StreamExt;
67use receive_sm::{ReceiveSMCommon, ReceiveSMState, ReceiveStateMachine};
68use secp256k1::Keypair;
69use send_sm::{SendSMCommon, SendSMState, SendStateMachine};
70use serde::{Deserialize, Serialize};
71use strum::IntoEnumIterator as _;
72use thiserror::Error;
73use tracing::{debug, warn};
74
75const SLICE_SIZE: u64 = 1000;
77
78const EVENT_LOG_PAGE_SIZE: u64 = 1000;
80
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub enum WalletOperationMeta {
83 Send(SendMeta),
84 Receive(ReceiveMeta),
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct SendMeta {
89 pub change_outpoint_range: OutPointRange,
90 pub address: Address<NetworkUnchecked>,
91 pub value: bitcoin::Amount,
92 pub fee: bitcoin::Amount,
93 #[serde(default)]
94 pub custom_meta: serde_json::Value,
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct ReceiveMeta {
99 pub change_outpoint_range: OutPointRange,
100 pub value: bitcoin::Amount,
101 pub fee: bitcoin::Amount,
102 pub address: Option<Address<NetworkUnchecked>>,
103 pub outpoint: Option<bitcoin::OutPoint>,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108pub enum FinalSendOperationState {
109 Success(bitcoin::Txid),
111 Aborted,
113 Failure,
115}
116
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119pub enum FinalReceiveOperationState {
120 Success,
122 Aborted,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144pub enum ReceiveProgress {
145 Mempool { value: bitcoin::Amount },
155 Confirming {
158 value: bitcoin::Amount,
159 height: u64,
164 confirmations: u64,
167 required: u64,
169 },
170}
171
172#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct AddressReceiveProgress {
179 pub deposits: Vec<(bitcoin::OutPoint, ReceiveProgress)>,
181 pub mempool_visibility: MempoolVisibility,
201}
202
203#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct AllReceiveProgress {
209 pub deposits: Vec<(Address, bitcoin::OutPoint, ReceiveProgress)>,
212 pub mempool_visibility: MempoolVisibility,
214}
215
216#[derive(Debug, Clone)]
217pub struct WalletClientModule {
218 account_secrets: [DerivableSecret; Account::ALL.len()],
221 cfg: WalletClientConfig,
222 notifier: ModuleNotifier<WalletClientStateMachines>,
223 client_ctx: ClientContext<Self>,
224 db: Database,
225 module_api: DynModuleApi,
226}
227
228#[derive(Debug, Clone)]
229pub struct WalletClientContext {
230 pub client_ctx: ClientContext<WalletClientModule>,
231}
232
233impl Context for WalletClientContext {
234 const KIND: Option<ModuleKind> = Some(KIND);
235}
236
237#[apply(async_trait_maybe_send!)]
238impl ClientModule for WalletClientModule {
239 type Init = WalletClientInit;
240 type Common = WalletModuleTypes;
241 type Backup = NoModuleBackup;
242 type ModuleStateMachineContext = WalletClientContext;
243 type States = WalletClientStateMachines;
244
245 fn context(&self) -> Self::ModuleStateMachineContext {
246 WalletClientContext {
247 client_ctx: self.client_ctx.clone(),
248 }
249 }
250
251 fn input_fee(
252 &self,
253 amount: &Amounts,
254 _input: &<Self::Common as ModuleCommon>::Input,
255 ) -> Option<Amounts> {
256 amount
257 .get(&AmountUnit::BITCOIN)
258 .map(|a| Amounts::new_bitcoin(self.cfg.fee_consensus.fee(*a)))
259 }
260
261 fn output_fee(
262 &self,
263 amount: &Amounts,
264 _output: &<Self::Common as ModuleCommon>::Output,
265 ) -> Option<Amounts> {
266 amount
267 .get(&AmountUnit::BITCOIN)
268 .map(|a| Amounts::new_bitcoin(self.cfg.fee_consensus.fee(*a)))
269 }
270
271 #[cfg(feature = "cli")]
272 async fn handle_cli_command(
273 &self,
274 args: &[std::ffi::OsString],
275 ) -> Result<serde_json::Value, ClientModuleError> {
276 cli::handle_cli_command(self, args)
277 .await
278 .map_err(ClientModuleError::other)
279 }
280}
281
282#[derive(Debug, Clone, Default)]
283pub struct WalletClientInit;
284
285impl ModuleInit for WalletClientInit {
286 type Common = WalletCommonInit;
287
288 async fn dump_database(
289 &self,
290 _dbtx: &mut DatabaseTransaction<'_>,
291 _prefix_names: Vec<String>,
292 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
293 Box::new(BTreeMap::new().into_iter())
294 }
295}
296
297#[apply(async_trait_maybe_send!)]
298impl ClientModuleInit for WalletClientInit {
299 type Module = WalletClientModule;
300
301 fn supported_api_versions(&self) -> MultiApiVersion {
302 MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
303 .expect("no version conflicts")
304 }
305
306 fn get_database_migrations(&self) -> BTreeMap<DatabaseVersion, ClientModuleMigrationFn> {
307 let mut migrations: BTreeMap<DatabaseVersion, ClientModuleMigrationFn> = BTreeMap::new();
308
309 migrations.insert(DatabaseVersion(0), |dbtx, active, inactive| {
310 Box::pin(migrations::migrate_to_accounts_v1(dbtx, active, inactive))
311 });
312
313 migrations
314 }
315
316 async fn init(
317 &self,
318 args: &ClientModuleInitArgs<Self>,
319 ) -> Result<Self::Module, ClientModuleError> {
320 let module = WalletClientModule {
321 account_secrets: Account::ALL
322 .map(|account| args.module_root_secret().derive_account_secret(account)),
323 cfg: args.cfg().clone(),
324 notifier: args.notifier().clone(),
325 client_ctx: args.context(),
326 db: args.db().clone(),
327 module_api: args.module_api().clone(),
328 };
329
330 module.spawn_output_scanner(args.task_group(), args.client_span());
331
332 Ok(module)
333 }
334
335 fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
336 Some(db::DbKeyPrefix::iter().map(|p| p as u8).collect())
337 }
338}
339
340impl WalletClientModule {
341 pub fn get_network(&self) -> bitcoin::Network {
343 self.cfg.network
344 }
345
346 pub async fn total_value(&self) -> FederationResult<bitcoin::Amount> {
348 self.module_api
349 .federation_wallet()
350 .await
351 .map(|tx_out| tx_out.map_or(bitcoin::Amount::ZERO, |tx_out| tx_out.value))
352 }
353
354 pub async fn block_count(&self) -> FederationResult<u64> {
356 self.module_api.consensus_block_count().await
357 }
358
359 pub async fn feerate(&self) -> FederationResult<Option<u64>> {
361 self.module_api.consensus_feerate().await
362 }
363
364 pub async fn pending_tx_chain(&self) -> FederationResult<Vec<TxInfo>> {
366 self.module_api.pending_tx_chain().await
367 }
368
369 pub async fn tx_chain(&self) -> FederationResult<Vec<TxInfo>> {
371 self.module_api.tx_chain().await
372 }
373
374 pub async fn send_fee(&self) -> Result<bitcoin::Amount, SendError> {
376 self.module_api
377 .send_fee()
378 .await
379 .map_err(|e| SendError::Federation(Box::new(e)))?
380 .ok_or(SendError::NoConsensusFeerateAvailable)
381 }
382
383 pub async fn send_fee_quote(
398 &self,
399 account: Account,
400 amount: bitcoin::Amount,
401 ) -> Result<FeeQuote, TransactionSubmitError> {
402 let amount = Amount::from_sats(amount.to_sat());
403 self.client_ctx
404 .fee_quote(
405 OperationId::new_random(),
406 FeeQuoteRequest {
407 input_amount: Amounts::ZERO,
408 output_amount: Amounts::new_bitcoin(amount),
409 input_fee: Amounts::ZERO,
410 output_fee: Amounts::new_bitcoin(self.cfg.fee_consensus.fee(amount)),
411 account,
412 },
413 )
414 .await
415 }
416
417 pub async fn max_sendable_amount(
453 &self,
454 account: Account,
455 balance: Amount,
456 fee: bitcoin::Amount,
457 ) -> Result<bitcoin::Amount, SendError> {
458 let fee_msats = Amount::from_sats(fee.to_sat());
459
460 let max = max_affordable_send_amount(
461 balance,
462 Amount::from_sats(self.cfg.dust_limit.to_sat()),
463 balance,
464 |value: Amount| Amount::from_sats(value.msats.div_ceil(1000)) + fee_msats,
469 |funded: Amount| {
470 self.send_fee_quote(account, bitcoin::Amount::from_sat(funded.msats / 1000))
471 },
472 )
473 .await
474 .map_err(SendError::Failed)?
475 .ok_or(SendError::InsufficientFunds)?;
476
477 Ok(bitcoin::Amount::from_sat(max.msats.div_ceil(1000)))
480 }
481
482 pub async fn receive_fee(&self) -> Result<bitcoin::Amount, ReceiveError> {
484 self.module_api
485 .receive_fee()
486 .await
487 .map_err(|e| ReceiveError::Federation(Box::new(e)))?
488 .ok_or(ReceiveError::NoConsensusFeerateAvailable)
489 }
490
491 pub async fn send(
493 &self,
494 account: Account,
495 address: Address<NetworkUnchecked>,
496 value: bitcoin::Amount,
497 fee: Option<bitcoin::Amount>,
498 custom_meta: serde_json::Value,
499 ) -> Result<OperationId, SendError> {
500 if !self
501 .client_ctx
502 .supports_account(AmountUnit::BITCOIN, account)
503 {
504 return Err(SendError::AccountNotSupported);
505 }
506
507 if !address.is_valid_for_network(self.cfg.network) {
508 return Err(SendError::WrongNetwork);
509 }
510
511 if value < self.cfg.dust_limit {
512 return Err(SendError::DustValue);
513 }
514
515 let fee = match fee {
516 Some(value) => value,
517 None => self
518 .module_api
519 .send_fee()
520 .await
521 .map_err(|e| SendError::Federation(Box::new(e)))?
522 .ok_or(SendError::NoConsensusFeerateAvailable)?,
523 };
524
525 let operation_id = OperationId::new_random();
526
527 let destination = StandardScript::from_address(&address.clone().assume_checked())
528 .ok_or(SendError::UnsupportedAddress)?;
529
530 let client_output = ClientOutput::<WalletOutput> {
531 output: WalletOutput::V0(WalletOutputV0 {
532 destination,
533 value,
534 fee,
535 }),
536 amounts: Amounts::new_bitcoin(Amount::from_sats((value + fee).to_sat())),
537 };
538
539 let client_output_sm = ClientOutputSM::<WalletClientStateMachines> {
540 state_machines: Arc::new(move |range: OutPointRange| {
541 vec![WalletClientStateMachines::Send(SendStateMachine {
542 common: SendSMCommon {
543 operation_id,
544 outpoint: OutPoint {
545 txid: range.txid(),
546 out_idx: 0,
547 },
548 value,
549 fee,
550 },
551 state: SendSMState::Funding,
552 })]
553 }),
554 };
555
556 let client_output_bundle = self.client_ctx.make_client_outputs(ClientOutputBundle::new(
557 vec![client_output],
558 vec![client_output_sm],
559 ));
560
561 let address_clone = address.clone();
562
563 self.client_ctx
564 .finalize_and_submit_transaction_with_events(
565 operation_id,
566 WalletCommonInit::KIND.as_str(),
567 move |change_outpoint_range| {
568 WalletOperationMeta::Send(SendMeta {
569 change_outpoint_range,
570 address: address_clone.clone(),
571 value,
572 fee,
573 custom_meta: custom_meta.clone(),
574 })
575 },
576 TransactionBuilder::new(account).with_outputs(client_output_bundle),
577 vec![self.client_ctx.make_event(SendPaymentEvent {
578 operation_id,
579 address,
580 value,
581 fee,
582 account,
583 })],
584 )
585 .await
586 .map_err(|error| match error {
587 TransactionSubmitError::InsufficientFunds(_) => SendError::InsufficientFunds,
588 error => SendError::Failed(error),
589 })?;
590
591 Ok(operation_id)
592 }
593
594 pub async fn await_final_send_operation_state(
596 &self,
597 operation_id: OperationId,
598 ) -> Result<FinalSendOperationState, OperationLookupError> {
599 let operation = self.client_ctx.get_operation(operation_id).await?;
600 let mut stream = self.notifier.subscribe(operation_id).await;
601
602 let mut stream = self
603 .client_ctx
604 .outcome_or_updates(&operation, operation_id, |_| true, move || {
605 async_stream::stream! {
606 loop {
607 if let Some(WalletClientStateMachines::Send(state)) = stream.next().await {
608 match state.state {
609 SendSMState::Funding => {}
610 SendSMState::Success(txid) => {
611 yield FinalSendOperationState::Success(txid);
612 return;
613 }
614 SendSMState::Aborted(..) => {
615 yield FinalSendOperationState::Aborted;
616 return;
617 }
618 SendSMState::Failure => {
619 yield FinalSendOperationState::Failure;
620 return;
621 }
622 }
623 }
624 }
625 }
626 })
627 .into_stream();
628
629 let mut final_state = None;
630
631 while let Some(state) = stream.next().await {
632 final_state = Some(state);
633 }
634
635 Ok(final_state.expect("Stream contains one final state"))
636 }
637
638 pub async fn await_final_receive_operation_state(
640 &self,
641 operation_id: OperationId,
642 ) -> Result<FinalReceiveOperationState, OperationLookupError> {
643 let operation = self.client_ctx.get_operation(operation_id).await?;
644 let mut stream = self.notifier.subscribe(operation_id).await;
645
646 let mut stream = self
647 .client_ctx
648 .outcome_or_updates(&operation, operation_id, |_| true, move || {
649 async_stream::stream! {
650 loop {
651 if let Some(WalletClientStateMachines::Receive(state)) = stream.next().await {
652 match state.state {
653 ReceiveSMState::Funding => {}
654 ReceiveSMState::Success => {
655 yield FinalReceiveOperationState::Success;
656 return;
657 }
658 ReceiveSMState::Aborted(..) => {
659 yield FinalReceiveOperationState::Aborted;
660 return;
661 }
662 }
663 }
664 }
665 }
666 })
667 .into_stream();
668
669 let mut final_state = None;
670
671 while let Some(state) = stream.next().await {
672 final_state = Some(state);
673 }
674
675 Ok(final_state.expect("Stream contains one final state"))
676 }
677
678 async fn address_index(&self, address: &Address) -> Option<(Account, u64)> {
685 let script = address.script_pubkey();
686
687 let indices: Vec<(Account, u64)> = self
688 .db
689 .begin_transaction_nc()
690 .await
691 .find_by_prefix(&ValidAddressIndexPrefix)
692 .await
693 .map(|entry| (entry.0.0, entry.0.1))
694 .collect()
695 .await;
696
697 indices.into_iter().find(|(account, index)| {
698 self.derive_address(*account, *index).script_pubkey() == script
699 })
700 }
701
702 pub async fn receive_progress(
715 &self,
716 outpoint: bitcoin::OutPoint,
717 ) -> Result<ReceiveProgress, ReceiveProgressError> {
718 let pending = self.module_api.pending_outputs().await;
719
720 let ours = self.address_map().await;
724
725 pending
726 .outputs
727 .iter()
728 .find(|output| output.outpoint == outpoint && ours.contains_key(&output.script))
729 .map(|output| Self::pending_progress(output, pending.block_count))
730 .ok_or(ReceiveProgressError::UnknownDeposit)
731 }
732
733 pub async fn address_receive_progress(
746 &self,
747 address: &Address,
748 ) -> Result<AddressReceiveProgress, ReceiveProgressError> {
749 self.address_index(address)
750 .await
751 .ok_or(ReceiveProgressError::UnknownAddress)?;
752
753 Ok(self.deposits_paying(&address.script_pubkey()).await)
754 }
755
756 pub async fn all_receive_progress(&self) -> AllReceiveProgress {
760 let pending = self.module_api.pending_outputs().await;
761 let ours = self.address_map().await;
762
763 owned_receive_progress(&pending, &ours, |(account, index)| {
764 self.derive_address(*account, *index)
765 })
766 }
767
768 async fn deposits_paying(&self, script: &ScriptBuf) -> AddressReceiveProgress {
770 let pending = self.module_api.pending_outputs().await;
771
772 let mut deposits: Vec<(bitcoin::OutPoint, ReceiveProgress)> = pending
773 .outputs
774 .iter()
775 .filter(|output| output.script == *script)
776 .map(|output| {
777 (
778 output.outpoint,
779 Self::pending_progress(output, pending.block_count),
780 )
781 })
782 .collect();
783
784 deposits.sort_by_key(|(outpoint, _)| *outpoint);
785
786 AddressReceiveProgress {
787 deposits,
788 mempool_visibility: pending.mempool_visibility,
789 }
790 }
791
792 async fn address_map(&self) -> BTreeMap<ScriptBuf, (Account, u64)> {
795 self.db
796 .begin_transaction_nc()
797 .await
798 .find_by_prefix(&ValidAddressIndexPrefix)
799 .await
800 .map(|entry| (entry.0.0, entry.0.1))
801 .map(|(account, index)| {
802 (
803 self.derive_address(account, index).script_pubkey(),
804 (account, index),
805 )
806 })
807 .collect()
808 .await
809 }
810
811 fn pending_progress(output: &PendingOutput, block_count: Option<u64>) -> ReceiveProgress {
812 let required = BLOCK_COUNT_VOTE_DELAY + 1;
817
818 match output.height {
819 Some(height) => ReceiveProgress::Confirming {
820 value: output.value,
821 height,
822 confirmations: block_count
830 .map_or(0, |count| count.saturating_sub(height))
831 .min(required),
832 required,
833 },
834 None => ReceiveProgress::Mempool {
835 value: output.value,
836 },
837 }
838 }
839
840 async fn valid_index(&self, account: Account) -> Option<u64> {
845 self.db
846 .begin_transaction_nc()
847 .await
848 .find_by_prefix_sorted_descending(&ValidAddressIndexAccountPrefix(account))
849 .await
850 .next()
851 .await
852 .map(|entry| entry.0.1)
853 }
854
855 pub async fn receive(&self, account: Account) -> Result<Address, ReceiveError> {
871 if !self
872 .client_ctx
873 .supports_account(AmountUnit::BITCOIN, account)
874 {
875 return Err(ReceiveError::AccountNotSupported);
876 }
877
878 loop {
879 if let Some(index) = self.valid_index(account).await {
880 return Ok(self.derive_address(account, index));
881 }
882
883 sleep(Duration::from_secs(1)).await;
884 }
885 }
886
887 pub async fn await_receive(
898 &self,
899 account: Account,
900 position: EventLogId,
901 ) -> Result<(FinalReceiveOperationState, EventLogId), AwaitReceiveError> {
902 let mut position = position;
903
904 loop {
905 let (operation_id, next_position) =
906 self.next_receive_operation(account, position).await;
907
908 position = next_position;
909
910 let state = self
911 .await_final_receive_operation_state(operation_id)
912 .await?;
913
914 if state == FinalReceiveOperationState::Success {
917 let operation = self.client_ctx.get_operation(operation_id).await?;
923
924 if let WalletOperationMeta::Receive(ReceiveMeta {
925 change_outpoint_range,
926 ..
927 }) = operation.meta::<WalletOperationMeta>()
928 {
929 self.client_ctx
930 .await_primary_module_outputs(
931 operation_id,
932 change_outpoint_range.into_iter().collect(),
933 )
934 .await?;
935 }
936
937 return Ok((state, position));
938 }
939 }
940 }
941
942 async fn next_receive_operation(
950 &self,
951 account: Account,
952 position: EventLogId,
953 ) -> (OperationId, EventLogId) {
954 let mut position = position;
955
956 loop {
957 let events = self
958 .client_ctx
959 .get_event_log(Some(position), EVENT_LOG_PAGE_SIZE)
960 .await;
961
962 for entry in &events {
963 position = entry.id().saturating_add(1);
964
965 if entry.module_kind() == Some(&KIND)
966 && entry.kind == ReceivePaymentEvent::KIND
967 && let Some(event) = entry.to_event::<ReceivePaymentEvent>()
968 && event.account == account
969 {
970 return (event.operation_id, position);
971 }
972 }
973
974 if events.is_empty() {
975 sleep(Duration::from_secs(1)).await;
977 }
978 }
979 }
980
981 fn derive_address(&self, account: Account, index: u64) -> Address {
982 descriptor(
983 &self.cfg.bitcoin_pks,
984 &self
985 .derive_tweak(account, index)
986 .public_key()
987 .consensus_hash(),
988 )
989 .address(self.cfg.network)
990 }
991
992 fn derive_tweak(&self, account: Account, index: u64) -> Keypair {
993 self.account_secrets[usize::from(account.index())]
994 .child_key(ChildId(index))
995 .to_secp_key(secp256k1::SECP256K1)
996 }
997
998 async fn next_valid_index(
1006 &self,
1007 account: Account,
1008 start_index: u64,
1009 handle: &TaskHandle,
1010 ) -> Option<u64> {
1011 const SCAN_BATCH: u64 = 256;
1013
1014 let pks_hash = self.cfg.bitcoin_pks.consensus_hash();
1015
1016 let mut index = start_index;
1017
1018 while !handle.is_shutting_down() {
1019 for _ in 0..SCAN_BATCH {
1020 if is_potential_receive(
1021 &self.derive_address(account, index).script_pubkey(),
1022 &pks_hash,
1023 ) {
1024 return Some(index);
1025 }
1026
1027 index += 1;
1028 }
1029
1030 sleep(Duration::ZERO).await;
1032 }
1033
1034 None
1035 }
1036
1037 async fn receive_output(
1042 &self,
1043 account: Account,
1044 output_index: u64,
1045 value: bitcoin::Amount,
1046 address_index: u64,
1047 fee: bitcoin::Amount,
1048 outpoint: Option<bitcoin::OutPoint>,
1049 ) -> Option<(OperationId, TransactionId)> {
1050 let operation_id = OperationId::new_random();
1051
1052 let client_input = ClientInput::<WalletInput> {
1053 input: WalletInput::V0(WalletInputV0 {
1054 output_index,
1055 fee,
1056 tweak: self.derive_tweak(account, address_index).public_key(),
1057 }),
1058 keys: vec![self.derive_tweak(account, address_index)],
1059 amounts: Amounts::new_bitcoin(Amount::from_sats(value.checked_sub(fee)?.to_sat())),
1060 };
1061
1062 let client_input_sm = ClientInputSM::<WalletClientStateMachines> {
1063 state_machines: Arc::new(move |range: OutPointRange| {
1064 vec![WalletClientStateMachines::Receive(ReceiveStateMachine {
1065 common: ReceiveSMCommon {
1066 operation_id,
1067 txid: range.txid(),
1068 value,
1069 fee,
1070 },
1071 state: ReceiveSMState::Funding,
1072 })]
1073 }),
1074 };
1075
1076 let client_input_bundle = self.client_ctx.make_client_inputs(ClientInputBundle::new(
1077 vec![client_input],
1078 vec![client_input_sm],
1079 ));
1080
1081 let address = self
1082 .derive_address(account, address_index)
1083 .as_unchecked()
1084 .clone();
1085
1086 let meta_address = address.clone();
1087 let range = self
1088 .client_ctx
1089 .finalize_and_submit_transaction_with_events(
1090 operation_id,
1091 WalletCommonInit::KIND.as_str(),
1092 move |change_outpoint_range| {
1093 WalletOperationMeta::Receive(ReceiveMeta {
1094 change_outpoint_range,
1095 value,
1096 fee,
1097 address: Some(meta_address.clone()),
1098 outpoint,
1099 })
1100 },
1101 TransactionBuilder::new(account).with_inputs(client_input_bundle),
1102 vec![self.client_ctx.make_event(ReceivePaymentEvent {
1103 operation_id,
1104 value,
1105 fee,
1106 address,
1107 outpoint,
1108 account,
1109 })],
1110 )
1111 .await
1112 .ok()?;
1113
1114 Some((operation_id, range.txid()))
1115 }
1116
1117 fn spawn_output_scanner(&self, task_group: &TaskGroup, client_span: &tracing::Span) {
1118 let module = self.clone();
1119 let handle = task_group.make_handle();
1120
1121 task_group.spawn_cancellable_with_span(client_span.clone(), "output-scanner", async move {
1122 for account in Account::ALL {
1135 let address_index_exists = {
1136 let mut dbtx = module.db.begin_transaction().await;
1137 dbtx.find_by_prefix(&ValidAddressIndexAccountPrefix(account))
1138 .await
1139 .next()
1140 .await
1141 .is_some()
1142 };
1143
1144 if address_index_exists {
1145 continue;
1146 }
1147
1148 let Some(index) = module.next_valid_index(account, 0, &handle).await else {
1149 return;
1150 };
1151
1152 let mut dbtx = module.db.begin_transaction().await;
1153 dbtx.insert_new_entry(&ValidAddressIndexKey(account, index), &())
1154 .await;
1155 dbtx.commit_tx().await;
1156 }
1157
1158 loop {
1159 match module.check_outputs(&handle).await {
1160 Ok(skip_wait) => {
1161 if skip_wait {
1162 continue;
1163 }
1164 }
1165 Err(e) => {
1166 warn!(target: LOG_CLIENT_MODULE_WALLETV2, "Failed to fetch outputs: {e}");
1167 }
1168 }
1169
1170 sleep(fedimint_walletv2_common::sleep_duration()).await;
1171 }
1172 });
1173 }
1174
1175 async fn check_outputs(&self, handle: &TaskHandle) -> Result<bool, CheckOutputsError> {
1176 let mut dbtx = self.db.begin_transaction_nc().await;
1177
1178 let next_output_index = dbtx.get_value(&NextOutputIndexKey).await.unwrap_or(0);
1179
1180 let valid_indices: Vec<(Account, u64)> = dbtx
1183 .find_by_prefix(&ValidAddressIndexPrefix)
1184 .await
1185 .map(|entry| (entry.0.0, entry.0.1))
1186 .collect()
1187 .await;
1188
1189 let mut address_map: BTreeMap<ScriptBuf, (Account, u64)> = valid_indices
1190 .iter()
1191 .map(|&(account, i)| {
1192 (
1193 self.derive_address(account, i).script_pubkey(),
1194 (account, i),
1195 )
1196 })
1197 .collect();
1198
1199 let mut frontier: BTreeMap<Account, u64> = BTreeMap::new();
1202
1203 for &(account, i) in &valid_indices {
1204 frontier
1205 .entry(account)
1206 .and_modify(|highest| *highest = (*highest).max(i))
1207 .or_insert(i);
1208 }
1209
1210 let outputs = self
1211 .module_api
1212 .output_info_slice(next_output_index, next_output_index + SLICE_SIZE)
1213 .await?;
1214
1215 let returned_num = outputs.len();
1216 let mut matched_num: usize = 0;
1217
1218 for output in &outputs {
1219 if let Some(&(account, address_index)) = address_map.get(&output.script) {
1220 matched_num += 1;
1221
1222 if !output.spent
1227 && !self
1228 .process_unspent_output(account, output, address_index)
1229 .await?
1230 {
1231 return Ok(false);
1232 }
1233
1234 let next_address_index = *frontier
1235 .get(&account)
1236 .expect("every account in the map has a frontier");
1237
1238 if address_index == next_address_index {
1240 let Some(index) = self
1241 .next_valid_index(account, next_address_index + 1, handle)
1242 .await
1243 else {
1244 return Ok(false);
1245 };
1246
1247 let mut dbtx = self.db.begin_transaction().await;
1248
1249 dbtx.insert_entry(&ValidAddressIndexKey(account, index), &())
1250 .await;
1251
1252 dbtx.commit_tx_result().await?;
1253
1254 frontier.insert(account, index);
1255
1256 address_map.insert(
1257 self.derive_address(account, index).script_pubkey(),
1258 (account, index),
1259 );
1260 }
1261 }
1262
1263 let mut dbtx = self.db.begin_transaction().await;
1264
1265 dbtx.insert_entry(&NextOutputIndexKey, &(output.index + 1))
1266 .await;
1267
1268 dbtx.commit_tx_result().await?;
1269 }
1270
1271 debug!(
1272 target: LOG_CLIENT_MODULE_WALLETV2,
1273 next_output_index,
1274 returned_num,
1275 matched_num,
1276 valid_indices_num = valid_indices.len(),
1277 "Scanning for outputs"
1278 );
1279
1280 Ok(!outputs.is_empty())
1281 }
1282
1283 async fn process_unspent_output(
1284 &self,
1285 account: Account,
1286 output: &OutputInfo,
1287 address_index: u64,
1288 ) -> Result<bool, ProcessOutputError> {
1289 debug!(
1290 target: LOG_CLIENT_MODULE_WALLETV2,
1291 output_index = output.index,
1292 value_sat = output.value.to_sat(),
1293 address_index,
1294 outpoint = ?output.outpoint,
1295 "Discovered unspent walletv2 receive output"
1296 );
1297
1298 let pending_tx_chain_len = self.module_api.pending_tx_chain().await?.len();
1301 if 3 <= pending_tx_chain_len {
1302 debug!(
1303 target: LOG_CLIENT_MODULE_WALLETV2,
1304 output_index = output.index,
1305 pending_tx_chain_len,
1306 "Delaying walletv2 receive claim because pending transaction chain is full"
1307 );
1308 return Ok(false);
1309 }
1310
1311 let receive_fee = self
1312 .module_api
1313 .receive_fee()
1314 .await?
1315 .ok_or(ProcessOutputError::NoFeerate)?;
1316
1317 if let Some((operation_id, txid)) = self
1318 .receive_output(
1319 account,
1320 output.index,
1321 output.value,
1322 address_index,
1323 receive_fee,
1324 output.outpoint,
1325 )
1326 .await
1327 {
1328 debug!(
1329 target: LOG_CLIENT_MODULE_WALLETV2,
1330 output_index = output.index,
1331 ?operation_id,
1332 %txid,
1333 "Waiting for walletv2 receive claim acceptance"
1334 );
1335 self.client_ctx
1336 .transaction_updates(operation_id)
1337 .await
1338 .await_tx_accepted(txid)
1339 .await
1340 .map_err(ProcessOutputError::ClaimRejected)?;
1341 debug!(
1342 target: LOG_CLIENT_MODULE_WALLETV2,
1343 output_index = output.index,
1344 ?operation_id,
1345 %txid,
1346 "Walletv2 receive claim accepted"
1347 );
1348 } else {
1349 debug!(
1350 target: LOG_CLIENT_MODULE_WALLETV2,
1351 output_index = output.index,
1352 value_sat = output.value.to_sat(),
1353 fee_sat = receive_fee.to_sat(),
1354 "Skipping walletv2 receive claim; value cannot cover the claim fees"
1355 );
1356 }
1357
1358 Ok(true)
1359 }
1360}
1361
1362#[derive(Error, Debug)]
1364#[non_exhaustive]
1365pub enum SendError {
1366 #[error("The primary module only holds a balance for the primary account")]
1367 AccountNotSupported,
1368 #[error("Address is from a different network than the federation")]
1370 WrongNetwork,
1371
1372 #[error("The value is too small")]
1374 DustValue,
1375
1376 #[error("The federation returned an error")]
1378 Federation(#[source] Box<FederationError>),
1379
1380 #[error("No consensus feerate is available at this time")]
1383 NoConsensusFeerateAvailable,
1384
1385 #[error("The client does not have sufficient funds to send the payment")]
1387 InsufficientFunds,
1388
1389 #[error("Unsupported address type")]
1391 UnsupportedAddress,
1392
1393 #[error("The send transaction could not be submitted")]
1396 Failed(#[source] TransactionSubmitError),
1397}
1398
1399#[derive(Error, Debug)]
1401#[non_exhaustive]
1402pub enum ReceiveError {
1403 #[error("The primary module only holds a balance for the primary account")]
1404 AccountNotSupported,
1405 #[error("The federation returned an error")]
1407 Federation(#[source] Box<FederationError>),
1408
1409 #[error("No consensus feerate is available at this time")]
1412 NoConsensusFeerateAvailable,
1413}
1414
1415#[derive(Debug, Error)]
1417#[non_exhaustive]
1418pub enum AwaitReceiveError {
1419 #[error("The receive operation could not be looked up")]
1421 Operation(#[from] OperationLookupError),
1422
1423 #[error("The ecash for the claimed deposit could not be issued")]
1425 Issuance(#[from] TransactionSubmitError),
1426}
1427
1428fn owned_receive_progress<A>(
1431 pending: &PendingOutputs,
1432 ours: &BTreeMap<ScriptBuf, A>,
1433 address: impl Fn(&A) -> Address,
1434) -> AllReceiveProgress {
1435 let mut deposits: Vec<_> = pending
1436 .outputs
1437 .iter()
1438 .filter_map(|output| {
1439 Some((
1440 address(ours.get(&output.script)?),
1441 output.outpoint,
1442 WalletClientModule::pending_progress(output, pending.block_count),
1443 ))
1444 })
1445 .collect();
1446
1447 deposits.sort_by_key(|(_, outpoint, _)| *outpoint);
1448
1449 AllReceiveProgress {
1450 deposits,
1451 mempool_visibility: pending.mempool_visibility,
1452 }
1453}
1454
1455#[derive(Debug, Error)]
1457#[non_exhaustive]
1458pub enum ReceiveProgressError {
1459 #[error("No deposit of ours at this outpoint")]
1463 UnknownDeposit,
1464
1465 #[error("Address was not derived by this client")]
1467 UnknownAddress,
1468}
1469
1470#[derive(Debug, Error)]
1473enum CheckOutputsError {
1474 #[error(transparent)]
1476 Federation(#[from] FederationError),
1477
1478 #[error(transparent)]
1480 Database(#[from] DatabaseError),
1481
1482 #[error(transparent)]
1484 ProcessOutput(#[from] ProcessOutputError),
1485}
1486
1487#[derive(Debug, Error)]
1489enum ProcessOutputError {
1490 #[error(transparent)]
1493 Federation(#[from] FederationError),
1494
1495 #[error("No consensus feerate is available")]
1497 NoFeerate,
1498
1499 #[error("Claim transaction was rejected: {0}")]
1501 ClaimRejected(String),
1502}
1503
1504#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1505pub enum WalletClientStateMachines {
1506 Send(send_sm::SendStateMachine),
1507 Receive(receive_sm::ReceiveStateMachine),
1508}
1509
1510impl State for WalletClientStateMachines {
1511 type ModuleContext = WalletClientContext;
1512
1513 fn transitions(
1514 &self,
1515 context: &Self::ModuleContext,
1516 global_context: &DynGlobalClientContext,
1517 ) -> Vec<StateTransition<Self>> {
1518 match self {
1519 WalletClientStateMachines::Send(sm) => sm_enum_variant_translation!(
1520 sm.transitions(context, global_context),
1521 WalletClientStateMachines::Send
1522 ),
1523 WalletClientStateMachines::Receive(sm) => sm_enum_variant_translation!(
1524 sm.transitions(context, global_context),
1525 WalletClientStateMachines::Receive
1526 ),
1527 }
1528 }
1529
1530 fn operation_id(&self) -> OperationId {
1531 match self {
1532 WalletClientStateMachines::Send(sm) => sm.operation_id(),
1533 WalletClientStateMachines::Receive(sm) => sm.operation_id(),
1534 }
1535 }
1536}
1537
1538impl IntoDynInstance for WalletClientStateMachines {
1539 type DynType = DynState;
1540
1541 fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
1542 DynState::from_typed(instance_id, self)
1543 }
1544}
1545
1546#[cfg(test)]
1547mod tests;