1pub extern crate ark;
287
288pub extern crate bip39;
289pub extern crate lightning_invoice;
290pub extern crate lnurl as lnurllib;
291
292#[macro_use] extern crate anyhow;
293#[macro_use] extern crate async_trait;
294#[macro_use] extern crate serde;
295
296pub mod chain;
297pub mod exit;
298pub mod movement;
299pub mod onchain;
300pub mod persist;
301pub mod round;
302pub mod subsystem;
303pub mod vtxo;
304
305#[cfg(feature = "pid-lock")]
306pub mod pid_lock;
307
308mod arkoor;
309mod board;
310mod config;
311mod daemon;
312mod fees;
313mod lightning;
314mod mailbox;
315mod notification;
316mod offboard;
317#[cfg(feature = "socks5-proxy")]
318mod proxy;
319mod psbtext;
320mod utils;
321
322pub use self::arkoor::ArkoorCreateResult;
323pub use self::config::{BarkNetwork, Config};
324pub use self::daemon::DaemonHandle;
325pub use self::fees::FeeEstimate;
326pub use self::notification::{WalletNotification, NotificationStream};
327pub use self::vtxo::WalletVtxo;
328
329use std::collections::HashSet;
330use std::sync::Arc;
331
332use anyhow::{bail, Context};
333use bip39::Mnemonic;
334use bitcoin::{Amount, Network, OutPoint};
335use bitcoin::bip32::{self, ChildNumber, Fingerprint};
336use bitcoin::secp256k1::{self, Keypair, PublicKey};
337use log::{trace, info, warn, error};
338use tokio::sync::{Mutex, RwLock};
339
340use ark::lightning::PaymentHash;
341
342use ark::{ArkInfo, ProtocolEncoding, Vtxo, VtxoId, VtxoPolicy, VtxoRequest};
343use ark::address::VtxoDelivery;
344use ark::fees::{validate_and_subtract_fee_min_dust, VtxoFeeInfo};
345use ark::vtxo::{Full, PubkeyVtxoPolicy, VtxoRef};
346use ark::vtxo::policy::signing::VtxoSigner;
347use bitcoin_ext::{BlockHeight, P2TR_DUST, TxStatus};
348use server_rpc::{protos, ServerConnection};
349
350use crate::chain::{ChainSource, ChainSourceSpec};
351use crate::exit::Exit;
352use crate::movement::{Movement, MovementStatus, PaymentMethod};
353use crate::movement::manager::MovementManager;
354use crate::movement::update::MovementUpdate;
355use crate::notification::NotificationDispatch;
356use crate::onchain::{ExitUnilaterally, PreparePsbt, SignPsbt, Utxo};
357use crate::onchain::DaemonizableOnchainWallet;
358use crate::persist::BarkPersister;
359use crate::persist::models::{PendingOffboard, RoundStateId, StoredRoundState, Unlocked};
360#[cfg(feature = "socks5-proxy")]
361use crate::proxy::proxy_for_url;
362use crate::round::{RoundParticipation, RoundStateLockIndex, RoundStatus};
363use crate::subsystem::{ArkoorMovement, RoundMovement};
364use crate::vtxo::{FilterVtxos, RefreshStrategy, VtxoFilter, VtxoState, VtxoStateKind};
365
366#[cfg(all(feature = "wasm-web", feature = "socks5-proxy"))]
367compile_error!("features `wasm-web` does not support feature `socks5-proxy");
368
369const BARK_PURPOSE_INDEX: u32 = 350;
371const VTXO_KEYS_INDEX: u32 = 0;
373const MAILBOX_KEY_INDEX: u32 = 1;
375const RECOVERY_MAILBOX_KEY_INDEX: u32 = 2;
377
378lazy_static::lazy_static! {
379 static ref SECP: secp256k1::Secp256k1<secp256k1::All> = secp256k1::Secp256k1::new();
381}
382
383fn log_server_pubkey_changed_error(expected: PublicKey, got: PublicKey) {
388 error!(
389 "
390Server public key has changed!
391
392The Ark server's public key is different from the one stored when this
393wallet was created. This typically happens when:
394
395 - The server operator has rotated their keys
396 - You are connecting to a different server
397 - The server has been replaced
398
399For safety, this wallet will not connect to the server until you
400resolve this. You can recover your funds on-chain by doing an emergency exit.
401
402This will exit your VTXOs to on-chain Bitcoin without needing the server's cooperation.
403
404Expected: {expected}
405Got: {got}")
406}
407
408#[derive(Debug, Clone)]
410pub struct LightningReceiveBalance {
411 pub total: Amount,
413 pub claimable: Amount,
415}
416
417#[derive(Debug, Clone)]
419pub struct Balance {
420 pub spendable: Amount,
422 pub pending_lightning_send: Amount,
424 pub claimable_lightning_receive: Amount,
426 pub pending_in_round: Amount,
428 pub pending_exit: Option<Amount>,
431 pub pending_board: Amount,
433}
434
435pub struct UtxoInfo {
436 pub outpoint: OutPoint,
437 pub amount: Amount,
438 pub confirmation_height: Option<u32>,
439}
440
441impl From<Utxo> for UtxoInfo {
442 fn from(value: Utxo) -> Self {
443 match value {
444 Utxo::Local(o) => UtxoInfo {
445 outpoint: o.outpoint,
446 amount: o.amount,
447 confirmation_height: o.confirmation_height,
448 },
449 Utxo::Exit(e) => UtxoInfo {
450 outpoint: e.vtxo.point(),
451 amount: e.vtxo.amount(),
452 confirmation_height: Some(e.height),
453 },
454 }
455 }
456}
457
458pub struct OffchainBalance {
461 pub available: Amount,
463 pub pending_in_round: Amount,
465 pub pending_exit: Amount,
468}
469
470#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
472pub struct WalletProperties {
473 pub network: Network,
477
478 pub fingerprint: Fingerprint,
482
483 pub server_pubkey: Option<PublicKey>,
490}
491
492pub struct WalletSeed {
498 master: bip32::Xpriv,
499 vtxo: bip32::Xpriv,
500}
501
502impl WalletSeed {
503 fn new(network: Network, seed: &[u8; 64]) -> Self {
504 let bark_path = [ChildNumber::from_hardened_idx(BARK_PURPOSE_INDEX).unwrap()];
505 let master = bip32::Xpriv::new_master(network, seed)
506 .expect("invalid seed")
507 .derive_priv(&SECP, &bark_path)
508 .expect("purpose is valid");
509
510 let vtxo_path = [ChildNumber::from_hardened_idx(VTXO_KEYS_INDEX).unwrap()];
511 let vtxo = master.derive_priv(&SECP, &vtxo_path)
512 .expect("vtxo path is valid");
513
514 Self { master, vtxo }
515 }
516
517 fn fingerprint(&self) -> Fingerprint {
518 self.master.fingerprint(&SECP)
519 }
520
521 fn derive_vtxo_keypair(&self, idx: u32) -> Keypair {
522 self.vtxo.derive_priv(&SECP, &[idx.into()]).unwrap().to_keypair(&SECP)
523 }
524
525 fn to_mailbox_keypair(&self) -> Keypair {
526 let mailbox_path = [ChildNumber::from_hardened_idx(MAILBOX_KEY_INDEX).unwrap()];
527 self.master.derive_priv(&SECP, &mailbox_path).unwrap().to_keypair(&SECP)
528 }
529
530 fn to_recovery_mailbox_keypair(&self) -> Keypair {
531 let mailbox_path = [ChildNumber::from_hardened_idx(RECOVERY_MAILBOX_KEY_INDEX).unwrap()];
532 self.master.derive_priv(&SECP, &mailbox_path).unwrap().to_keypair(&SECP)
533 }
534}
535
536pub struct Wallet {
669 pub chain: Arc<ChainSource>,
671
672 pub exit: RwLock<Exit>,
674
675 pub movements: Arc<MovementManager>,
677
678 notifications: NotificationDispatch,
680
681 config: Config,
683
684 db: Arc<dyn BarkPersister>,
686
687 seed: WalletSeed,
689
690 server: parking_lot::RwLock<Option<ServerConnection>>,
692
693 inflight_lightning_payments: Mutex<HashSet<PaymentHash>>,
696
697 round_state_lock_index: RoundStateLockIndex,
699}
700
701impl Wallet {
702 pub fn chain_source(
705 config: &Config,
706 ) -> anyhow::Result<ChainSourceSpec> {
707 if let Some(ref url) = config.esplora_address {
708 Ok(ChainSourceSpec::Esplora {
709 url: url.clone(),
710 })
711 } else if let Some(ref url) = config.bitcoind_address {
712 let auth = if let Some(ref c) = config.bitcoind_cookiefile {
713 bitcoin_ext::rpc::Auth::CookieFile(c.clone())
714 } else {
715 bitcoin_ext::rpc::Auth::UserPass(
716 config.bitcoind_user.clone().context("need bitcoind auth config")?,
717 config.bitcoind_pass.clone().context("need bitcoind auth config")?,
718 )
719 };
720 Ok(ChainSourceSpec::Bitcoind {
721 url: url.clone(),
722 auth,
723 })
724 } else {
725 bail!("Need to either provide esplora or bitcoind info");
726 }
727 }
728
729 pub fn require_chainsource_version(&self) -> anyhow::Result<()> {
733 self.chain.require_version()
734 }
735
736 pub async fn network(&self) -> anyhow::Result<Network> {
737 Ok(self.properties().await?.network)
738 }
739
740 pub async fn peek_next_keypair(&self) -> anyhow::Result<(Keypair, u32)> {
743 let last_revealed = self.db.get_last_vtxo_key_index().await?;
744
745 let index = last_revealed.map(|i| i + 1).unwrap_or(u32::MIN);
746 let keypair = self.seed.derive_vtxo_keypair(index);
747
748 Ok((keypair, index))
749 }
750
751 pub async fn derive_store_next_keypair(&self) -> anyhow::Result<(Keypair, u32)> {
754 let (keypair, index) = self.peek_next_keypair().await?;
755 self.db.store_vtxo_key(index, keypair.public_key()).await?;
756 Ok((keypair, index))
757 }
758
759 #[deprecated(note = "use peek_keypair instead")]
760 pub async fn peak_keypair(&self, index: u32) -> anyhow::Result<Keypair> {
761 self.peek_keypair(index).await
762 }
763
764 pub async fn peek_keypair(&self, index: u32) -> anyhow::Result<Keypair> {
778 let keypair = self.seed.derive_vtxo_keypair(index);
779 if self.db.get_public_key_idx(&keypair.public_key()).await?.is_some() {
780 Ok(keypair)
781 } else {
782 bail!("VTXO key {} does not exist, please derive it first", index)
783 }
784 }
785
786
787 pub async fn pubkey_keypair(&self, public_key: &PublicKey) -> anyhow::Result<Option<(u32, Keypair)>> {
799 if let Some(index) = self.db.get_public_key_idx(&public_key).await? {
800 Ok(Some((index, self.seed.derive_vtxo_keypair(index))))
801 } else {
802 Ok(None)
803 }
804 }
805
806 pub async fn get_vtxo_key(&self, vtxo: impl VtxoRef) -> anyhow::Result<Keypair> {
817 let wallet_vtxo = self.get_vtxo_by_id(vtxo.vtxo_id()).await?;
818 let pubkey = self.find_signable_clause(&wallet_vtxo.vtxo).await
819 .context("VTXO is not signable by wallet")?
820 .pubkey();
821 let idx = self.db.get_public_key_idx(&pubkey).await?
822 .context("VTXO key not found")?;
823 Ok(self.seed.derive_vtxo_keypair(idx))
824 }
825
826 #[deprecated(note = "use peek_address instead")]
827 pub async fn peak_address(&self, index: u32) -> anyhow::Result<ark::Address> {
828 self.peek_address(index).await
829 }
830
831 pub async fn peek_address(&self, index: u32) -> anyhow::Result<ark::Address> {
835 let (_, ark_info) = &self.require_server().await?;
836 let network = self.properties().await?.network;
837 let keypair = self.peek_keypair(index).await?;
838 let mailbox = self.mailbox_identifier();
839
840 Ok(ark::Address::builder()
841 .testnet(network != bitcoin::Network::Bitcoin)
842 .server_pubkey(ark_info.server_pubkey)
843 .pubkey_policy(keypair.public_key())
844 .mailbox(ark_info.mailbox_pubkey, mailbox, &keypair)
845 .expect("Failed to assign mailbox")
846 .into_address().unwrap())
847 }
848
849 pub async fn new_address_with_index(&self) -> anyhow::Result<(ark::Address, u32)> {
853 let (_, index) = self.derive_store_next_keypair().await?;
854 let addr = self.peek_address(index).await?;
855 Ok((addr, index))
856 }
857
858 pub async fn new_address(&self) -> anyhow::Result<ark::Address> {
860 let (addr, _) = self.new_address_with_index().await?;
861 Ok(addr)
862 }
863
864 pub async fn create(
870 mnemonic: &Mnemonic,
871 network: Network,
872 config: Config,
873 db: Arc<dyn BarkPersister>,
874 force: bool,
875 ) -> anyhow::Result<Wallet> {
876 trace!("Config: {:?}", config);
877 if let Some(existing) = db.read_properties().await? {
878 trace!("Existing config: {:?}", existing);
879 bail!("cannot overwrite already existing config")
880 }
881
882 let server_pubkey = if !force {
884 match Self::connect_to_server(&config, network).await {
885 Ok(conn) => {
886 let ark_info = conn.ark_info().await?;
887 Some(ark_info.server_pubkey)
888 }
889 Err(err) => {
890 bail!("Failed to connect to provided server (if you are sure use the --force flag): {:#}", err);
891 }
892 }
893 } else {
894 None
895 };
896
897 let wallet_fingerprint = WalletSeed::new(network, &mnemonic.to_seed("")).fingerprint();
898 let properties = WalletProperties {
899 network,
900 fingerprint: wallet_fingerprint,
901 server_pubkey,
902 };
903
904 db.init_wallet(&properties).await.context("cannot init wallet in the database")?;
906 info!("Created wallet with fingerprint: {}", wallet_fingerprint);
907 if let Some(pk) = server_pubkey {
908 info!("Stored server pubkey: {}", pk);
909 }
910
911 let wallet = Wallet::open(&mnemonic, db, config).await.context("failed to open wallet")?;
913 wallet.require_chainsource_version()?;
914
915 Ok(wallet)
916 }
917
918 pub async fn create_with_onchain(
926 mnemonic: &Mnemonic,
927 network: Network,
928 config: Config,
929 db: Arc<dyn BarkPersister>,
930 onchain: &dyn ExitUnilaterally,
931 force: bool,
932 ) -> anyhow::Result<Wallet> {
933 let mut wallet = Wallet::create(mnemonic, network, config, db, force).await?;
934 wallet.exit.get_mut().load(onchain).await?;
935 Ok(wallet)
936 }
937
938 pub async fn open(
940 mnemonic: &Mnemonic,
941 db: Arc<dyn BarkPersister>,
942 config: Config,
943 ) -> anyhow::Result<Wallet> {
944 let properties = db.read_properties().await?.context("Wallet is not initialised")?;
945
946 let seed = {
947 let seed = mnemonic.to_seed("");
948 WalletSeed::new(properties.network, &seed)
949 };
950
951 if properties.fingerprint != seed.fingerprint() {
952 bail!("incorrect mnemonic")
953 }
954
955 let chain_source = if let Some(ref url) = config.esplora_address {
956 ChainSourceSpec::Esplora {
957 url: url.clone(),
958 }
959 } else if let Some(ref url) = config.bitcoind_address {
960 let auth = if let Some(ref c) = config.bitcoind_cookiefile {
961 bitcoin_ext::rpc::Auth::CookieFile(c.clone())
962 } else {
963 bitcoin_ext::rpc::Auth::UserPass(
964 config.bitcoind_user.clone().context("need bitcoind auth config")?,
965 config.bitcoind_pass.clone().context("need bitcoind auth config")?,
966 )
967 };
968 ChainSourceSpec::Bitcoind { url: url.clone(), auth }
969 } else {
970 bail!("Need to either provide esplora or bitcoind info");
971 };
972
973 #[cfg(feature = "socks5-proxy")]
974 let chain_proxy = proxy_for_url(&config.socks5_proxy, chain_source.url())?;
975 let chain_source_client = ChainSource::new(
976 chain_source, properties.network, config.fallback_fee_rate,
977 #[cfg(feature = "socks5-proxy")] chain_proxy.as_deref(),
978 ).await?;
979 let chain = Arc::new(chain_source_client);
980
981 let server = match Self::connect_to_server(&config, properties.network).await {
982 Ok(s) => Some(s),
983 Err(e) => {
984 warn!("Ark server handshake failed: {:#}", e);
985 None
986 }
987 };
988 let server = parking_lot::RwLock::new(server);
989
990 let notifications = NotificationDispatch::new();
991 let movements = Arc::new(MovementManager::new(db.clone(), notifications.clone()));
992 let exit = RwLock::new(Exit::new(db.clone(), chain.clone(), movements.clone()).await?);
993
994 Ok(Wallet {
995 config, db, seed, exit, movements, notifications, server, chain,
996 inflight_lightning_payments: Mutex::new(HashSet::new()),
997 round_state_lock_index: RoundStateLockIndex::new(),
998 })
999 }
1000
1001 pub async fn open_with_onchain(
1004 mnemonic: &Mnemonic,
1005 db: Arc<dyn BarkPersister>,
1006 onchain: &dyn ExitUnilaterally,
1007 cfg: Config,
1008 ) -> anyhow::Result<Wallet> {
1009 let mut wallet = Wallet::open(mnemonic, db, cfg).await?;
1010 wallet.exit.get_mut().load(onchain).await?;
1011 Ok(wallet)
1012 }
1013
1014 pub fn config(&self) -> &Config {
1016 &self.config
1017 }
1018
1019 pub async fn properties(&self) -> anyhow::Result<WalletProperties> {
1021 let properties = self.db.read_properties().await?.context("Wallet is not initialised")?;
1022 Ok(properties)
1023 }
1024
1025 pub fn fingerprint(&self) -> Fingerprint {
1027 self.seed.fingerprint()
1028 }
1029
1030 async fn connect_to_server(
1031 config: &Config,
1032 network: Network,
1033 ) -> anyhow::Result<ServerConnection> {
1034 let address = &config.server_address;
1035 #[cfg(feature = "socks5-proxy")]
1036 if let Some(proxy) = proxy_for_url(&config.socks5_proxy, address)? {
1037 return ServerConnection::connect_via_proxy(address, network, &proxy).await
1038 .context("Failed to connect Ark server via proxy");
1039 }
1040 ServerConnection::connect(address, network).await
1041 .context("Failed to connect to Ark server")
1042 }
1043
1044 async fn require_server(&self) -> anyhow::Result<(ServerConnection, ArkInfo)> {
1045 let conn = self.server.read().clone()
1046 .context("You should be connected to Ark server to perform this action")?;
1047 let ark_info = conn.ark_info().await?;
1048
1049 if let Some(stored_pubkey) = self.properties().await?.server_pubkey {
1051 if stored_pubkey != ark_info.server_pubkey {
1052 log_server_pubkey_changed_error(stored_pubkey, ark_info.server_pubkey);
1053 bail!("Server public key has changed. You should exit all your VTXOs!");
1054 }
1055 } else {
1056 self.db.set_server_pubkey(ark_info.server_pubkey).await?;
1058 info!("Stored server pubkey for existing wallet: {}", ark_info.server_pubkey);
1059 }
1060
1061 Ok((conn, ark_info))
1062 }
1063
1064 pub async fn refresh_server(&self) -> anyhow::Result<()> {
1065 let server = self.server.read().clone();
1066 let properties = self.properties().await?;
1067
1068 let srv = if let Some(srv) = server {
1069 srv.check_connection().await?;
1070 let ark_info = srv.ark_info().await?;
1071 ark_info.fees.validate().context("invalid fee schedule")?;
1072
1073 if let Some(stored_pubkey) = properties.server_pubkey {
1075 if stored_pubkey != ark_info.server_pubkey {
1076 log_server_pubkey_changed_error(stored_pubkey, ark_info.server_pubkey);
1077 bail!("Server public key has changed. You should exit all your VTXOs!");
1078 }
1079 } else {
1080 self.db.set_server_pubkey(ark_info.server_pubkey).await?;
1082 info!("Stored server pubkey for existing wallet: {}", ark_info.server_pubkey);
1083 }
1084
1085 srv
1086 } else {
1087 let conn = Self::connect_to_server(&self.config, properties.network).await?;
1088 let ark_info = conn.ark_info().await?;
1089 ark_info.fees.validate().context("invalid fee schedule")?;
1090
1091 if let Some(stored_pubkey) = properties.server_pubkey {
1093 if stored_pubkey != ark_info.server_pubkey {
1094 log_server_pubkey_changed_error(stored_pubkey, ark_info.server_pubkey);
1095 bail!("Server public key has changed. You should exit all your VTXOs!");
1096 }
1097 } else {
1098 self.db.set_server_pubkey(ark_info.server_pubkey).await?;
1100 info!("Stored server pubkey for existing wallet: {}", ark_info.server_pubkey);
1101 }
1102
1103 conn
1104 };
1105
1106 let _ = self.server.write().insert(srv);
1107
1108 Ok(())
1109 }
1110
1111 pub async fn ark_info(&self) -> anyhow::Result<Option<ArkInfo>> {
1113 let server = self.server.read().clone();
1114 match server.as_ref() {
1115 Some(srv) => Ok(Some(srv.ark_info().await?)),
1116 _ => Ok(None),
1117 }
1118 }
1119
1120 pub async fn balance(&self) -> anyhow::Result<Balance> {
1124 let vtxos = self.vtxos().await?;
1125
1126 let spendable = {
1127 let mut v = vtxos.iter().collect();
1128 VtxoStateKind::Spendable.filter_vtxos(&mut v).await?;
1129 v.into_iter().map(|v| v.amount()).sum::<Amount>()
1130 };
1131
1132 let pending_lightning_send = self.pending_lightning_send_vtxos().await?.iter()
1133 .map(|v| v.amount())
1134 .sum::<Amount>();
1135
1136 let claimable_lightning_receive = self.claimable_lightning_receive_balance().await?;
1137
1138 let pending_board = self.pending_board_vtxos().await?.iter()
1139 .map(|v| v.amount())
1140 .sum::<Amount>();
1141
1142 let pending_in_round = self.pending_round_balance().await?;
1143
1144 let pending_exit = self.exit.try_read().ok().map(|e| e.pending_total());
1145
1146 Ok(Balance {
1147 spendable,
1148 pending_in_round,
1149 pending_lightning_send,
1150 claimable_lightning_receive,
1151 pending_exit,
1152 pending_board,
1153 })
1154 }
1155
1156 pub async fn validate_vtxo(&self, vtxo: &Vtxo<Full>) -> anyhow::Result<()> {
1158 let tx = self.chain.get_tx(&vtxo.chain_anchor().txid).await
1159 .context("could not fetch chain tx")?;
1160
1161 let tx = tx.with_context(|| {
1162 format!("vtxo chain anchor not found for vtxo: {}", vtxo.chain_anchor().txid)
1163 })?;
1164
1165 vtxo.validate(&tx)?;
1166
1167 Ok(())
1168 }
1169
1170 pub async fn import_vtxo(&self, vtxo: &Vtxo<Full>) -> anyhow::Result<()> {
1180 if self.db.get_wallet_vtxo(vtxo.id()).await?.is_some() {
1181 info!("VTXO {} already exists in wallet, skipping import", vtxo.id());
1182 return Ok(());
1183 }
1184
1185 self.validate_vtxo(vtxo).await.context("VTXO validation failed")?;
1186
1187 if self.find_signable_clause(vtxo).await.is_none() {
1188 bail!("VTXO {} is not owned by this wallet (no signable clause found)", vtxo.id());
1189 }
1190
1191 let current_height = self.chain.tip().await?;
1192 if vtxo.expiry_height() <= current_height {
1193 bail!("Vtxo {} has expired", vtxo.id());
1194 }
1195
1196 self.store_spendable_vtxos([vtxo]).await.context("failed to store imported VTXO")?;
1197
1198 info!("Successfully imported VTXO {}", vtxo.id());
1199 Ok(())
1200 }
1201
1202 pub async fn get_vtxo_by_id(&self, vtxo_id: VtxoId) -> anyhow::Result<WalletVtxo> {
1204 let vtxo = self.db.get_wallet_vtxo(vtxo_id).await
1205 .with_context(|| format!("Error when querying vtxo {} in database", vtxo_id))?
1206 .with_context(|| format!("The VTXO with id {} cannot be found", vtxo_id))?;
1207 Ok(vtxo)
1208 }
1209
1210 #[deprecated(since="0.1.0-beta.5", note = "Use Wallet::history instead")]
1212 pub async fn movements(&self) -> anyhow::Result<Vec<Movement>> {
1213 self.history().await
1214 }
1215
1216 pub async fn history(&self) -> anyhow::Result<Vec<Movement>> {
1218 Ok(self.db.get_all_movements().await?)
1219 }
1220
1221 pub async fn history_by_payment_method(
1223 &self,
1224 payment_method: &PaymentMethod,
1225 ) -> anyhow::Result<Vec<Movement>> {
1226 let mut ret = self.db.get_movements_by_payment_method(payment_method).await?;
1227 ret.sort_by_key(|m| m.id);
1228 Ok(ret)
1229 }
1230
1231 pub async fn all_vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
1233 Ok(self.db.get_all_vtxos().await?)
1234 }
1235
1236 pub async fn vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
1238 Ok(self.db.get_vtxos_by_state(&VtxoStateKind::UNSPENT_STATES).await?)
1239 }
1240
1241 pub async fn vtxos_with(&self, filter: &impl FilterVtxos) -> anyhow::Result<Vec<WalletVtxo>> {
1243 let mut vtxos = self.vtxos().await?;
1244 filter.filter_vtxos(&mut vtxos).await.context("error filtering vtxos")?;
1245 Ok(vtxos)
1246 }
1247
1248 pub async fn spendable_vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
1250 Ok(self.vtxos_with(&VtxoStateKind::Spendable).await?)
1251 }
1252
1253 pub async fn spendable_vtxos_with(
1255 &self,
1256 filter: &impl FilterVtxos,
1257 ) -> anyhow::Result<Vec<WalletVtxo>> {
1258 let mut vtxos = self.spendable_vtxos().await?;
1259 filter.filter_vtxos(&mut vtxos).await.context("error filtering vtxos")?;
1260 Ok(vtxos)
1261 }
1262
1263 pub async fn get_expiring_vtxos(
1265 &self,
1266 threshold: BlockHeight,
1267 ) -> anyhow::Result<Vec<WalletVtxo>> {
1268 let expiry = self.chain.tip().await? + threshold;
1269 let filter = VtxoFilter::new(&self).expires_before(expiry);
1270 Ok(self.spendable_vtxos_with(&filter).await?)
1271 }
1272
1273 pub async fn sync_pending_offboards(&self) -> anyhow::Result<()> {
1279 let pending_offboards: Vec<PendingOffboard> = self.db.get_pending_offboards().await?;
1280
1281 if pending_offboards.is_empty() {
1282 return Ok(());
1283 }
1284
1285 let current_height = self.chain.tip().await?;
1286 let required_confs = self.config.offboard_required_confirmations;
1287
1288 trace!("Checking {} pending offboard transaction(s)", pending_offboards.len());
1289
1290 for pending in pending_offboards {
1291 let status = self.chain.tx_status(pending.offboard_txid).await;
1292
1293 match status {
1294 Ok(TxStatus::Confirmed(block_ref)) => {
1295 let confs = current_height - (block_ref.height - 1);
1296 if confs < required_confs as BlockHeight {
1297 trace!(
1298 "Offboard tx {} has {}/{} confirmations, waiting...",
1299 pending.offboard_txid, confs, required_confs,
1300 );
1301 continue;
1302 }
1303
1304 info!(
1305 "Offboard tx {} confirmed, finalizing movement {}",
1306 pending.offboard_txid, pending.movement_id,
1307 );
1308
1309 for vtxo_id in &pending.vtxo_ids {
1311 if let Err(e) = self.db.update_vtxo_state_checked(
1312 *vtxo_id,
1313 VtxoState::Spent,
1314 &[VtxoStateKind::Locked],
1315 ).await {
1316 warn!("Failed to mark vtxo {} as spent: {:#}", vtxo_id, e);
1317 }
1318 }
1319
1320 if let Err(e) = self.movements.finish_movement(
1322 pending.movement_id,
1323 MovementStatus::Successful,
1324 ).await {
1325 warn!("Failed to finish movement {}: {:#}", pending.movement_id, e);
1326 }
1327
1328 self.db.remove_pending_offboard(pending.movement_id).await?;
1329 }
1330 Ok(TxStatus::Mempool) => {
1331 if required_confs == 0 {
1332 info!(
1333 "Offboard tx {} in mempool with 0 required confirmations, \
1334 finalizing movement {}",
1335 pending.offboard_txid, pending.movement_id,
1336 );
1337
1338 for vtxo_id in &pending.vtxo_ids {
1340 if let Err(e) = self.db.update_vtxo_state_checked(
1341 *vtxo_id,
1342 VtxoState::Spent,
1343 &[VtxoStateKind::Locked],
1344 ).await {
1345 warn!("Failed to mark vtxo {} as spent: {:#}", vtxo_id, e);
1346 }
1347 }
1348
1349 if let Err(e) = self.movements.finish_movement(
1351 pending.movement_id,
1352 MovementStatus::Successful,
1353 ).await {
1354 warn!("Failed to finish movement {}: {:#}", pending.movement_id, e);
1355 }
1356
1357 self.db.remove_pending_offboard(pending.movement_id).await?;
1358 } else {
1359 trace!(
1360 "Offboard tx {} still in mempool, waiting...",
1361 pending.offboard_txid,
1362 );
1363 }
1364 }
1365 Ok(TxStatus::NotFound) => {
1366 let age = chrono::Local::now() - pending.created_at;
1370 if age < chrono::Duration::hours(1) {
1371 trace!(
1372 "Offboard tx {} not found, but only {} minutes old — waiting...",
1373 pending.offboard_txid, age.num_minutes(),
1374 );
1375 continue;
1376 }
1377
1378 warn!(
1379 "Offboard tx {} not found after {} minutes, canceling movement {}",
1380 pending.offboard_txid, age.num_minutes(), pending.movement_id,
1381 );
1382
1383 for vtxo_id in &pending.vtxo_ids {
1385 if let Err(e) = self.db.update_vtxo_state_checked(
1386 *vtxo_id,
1387 VtxoState::Spendable,
1388 &[VtxoStateKind::Locked],
1389 ).await {
1390 warn!("Failed to restore vtxo {} to spendable: {:#}", vtxo_id, e);
1391 }
1392 }
1393
1394 if let Err(e) = self.movements.finish_movement(
1396 pending.movement_id,
1397 MovementStatus::Failed,
1398 ).await {
1399 warn!("Failed to fail movement {}: {:#}", pending.movement_id, e);
1400 }
1401
1402 self.db.remove_pending_offboard(pending.movement_id).await?;
1403 }
1404 Err(e) => {
1405 warn!(
1406 "Failed to check status of offboard tx {}: {:#}",
1407 pending.offboard_txid, e,
1408 );
1409 }
1410 }
1411 }
1412
1413 Ok(())
1414 }
1415
1416 pub async fn maintenance(&self) -> anyhow::Result<()> {
1422 info!("Starting wallet maintenance in interactive mode");
1423 self.sync().await;
1424
1425 let rounds = self.progress_pending_rounds(None).await;
1426 if let Err(e) = rounds.as_ref() {
1427 warn!("Error progressing pending rounds: {:#}", e);
1428 }
1429 let refresh = self.maintenance_refresh().await;
1430 if let Err(e) = refresh.as_ref() {
1431 warn!("Error refreshing VTXOs: {:#}", e);
1432 }
1433 if rounds.is_err() || refresh.is_err() {
1434 bail!("Maintenance encountered errors.\nprogress_rounds: {:#?}\nrefresh: {:#?}", rounds, refresh);
1435 }
1436 Ok(())
1437 }
1438
1439 pub async fn maintenance_delegated(&self) -> anyhow::Result<()> {
1445 info!("Starting wallet maintenance in delegated mode");
1446 self.sync().await;
1447 let rounds = self.progress_pending_rounds(None).await;
1448 if let Err(e) = rounds.as_ref() {
1449 warn!("Error progressing pending rounds: {:#}", e);
1450 }
1451 let refresh = self.maybe_schedule_maintenance_refresh_delegated().await;
1452 if let Err(e) = refresh.as_ref() {
1453 warn!("Error refreshing VTXOs: {:#}", e);
1454 }
1455 if rounds.is_err() || refresh.is_err() {
1456 bail!("Delegated maintenance encountered errors.\nprogress_rounds: {:#?}\nrefresh: {:#?}", rounds, refresh);
1457 }
1458 Ok(())
1459 }
1460
1461 pub async fn maintenance_with_onchain<W: PreparePsbt + SignPsbt + ExitUnilaterally>(
1469 &self,
1470 onchain: &mut W,
1471 ) -> anyhow::Result<()> {
1472 info!("Starting wallet maintenance in interactive mode with onchain wallet");
1473
1474 let maintenance = self.maintenance().await;
1476
1477 let exit_sync = self.sync_exits(onchain).await;
1479 if let Err(e) = exit_sync.as_ref() {
1480 warn!("Error syncing exits: {:#}", e);
1481 }
1482 let exit_progress = self.exit.write().await.progress_exits(&self, onchain, None).await;
1483 if let Err(e) = exit_progress.as_ref() {
1484 warn!("Error progressing exits: {:#}", e);
1485 }
1486 if maintenance.is_err() || exit_sync.is_err() || exit_progress.is_err() {
1487 bail!("Maintenance encountered errors.\nmaintenance: {:#?}\nexit_sync: {:#?}\nexit_progress: {:#?}", maintenance, exit_sync, exit_progress);
1488 }
1489 Ok(())
1490 }
1491
1492 pub async fn maintenance_with_onchain_delegated<W: PreparePsbt + SignPsbt + ExitUnilaterally>(
1499 &self,
1500 onchain: &mut W,
1501 ) -> anyhow::Result<()> {
1502 info!("Starting wallet maintenance in delegated mode with onchain wallet");
1503
1504 let maintenance = self.maintenance_delegated().await;
1506
1507 let exit_sync = self.sync_exits(onchain).await;
1509 if let Err(e) = exit_sync.as_ref() {
1510 warn!("Error syncing exits: {:#}", e);
1511 }
1512 let exit_progress = self.exit.write().await.progress_exits(&self, onchain, None).await;
1513 if let Err(e) = exit_progress.as_ref() {
1514 warn!("Error progressing exits: {:#}", e);
1515 }
1516 if maintenance.is_err() || exit_sync.is_err() || exit_progress.is_err() {
1517 bail!("Delegated maintenance encountered errors.\nmaintenance: {:#?}\nexit_sync: {:#?}\nexit_progress: {:#?}", maintenance, exit_sync, exit_progress);
1518 }
1519 Ok(())
1520 }
1521
1522 pub async fn maybe_schedule_maintenance_refresh(&self) -> anyhow::Result<Option<RoundStateId>> {
1530 let vtxos = self.get_vtxos_to_refresh().await?;
1531 if vtxos.len() == 0 {
1532 return Ok(None);
1533 }
1534
1535 let participation = match self.build_refresh_participation(vtxos).await? {
1536 Some(participation) => participation,
1537 None => return Ok(None),
1538 };
1539
1540 info!("Scheduling maintenance refresh ({} vtxos)", participation.inputs.len());
1541 let state = self.join_next_round(participation, Some(RoundMovement::Refresh)).await?;
1542 Ok(Some(state.id()))
1543 }
1544
1545 pub async fn maybe_schedule_maintenance_refresh_delegated(
1553 &self,
1554 ) -> anyhow::Result<Option<RoundStateId>> {
1555 let vtxos = self.get_vtxos_to_refresh().await?;
1556 if vtxos.len() == 0 {
1557 return Ok(None);
1558 }
1559
1560 let participation = match self.build_refresh_participation(vtxos).await? {
1561 Some(participation) => participation,
1562 None => return Ok(None),
1563 };
1564
1565 info!("Scheduling delegated maintenance refresh ({} vtxos)", participation.inputs.len());
1566 let state = self.join_next_round_delegated(participation, Some(RoundMovement::Refresh)).await?;
1567 Ok(Some(state.id()))
1568 }
1569
1570 pub async fn maintenance_refresh(&self) -> anyhow::Result<Option<RoundStatus>> {
1578 let vtxos = self.get_vtxos_to_refresh().await?;
1579 if vtxos.len() == 0 {
1580 return Ok(None);
1581 }
1582
1583 info!("Performing maintenance refresh");
1584 self.refresh_vtxos(vtxos).await
1585 }
1586
1587 pub async fn sync(&self) {
1593 futures::join!(
1594 async {
1595 if let Err(e) = self.chain.update_fee_rates(self.config.fallback_fee_rate).await {
1598 warn!("Error updating fee rates: {:#}", e);
1599 }
1600 },
1601 async {
1602 if let Err(e) = self.sync_mailbox().await {
1603 warn!("Error in mailbox sync: {:#}", e);
1604 }
1605 },
1606 async {
1607 if let Err(e) = self.sync_pending_rounds().await {
1608 warn!("Error while trying to progress rounds awaiting confirmations: {:#}", e);
1609 }
1610 },
1611 async {
1612 if let Err(e) = self.sync_pending_lightning_send_vtxos().await {
1613 warn!("Error syncing pending lightning payments: {:#}", e);
1614 }
1615 },
1616 async {
1617 if let Err(e) = self.try_claim_all_lightning_receives(false).await {
1618 warn!("Error claiming pending lightning receives: {:#}", e);
1619 }
1620 },
1621 async {
1622 if let Err(e) = self.sync_pending_boards().await {
1623 warn!("Error syncing pending boards: {:#}", e);
1624 }
1625 },
1626 async {
1627 if let Err(e) = self.sync_pending_offboards().await {
1628 warn!("Error syncing pending offboards: {:#}", e);
1629 }
1630 }
1631 );
1632 }
1633
1634 pub async fn sync_exits(
1640 &self,
1641 onchain: &mut dyn ExitUnilaterally,
1642 ) -> anyhow::Result<()> {
1643 self.exit.write().await.sync(&self, onchain).await?;
1644 Ok(())
1645 }
1646
1647 pub async fn dangerous_drop_vtxo(&self, vtxo_id: VtxoId) -> anyhow::Result<()> {
1650 warn!("Drop vtxo {} from the database", vtxo_id);
1651 self.db.remove_vtxo(vtxo_id).await?;
1652 Ok(())
1653 }
1654
1655 pub async fn dangerous_drop_all_vtxos(&self) -> anyhow::Result<()> {
1658 warn!("Dropping all vtxos from the db...");
1659 for vtxo in self.vtxos().await? {
1660 self.db.remove_vtxo(vtxo.id()).await?;
1661 }
1662
1663 self.exit.write().await.dangerous_clear_exit().await?;
1664 Ok(())
1665 }
1666
1667 async fn has_counterparty_risk(&self, vtxo: &Vtxo<Full>) -> anyhow::Result<bool> {
1672 for past_pks in vtxo.past_arkoor_pubkeys() {
1673 let mut owns_any = false;
1674 for past_pk in past_pks {
1675 if self.db.get_public_key_idx(&past_pk).await?.is_some() {
1676 owns_any = true;
1677 break;
1678 }
1679 }
1680 if !owns_any {
1681 return Ok(true);
1682 }
1683 }
1684
1685 let my_clause = self.find_signable_clause(vtxo).await;
1686 Ok(!my_clause.is_some())
1687 }
1688
1689 async fn add_should_refresh_vtxos(
1695 &self,
1696 participation: &mut RoundParticipation,
1697 ) -> anyhow::Result<()> {
1698 let tip = self.chain.tip().await?;
1701 let mut vtxos_to_refresh = self.spendable_vtxos_with(
1702 &RefreshStrategy::should_refresh(self, tip, self.chain.fee_rates().await.fast),
1703 ).await?;
1704 if vtxos_to_refresh.is_empty() {
1705 return Ok(());
1706 }
1707
1708 let excluded_ids = participation.inputs.iter().map(|v| v.vtxo_id())
1709 .collect::<HashSet<_>>();
1710 let mut total_amount = Amount::ZERO;
1711 for i in (0..vtxos_to_refresh.len()).rev() {
1712 let vtxo = &vtxos_to_refresh[i];
1713 if excluded_ids.contains(&vtxo.id()) {
1714 vtxos_to_refresh.swap_remove(i);
1715 continue;
1716 }
1717 total_amount += vtxo.amount();
1718 }
1719 if vtxos_to_refresh.is_empty() {
1720 return Ok(());
1722 }
1723
1724 let (_, ark_info) = self.require_server().await?;
1727 let fee = ark_info.fees.refresh.calculate_no_base_fee(
1728 vtxos_to_refresh.iter().map(|wv| VtxoFeeInfo::from_vtxo_and_tip(&wv.vtxo, tip)),
1729 ).context("fee overflowed")?;
1730
1731 let output_amount = match validate_and_subtract_fee_min_dust(total_amount, fee) {
1733 Ok(amount) => amount,
1734 Err(e) => {
1735 trace!("Cannot add should-refresh VTXOs: {}", e);
1736 return Ok(());
1737 },
1738 };
1739 info!(
1740 "Adding {} extra VTXOs to round participation total = {}, fee = {}, output = {}",
1741 vtxos_to_refresh.len(), total_amount, fee, output_amount,
1742 );
1743 let (user_keypair, _) = self.derive_store_next_keypair().await?;
1744 let req = VtxoRequest {
1745 policy: VtxoPolicy::new_pubkey(user_keypair.public_key()),
1746 amount: output_amount,
1747 };
1748 participation.inputs.reserve(vtxos_to_refresh.len());
1749 participation.inputs.extend(vtxos_to_refresh.into_iter().map(|wv| wv.vtxo));
1750 participation.outputs.push(req);
1751
1752 Ok(())
1753 }
1754
1755 pub async fn build_refresh_participation<V: VtxoRef>(
1756 &self,
1757 vtxos: impl IntoIterator<Item = V>,
1758 ) -> anyhow::Result<Option<RoundParticipation>> {
1759 let (vtxos, total_amount) = {
1760 let iter = vtxos.into_iter();
1761 let size_hint = iter.size_hint();
1762 let mut vtxos = Vec::<Vtxo<Full>>::with_capacity(size_hint.1.unwrap_or(size_hint.0));
1763 let mut amount = Amount::ZERO;
1764 for vref in iter {
1765 let id = vref.vtxo_id();
1770 if vtxos.iter().any(|v| v.id() == id) {
1771 bail!("duplicate VTXO id: {}", id);
1772 }
1773 let vtxo = if let Some(vtxo) = vref.into_full_vtxo() {
1774 vtxo
1775 } else {
1776 self.get_vtxo_by_id(id).await
1777 .with_context(|| format!("vtxo with id {} not found", id))?.vtxo
1778 };
1779 amount += vtxo.amount();
1780 vtxos.push(vtxo);
1781 }
1782 (vtxos, amount)
1783 };
1784
1785 if vtxos.is_empty() {
1786 info!("Skipping refresh since no VTXOs are provided.");
1787 return Ok(None);
1788 }
1789 ensure!(total_amount >= P2TR_DUST,
1790 "vtxo amount must be at least {} to participate in a round",
1791 P2TR_DUST,
1792 );
1793
1794 let (_, ark_info) = self.require_server().await?;
1796 let current_height = self.chain.tip().await?;
1797 let vtxo_fee_infos = vtxos.iter()
1798 .map(|v| VtxoFeeInfo::from_vtxo_and_tip(v, current_height));
1799 let fee = ark_info.fees.refresh.calculate(vtxo_fee_infos).context("fee overflowed")?;
1800 let output_amount = validate_and_subtract_fee_min_dust(total_amount, fee)?;
1801
1802 info!("Refreshing {} VTXOs (total amount = {}, fee = {}, output = {}).",
1803 vtxos.len(), total_amount, fee, output_amount,
1804 );
1805 let (user_keypair, _) = self.derive_store_next_keypair().await?;
1806 let req = VtxoRequest {
1807 policy: VtxoPolicy::Pubkey(PubkeyVtxoPolicy { user_pubkey: user_keypair.public_key() }),
1808 amount: output_amount,
1809 };
1810
1811 Ok(Some(RoundParticipation {
1812 inputs: vtxos,
1813 outputs: vec![req],
1814 unblinded_mailbox_id: None,
1815 }))
1816 }
1817
1818 pub async fn refresh_vtxos<V: VtxoRef>(
1823 &self,
1824 vtxos: impl IntoIterator<Item = V>,
1825 ) -> anyhow::Result<Option<RoundStatus>> {
1826 let mut participation = match self.build_refresh_participation(vtxos).await? {
1827 Some(participation) => participation,
1828 None => return Ok(None),
1829 };
1830
1831 if let Err(e) = self.add_should_refresh_vtxos(&mut participation).await {
1832 warn!("Error trying to add additional VTXOs that should be refreshed: {:#}", e);
1833 }
1834
1835 Ok(Some(self.participate_round(participation, Some(RoundMovement::Refresh)).await?))
1836 }
1837
1838 pub async fn refresh_vtxos_delegated<V: VtxoRef>(
1844 &self,
1845 vtxos: impl IntoIterator<Item = V>,
1846 ) -> anyhow::Result<Option<StoredRoundState<Unlocked>>> {
1847 let mut part = match self.build_refresh_participation(vtxos).await? {
1848 Some(participation) => participation,
1849 None => return Ok(None),
1850 };
1851
1852 if let Err(e) = self.add_should_refresh_vtxos(&mut part).await {
1853 warn!("Error trying to add additional VTXOs that should be refreshed: {:#}", e);
1854 }
1855
1856 Ok(Some(self.join_next_round_delegated(part, Some(RoundMovement::Refresh)).await?))
1857 }
1858
1859 pub async fn get_vtxos_to_refresh(&self) -> anyhow::Result<Vec<WalletVtxo>> {
1862 let vtxos = self.spendable_vtxos_with(&RefreshStrategy::should_refresh_if_must(
1863 self,
1864 self.chain.tip().await?,
1865 self.chain.fee_rates().await.fast,
1866 )).await?;
1867 Ok(vtxos)
1868 }
1869
1870 pub async fn get_first_expiring_vtxo_blockheight(
1872 &self,
1873 ) -> anyhow::Result<Option<BlockHeight>> {
1874 Ok(self.spendable_vtxos().await?.iter().map(|v| v.expiry_height()).min())
1875 }
1876
1877 pub async fn get_next_required_refresh_blockheight(
1880 &self,
1881 ) -> anyhow::Result<Option<BlockHeight>> {
1882 let first_expiry = self.get_first_expiring_vtxo_blockheight().await?;
1883 Ok(first_expiry.map(|h| h.saturating_sub(self.config.vtxo_refresh_expiry_threshold)))
1884 }
1885
1886 async fn select_vtxos_to_cover(
1892 &self,
1893 amount: Amount,
1894 ) -> anyhow::Result<Vec<WalletVtxo>> {
1895 let mut vtxos = self.spendable_vtxos().await?;
1896 vtxos.sort_by_key(|v| v.expiry_height());
1897
1898 let mut result = Vec::new();
1900 let mut total_amount = Amount::ZERO;
1901 for input in vtxos {
1902 total_amount += input.amount();
1903 result.push(input);
1904
1905 if total_amount >= amount {
1906 return Ok(result)
1907 }
1908 }
1909
1910 bail!("Insufficient money available. Needed {} but {} is available",
1911 amount, total_amount,
1912 );
1913 }
1914
1915 async fn select_vtxos_to_cover_with_fee<F>(
1921 &self,
1922 amount: Amount,
1923 calc_fee: F,
1924 ) -> anyhow::Result<(Vec<WalletVtxo>, Amount)>
1925 where
1926 F: for<'a> Fn(
1927 Amount, std::iter::Copied<std::slice::Iter<'a, VtxoFeeInfo>>,
1928 ) -> anyhow::Result<Amount>,
1929 {
1930 let tip = self.chain.tip().await?;
1931
1932 const MAX_ITERATIONS: usize = 100;
1935 let mut fee = Amount::ZERO;
1936 let mut fee_info = Vec::new();
1937 for _ in 0..MAX_ITERATIONS {
1938 let required = amount.checked_add(fee)
1939 .context("Amount + fee overflow")?;
1940
1941 let vtxos = self.select_vtxos_to_cover(required).await
1942 .context("Could not find enough suitable VTXOs to cover payment + fees")?;
1943
1944 fee_info.reserve(vtxos.len());
1945 let mut vtxo_amount = Amount::ZERO;
1946 for vtxo in &vtxos {
1947 vtxo_amount += vtxo.amount();
1948 fee_info.push(VtxoFeeInfo::from_vtxo_and_tip(vtxo, tip));
1949 }
1950
1951 fee = calc_fee(amount, fee_info.iter().copied())?;
1952 if amount + fee <= vtxo_amount {
1953 trace!("Selected vtxos to cover amount + fee: amount = {}, fee = {}, total inputs = {}",
1954 amount, fee, vtxo_amount,
1955 );
1956 return Ok((vtxos, fee));
1957 }
1958 trace!("VTXO sum of {} did not exceed amount {} and fee {}, iterating again",
1959 vtxo_amount, amount, fee,
1960 );
1961 fee_info.clear();
1962 }
1963 bail!("Fee calculation did not converge after maximum iterations")
1964 }
1965
1966 pub async fn run_daemon(
1972 self: &Arc<Self>,
1973 onchain: Arc<RwLock<dyn DaemonizableOnchainWallet>>,
1974 ) -> anyhow::Result<DaemonHandle> {
1975 Ok(crate::daemon::start_daemon(self.clone(), onchain))
1978 }
1979
1980 pub async fn register_vtxos_with_server(
1984 &self,
1985 vtxos: &[impl AsRef<Vtxo<Full>>],
1986 ) -> anyhow::Result<()> {
1987 if vtxos.is_empty() {
1988 return Ok(());
1989 }
1990
1991 let (mut srv, _) = self.require_server().await?;
1992 srv.client.register_vtxos(protos::RegisterVtxosRequest {
1993 vtxos: vtxos.iter().map(|v| v.as_ref().serialize()).collect(),
1994 }).await.context("failed to register vtxos")?;
1995
1996 Ok(())
1997 }
1998}