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 async fn open_with_daemon(
1017 mnemonic: &Mnemonic,
1018 db: Arc<dyn BarkPersister>,
1019 cfg: Config,
1020 onchain: Option<Arc<RwLock<dyn DaemonizableOnchainWallet>>>,
1021 ) -> anyhow::Result<(Arc<Wallet>, DaemonHandle)> {
1022 let wallet = Arc::new(Wallet::open(mnemonic, db, cfg).await?);
1023 if let Some(onchain) = onchain.as_ref() {
1024 let mut onchain = onchain.write().await;
1025 wallet.exit.write().await.load(&mut *onchain).await?;
1026 }
1027
1028 let daemon = wallet.clone().run_daemon(onchain)?;
1029
1030 Ok((wallet, daemon))
1031 }
1032
1033 pub fn config(&self) -> &Config {
1035 &self.config
1036 }
1037
1038 pub async fn properties(&self) -> anyhow::Result<WalletProperties> {
1040 let properties = self.db.read_properties().await?.context("Wallet is not initialised")?;
1041 Ok(properties)
1042 }
1043
1044 pub fn fingerprint(&self) -> Fingerprint {
1046 self.seed.fingerprint()
1047 }
1048
1049 async fn connect_to_server(
1050 config: &Config,
1051 network: Network,
1052 ) -> anyhow::Result<ServerConnection> {
1053 let address = &config.server_address;
1054 #[cfg(feature = "socks5-proxy")]
1055 if let Some(proxy) = proxy_for_url(&config.socks5_proxy, address)? {
1056 return ServerConnection::connect_via_proxy(address, network, &proxy).await
1057 .context("Failed to connect Ark server via proxy");
1058 }
1059 ServerConnection::connect(address, network).await
1060 .context("Failed to connect to Ark server")
1061 }
1062
1063 async fn require_server(&self) -> anyhow::Result<(ServerConnection, ArkInfo)> {
1064 let conn = self.server.read().clone()
1065 .context("You should be connected to Ark server to perform this action")?;
1066 let ark_info = conn.ark_info().await?;
1067
1068 if let Some(stored_pubkey) = self.properties().await?.server_pubkey {
1070 if stored_pubkey != ark_info.server_pubkey {
1071 log_server_pubkey_changed_error(stored_pubkey, ark_info.server_pubkey);
1072 bail!("Server public key has changed. You should exit all your VTXOs!");
1073 }
1074 } else {
1075 self.db.set_server_pubkey(ark_info.server_pubkey).await?;
1077 info!("Stored server pubkey for existing wallet: {}", ark_info.server_pubkey);
1078 }
1079
1080 Ok((conn, ark_info))
1081 }
1082
1083 pub async fn refresh_server(&self) -> anyhow::Result<()> {
1084 let server = self.server.read().clone();
1085 let properties = self.properties().await?;
1086
1087 let srv = if let Some(srv) = server {
1088 srv.check_connection().await?;
1089 let ark_info = srv.ark_info().await?;
1090 ark_info.fees.validate().context("invalid fee schedule")?;
1091
1092 if let Some(stored_pubkey) = properties.server_pubkey {
1094 if stored_pubkey != ark_info.server_pubkey {
1095 log_server_pubkey_changed_error(stored_pubkey, ark_info.server_pubkey);
1096 bail!("Server public key has changed. You should exit all your VTXOs!");
1097 }
1098 } else {
1099 self.db.set_server_pubkey(ark_info.server_pubkey).await?;
1101 info!("Stored server pubkey for existing wallet: {}", ark_info.server_pubkey);
1102 }
1103
1104 srv
1105 } else {
1106 let conn = Self::connect_to_server(&self.config, properties.network).await?;
1107 let ark_info = conn.ark_info().await?;
1108 ark_info.fees.validate().context("invalid fee schedule")?;
1109
1110 if let Some(stored_pubkey) = properties.server_pubkey {
1112 if stored_pubkey != ark_info.server_pubkey {
1113 log_server_pubkey_changed_error(stored_pubkey, ark_info.server_pubkey);
1114 bail!("Server public key has changed. You should exit all your VTXOs!");
1115 }
1116 } else {
1117 self.db.set_server_pubkey(ark_info.server_pubkey).await?;
1119 info!("Stored server pubkey for existing wallet: {}", ark_info.server_pubkey);
1120 }
1121
1122 conn
1123 };
1124
1125 let _ = self.server.write().insert(srv);
1126
1127 Ok(())
1128 }
1129
1130 pub async fn ark_info(&self) -> anyhow::Result<Option<ArkInfo>> {
1132 let server = self.server.read().clone();
1133 match server.as_ref() {
1134 Some(srv) => Ok(Some(srv.ark_info().await?)),
1135 _ => Ok(None),
1136 }
1137 }
1138
1139 pub async fn balance(&self) -> anyhow::Result<Balance> {
1143 let vtxos = self.vtxos().await?;
1144
1145 let spendable = {
1146 let mut v = vtxos.iter().collect();
1147 VtxoStateKind::Spendable.filter_vtxos(&mut v).await?;
1148 v.into_iter().map(|v| v.amount()).sum::<Amount>()
1149 };
1150
1151 let pending_lightning_send = self.pending_lightning_send_vtxos().await?.iter()
1152 .map(|v| v.amount())
1153 .sum::<Amount>();
1154
1155 let claimable_lightning_receive = self.claimable_lightning_receive_balance().await?;
1156
1157 let pending_board = self.pending_board_vtxos().await?.iter()
1158 .map(|v| v.amount())
1159 .sum::<Amount>();
1160
1161 let pending_in_round = self.pending_round_balance().await?;
1162
1163 let pending_exit = self.exit.try_read().ok().map(|e| e.pending_total());
1164
1165 Ok(Balance {
1166 spendable,
1167 pending_in_round,
1168 pending_lightning_send,
1169 claimable_lightning_receive,
1170 pending_exit,
1171 pending_board,
1172 })
1173 }
1174
1175 pub async fn validate_vtxo(&self, vtxo: &Vtxo<Full>) -> anyhow::Result<()> {
1177 let tx = self.chain.get_tx(&vtxo.chain_anchor().txid).await
1178 .context("could not fetch chain tx")?;
1179
1180 let tx = tx.with_context(|| {
1181 format!("vtxo chain anchor not found for vtxo: {}", vtxo.chain_anchor().txid)
1182 })?;
1183
1184 vtxo.validate(&tx)?;
1185
1186 Ok(())
1187 }
1188
1189 pub async fn import_vtxo(&self, vtxo: &Vtxo<Full>) -> anyhow::Result<()> {
1199 if self.db.get_wallet_vtxo(vtxo.id()).await?.is_some() {
1200 info!("VTXO {} already exists in wallet, skipping import", vtxo.id());
1201 return Ok(());
1202 }
1203
1204 self.validate_vtxo(vtxo).await.context("VTXO validation failed")?;
1205
1206 if self.find_signable_clause(vtxo).await.is_none() {
1207 bail!("VTXO {} is not owned by this wallet (no signable clause found)", vtxo.id());
1208 }
1209
1210 let current_height = self.chain.tip().await?;
1211 if vtxo.expiry_height() <= current_height {
1212 bail!("Vtxo {} has expired", vtxo.id());
1213 }
1214
1215 self.store_spendable_vtxos([vtxo]).await.context("failed to store imported VTXO")?;
1216
1217 info!("Successfully imported VTXO {}", vtxo.id());
1218 Ok(())
1219 }
1220
1221 pub async fn get_vtxo_by_id(&self, vtxo_id: VtxoId) -> anyhow::Result<WalletVtxo> {
1223 let vtxo = self.db.get_wallet_vtxo(vtxo_id).await
1224 .with_context(|| format!("Error when querying vtxo {} in database", vtxo_id))?
1225 .with_context(|| format!("The VTXO with id {} cannot be found", vtxo_id))?;
1226 Ok(vtxo)
1227 }
1228
1229 #[deprecated(since="0.1.0-beta.5", note = "Use Wallet::history instead")]
1231 pub async fn movements(&self) -> anyhow::Result<Vec<Movement>> {
1232 self.history().await
1233 }
1234
1235 pub async fn history(&self) -> anyhow::Result<Vec<Movement>> {
1237 Ok(self.db.get_all_movements().await?)
1238 }
1239
1240 pub async fn history_by_payment_method(
1242 &self,
1243 payment_method: &PaymentMethod,
1244 ) -> anyhow::Result<Vec<Movement>> {
1245 let mut ret = self.db.get_movements_by_payment_method(payment_method).await?;
1246 ret.sort_by_key(|m| m.id);
1247 Ok(ret)
1248 }
1249
1250 pub async fn all_vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
1252 Ok(self.db.get_all_vtxos().await?)
1253 }
1254
1255 pub async fn vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
1257 Ok(self.db.get_vtxos_by_state(&VtxoStateKind::UNSPENT_STATES).await?)
1258 }
1259
1260 pub async fn vtxos_with(&self, filter: &impl FilterVtxos) -> anyhow::Result<Vec<WalletVtxo>> {
1262 let mut vtxos = self.vtxos().await?;
1263 filter.filter_vtxos(&mut vtxos).await.context("error filtering vtxos")?;
1264 Ok(vtxos)
1265 }
1266
1267 pub async fn spendable_vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
1269 Ok(self.vtxos_with(&VtxoStateKind::Spendable).await?)
1270 }
1271
1272 pub async fn spendable_vtxos_with(
1274 &self,
1275 filter: &impl FilterVtxos,
1276 ) -> anyhow::Result<Vec<WalletVtxo>> {
1277 let mut vtxos = self.spendable_vtxos().await?;
1278 filter.filter_vtxos(&mut vtxos).await.context("error filtering vtxos")?;
1279 Ok(vtxos)
1280 }
1281
1282 pub async fn get_expiring_vtxos(
1284 &self,
1285 threshold: BlockHeight,
1286 ) -> anyhow::Result<Vec<WalletVtxo>> {
1287 let expiry = self.chain.tip().await? + threshold;
1288 let filter = VtxoFilter::new(&self).expires_before(expiry);
1289 Ok(self.spendable_vtxos_with(&filter).await?)
1290 }
1291
1292 pub async fn sync_pending_offboards(&self) -> anyhow::Result<()> {
1298 let pending_offboards: Vec<PendingOffboard> = self.db.get_pending_offboards().await?;
1299
1300 if pending_offboards.is_empty() {
1301 return Ok(());
1302 }
1303
1304 let current_height = self.chain.tip().await?;
1305 let required_confs = self.config.offboard_required_confirmations;
1306
1307 trace!("Checking {} pending offboard transaction(s)", pending_offboards.len());
1308
1309 for pending in pending_offboards {
1310 let status = self.chain.tx_status(pending.offboard_txid).await;
1311
1312 match status {
1313 Ok(TxStatus::Confirmed(block_ref)) => {
1314 let confs = current_height - (block_ref.height - 1);
1315 if confs < required_confs as BlockHeight {
1316 trace!(
1317 "Offboard tx {} has {}/{} confirmations, waiting...",
1318 pending.offboard_txid, confs, required_confs,
1319 );
1320 continue;
1321 }
1322
1323 info!(
1324 "Offboard tx {} confirmed, finalizing movement {}",
1325 pending.offboard_txid, pending.movement_id,
1326 );
1327
1328 for vtxo_id in &pending.vtxo_ids {
1330 if let Err(e) = self.db.update_vtxo_state_checked(
1331 *vtxo_id,
1332 VtxoState::Spent,
1333 &[VtxoStateKind::Locked],
1334 ).await {
1335 warn!("Failed to mark vtxo {} as spent: {:#}", vtxo_id, e);
1336 }
1337 }
1338
1339 if let Err(e) = self.movements.finish_movement(
1341 pending.movement_id,
1342 MovementStatus::Successful,
1343 ).await {
1344 warn!("Failed to finish movement {}: {:#}", pending.movement_id, e);
1345 }
1346
1347 self.db.remove_pending_offboard(pending.movement_id).await?;
1348 }
1349 Ok(TxStatus::Mempool) => {
1350 if required_confs == 0 {
1351 info!(
1352 "Offboard tx {} in mempool with 0 required confirmations, \
1353 finalizing movement {}",
1354 pending.offboard_txid, pending.movement_id,
1355 );
1356
1357 for vtxo_id in &pending.vtxo_ids {
1359 if let Err(e) = self.db.update_vtxo_state_checked(
1360 *vtxo_id,
1361 VtxoState::Spent,
1362 &[VtxoStateKind::Locked],
1363 ).await {
1364 warn!("Failed to mark vtxo {} as spent: {:#}", vtxo_id, e);
1365 }
1366 }
1367
1368 if let Err(e) = self.movements.finish_movement(
1370 pending.movement_id,
1371 MovementStatus::Successful,
1372 ).await {
1373 warn!("Failed to finish movement {}: {:#}", pending.movement_id, e);
1374 }
1375
1376 self.db.remove_pending_offboard(pending.movement_id).await?;
1377 } else {
1378 trace!(
1379 "Offboard tx {} still in mempool, waiting...",
1380 pending.offboard_txid,
1381 );
1382 }
1383 }
1384 Ok(TxStatus::NotFound) => {
1385 let age = chrono::Local::now() - pending.created_at;
1389 if age < chrono::Duration::hours(1) {
1390 trace!(
1391 "Offboard tx {} not found, but only {} minutes old — waiting...",
1392 pending.offboard_txid, age.num_minutes(),
1393 );
1394 continue;
1395 }
1396
1397 warn!(
1398 "Offboard tx {} not found after {} minutes, canceling movement {}",
1399 pending.offboard_txid, age.num_minutes(), pending.movement_id,
1400 );
1401
1402 for vtxo_id in &pending.vtxo_ids {
1404 if let Err(e) = self.db.update_vtxo_state_checked(
1405 *vtxo_id,
1406 VtxoState::Spendable,
1407 &[VtxoStateKind::Locked],
1408 ).await {
1409 warn!("Failed to restore vtxo {} to spendable: {:#}", vtxo_id, e);
1410 }
1411 }
1412
1413 if let Err(e) = self.movements.finish_movement(
1415 pending.movement_id,
1416 MovementStatus::Failed,
1417 ).await {
1418 warn!("Failed to fail movement {}: {:#}", pending.movement_id, e);
1419 }
1420
1421 self.db.remove_pending_offboard(pending.movement_id).await?;
1422 }
1423 Err(e) => {
1424 warn!(
1425 "Failed to check status of offboard tx {}: {:#}",
1426 pending.offboard_txid, e,
1427 );
1428 }
1429 }
1430 }
1431
1432 Ok(())
1433 }
1434
1435 pub async fn maintenance(&self) -> anyhow::Result<()> {
1441 info!("Starting wallet maintenance in interactive mode");
1442 self.sync().await;
1443
1444 let rounds = self.progress_pending_rounds(None).await;
1445 if let Err(e) = rounds.as_ref() {
1446 warn!("Error progressing pending rounds: {:#}", e);
1447 }
1448 let refresh = self.maintenance_refresh().await;
1449 if let Err(e) = refresh.as_ref() {
1450 warn!("Error refreshing VTXOs: {:#}", e);
1451 }
1452 if rounds.is_err() || refresh.is_err() {
1453 bail!("Maintenance encountered errors.\nprogress_rounds: {:#?}\nrefresh: {:#?}", rounds, refresh);
1454 }
1455 Ok(())
1456 }
1457
1458 pub async fn maintenance_delegated(&self) -> anyhow::Result<()> {
1464 info!("Starting wallet maintenance in delegated mode");
1465 self.sync().await;
1466 let rounds = self.progress_pending_rounds(None).await;
1467 if let Err(e) = rounds.as_ref() {
1468 warn!("Error progressing pending rounds: {:#}", e);
1469 }
1470 let refresh = self.maybe_schedule_maintenance_refresh_delegated().await;
1471 if let Err(e) = refresh.as_ref() {
1472 warn!("Error refreshing VTXOs: {:#}", e);
1473 }
1474 if rounds.is_err() || refresh.is_err() {
1475 bail!("Delegated maintenance encountered errors.\nprogress_rounds: {:#?}\nrefresh: {:#?}", rounds, refresh);
1476 }
1477 Ok(())
1478 }
1479
1480 pub async fn maintenance_with_onchain<W: PreparePsbt + SignPsbt + ExitUnilaterally>(
1488 &self,
1489 onchain: &mut W,
1490 ) -> anyhow::Result<()> {
1491 info!("Starting wallet maintenance in interactive mode with onchain wallet");
1492
1493 let maintenance = self.maintenance().await;
1495
1496 let exit_sync = self.sync_exits(onchain).await;
1498 if let Err(e) = exit_sync.as_ref() {
1499 warn!("Error syncing exits: {:#}", e);
1500 }
1501 let exit_progress = self.exit.write().await.progress_exits(&self, onchain, None).await;
1502 if let Err(e) = exit_progress.as_ref() {
1503 warn!("Error progressing exits: {:#}", e);
1504 }
1505 if maintenance.is_err() || exit_sync.is_err() || exit_progress.is_err() {
1506 bail!("Maintenance encountered errors.\nmaintenance: {:#?}\nexit_sync: {:#?}\nexit_progress: {:#?}", maintenance, exit_sync, exit_progress);
1507 }
1508 Ok(())
1509 }
1510
1511 pub async fn maintenance_with_onchain_delegated<W: PreparePsbt + SignPsbt + ExitUnilaterally>(
1518 &self,
1519 onchain: &mut W,
1520 ) -> anyhow::Result<()> {
1521 info!("Starting wallet maintenance in delegated mode with onchain wallet");
1522
1523 let maintenance = self.maintenance_delegated().await;
1525
1526 let exit_sync = self.sync_exits(onchain).await;
1528 if let Err(e) = exit_sync.as_ref() {
1529 warn!("Error syncing exits: {:#}", e);
1530 }
1531 let exit_progress = self.exit.write().await.progress_exits(&self, onchain, None).await;
1532 if let Err(e) = exit_progress.as_ref() {
1533 warn!("Error progressing exits: {:#}", e);
1534 }
1535 if maintenance.is_err() || exit_sync.is_err() || exit_progress.is_err() {
1536 bail!("Delegated maintenance encountered errors.\nmaintenance: {:#?}\nexit_sync: {:#?}\nexit_progress: {:#?}", maintenance, exit_sync, exit_progress);
1537 }
1538 Ok(())
1539 }
1540
1541 pub async fn maybe_schedule_maintenance_refresh(&self) -> anyhow::Result<Option<RoundStateId>> {
1549 let vtxos = self.get_vtxos_to_refresh().await?;
1550 if vtxos.len() == 0 {
1551 return Ok(None);
1552 }
1553
1554 let participation = match self.build_refresh_participation(vtxos).await? {
1555 Some(participation) => participation,
1556 None => return Ok(None),
1557 };
1558
1559 info!("Scheduling maintenance refresh ({} vtxos)", participation.inputs.len());
1560 let state = self.join_next_round(participation, Some(RoundMovement::Refresh)).await?;
1561 Ok(Some(state.id()))
1562 }
1563
1564 pub async fn maybe_schedule_maintenance_refresh_delegated(
1572 &self,
1573 ) -> anyhow::Result<Option<RoundStateId>> {
1574 let vtxos = self.get_vtxos_to_refresh().await?;
1575 if vtxos.len() == 0 {
1576 return Ok(None);
1577 }
1578
1579 let participation = match self.build_refresh_participation(vtxos).await? {
1580 Some(participation) => participation,
1581 None => return Ok(None),
1582 };
1583
1584 info!("Scheduling delegated maintenance refresh ({} vtxos)", participation.inputs.len());
1585 let state = self.join_next_round_delegated(participation, Some(RoundMovement::Refresh)).await?;
1586 Ok(Some(state.id()))
1587 }
1588
1589 pub async fn maintenance_refresh(&self) -> anyhow::Result<Option<RoundStatus>> {
1597 let vtxos = self.get_vtxos_to_refresh().await?;
1598 if vtxos.len() == 0 {
1599 return Ok(None);
1600 }
1601
1602 info!("Performing maintenance refresh");
1603 self.refresh_vtxos(vtxos).await
1604 }
1605
1606 pub async fn sync(&self) {
1612 futures::join!(
1613 async {
1614 if let Err(e) = self.chain.update_fee_rates(self.config.fallback_fee_rate).await {
1617 warn!("Error updating fee rates: {:#}", e);
1618 }
1619 },
1620 async {
1621 if let Err(e) = self.sync_mailbox().await {
1622 warn!("Error in mailbox sync: {:#}", e);
1623 }
1624 },
1625 async {
1626 if let Err(e) = self.sync_pending_rounds().await {
1627 warn!("Error while trying to progress rounds awaiting confirmations: {:#}", e);
1628 }
1629 },
1630 async {
1631 if let Err(e) = self.sync_pending_lightning_send_vtxos().await {
1632 warn!("Error syncing pending lightning payments: {:#}", e);
1633 }
1634 },
1635 async {
1636 if let Err(e) = self.try_claim_all_lightning_receives(false).await {
1637 warn!("Error claiming pending lightning receives: {:#}", e);
1638 }
1639 },
1640 async {
1641 if let Err(e) = self.sync_pending_boards().await {
1642 warn!("Error syncing pending boards: {:#}", e);
1643 }
1644 },
1645 async {
1646 if let Err(e) = self.sync_pending_offboards().await {
1647 warn!("Error syncing pending offboards: {:#}", e);
1648 }
1649 }
1650 );
1651 }
1652
1653 pub async fn sync_exits(
1659 &self,
1660 onchain: &mut dyn ExitUnilaterally,
1661 ) -> anyhow::Result<()> {
1662 self.exit.write().await.sync(&self, onchain).await?;
1663 Ok(())
1664 }
1665
1666 pub async fn dangerous_drop_vtxo(&self, vtxo_id: VtxoId) -> anyhow::Result<()> {
1669 warn!("Drop vtxo {} from the database", vtxo_id);
1670 self.db.remove_vtxo(vtxo_id).await?;
1671 Ok(())
1672 }
1673
1674 pub async fn dangerous_drop_all_vtxos(&self) -> anyhow::Result<()> {
1677 warn!("Dropping all vtxos from the db...");
1678 for vtxo in self.vtxos().await? {
1679 self.db.remove_vtxo(vtxo.id()).await?;
1680 }
1681
1682 self.exit.write().await.dangerous_clear_exit().await?;
1683 Ok(())
1684 }
1685
1686 async fn has_counterparty_risk(&self, vtxo: &Vtxo<Full>) -> anyhow::Result<bool> {
1691 for past_pks in vtxo.past_arkoor_pubkeys() {
1692 let mut owns_any = false;
1693 for past_pk in past_pks {
1694 if self.db.get_public_key_idx(&past_pk).await?.is_some() {
1695 owns_any = true;
1696 break;
1697 }
1698 }
1699 if !owns_any {
1700 return Ok(true);
1701 }
1702 }
1703
1704 let my_clause = self.find_signable_clause(vtxo).await;
1705 Ok(!my_clause.is_some())
1706 }
1707
1708 async fn add_should_refresh_vtxos(
1714 &self,
1715 participation: &mut RoundParticipation,
1716 ) -> anyhow::Result<()> {
1717 let tip = self.chain.tip().await?;
1720 let mut vtxos_to_refresh = self.spendable_vtxos_with(
1721 &RefreshStrategy::should_refresh(self, tip, self.chain.fee_rates().await.fast),
1722 ).await?;
1723 if vtxos_to_refresh.is_empty() {
1724 return Ok(());
1725 }
1726
1727 let excluded_ids = participation.inputs.iter().map(|v| v.vtxo_id())
1728 .collect::<HashSet<_>>();
1729 let mut total_amount = Amount::ZERO;
1730 for i in (0..vtxos_to_refresh.len()).rev() {
1731 let vtxo = &vtxos_to_refresh[i];
1732 if excluded_ids.contains(&vtxo.id()) {
1733 vtxos_to_refresh.swap_remove(i);
1734 continue;
1735 }
1736 total_amount += vtxo.amount();
1737 }
1738 if vtxos_to_refresh.is_empty() {
1739 return Ok(());
1741 }
1742
1743 let (_, ark_info) = self.require_server().await?;
1746 let fee = ark_info.fees.refresh.calculate_no_base_fee(
1747 vtxos_to_refresh.iter().map(|wv| VtxoFeeInfo::from_vtxo_and_tip(&wv.vtxo, tip)),
1748 ).context("fee overflowed")?;
1749
1750 let output_amount = match validate_and_subtract_fee_min_dust(total_amount, fee) {
1752 Ok(amount) => amount,
1753 Err(e) => {
1754 trace!("Cannot add should-refresh VTXOs: {}", e);
1755 return Ok(());
1756 },
1757 };
1758 info!(
1759 "Adding {} extra VTXOs to round participation total = {}, fee = {}, output = {}",
1760 vtxos_to_refresh.len(), total_amount, fee, output_amount,
1761 );
1762 let (user_keypair, _) = self.derive_store_next_keypair().await?;
1763 let req = VtxoRequest {
1764 policy: VtxoPolicy::new_pubkey(user_keypair.public_key()),
1765 amount: output_amount,
1766 };
1767 participation.inputs.reserve(vtxos_to_refresh.len());
1768 participation.inputs.extend(vtxos_to_refresh.into_iter().map(|wv| wv.vtxo));
1769 participation.outputs.push(req);
1770
1771 Ok(())
1772 }
1773
1774 pub async fn build_refresh_participation<V: VtxoRef>(
1775 &self,
1776 vtxos: impl IntoIterator<Item = V>,
1777 ) -> anyhow::Result<Option<RoundParticipation>> {
1778 let (vtxos, total_amount) = {
1779 let iter = vtxos.into_iter();
1780 let size_hint = iter.size_hint();
1781 let mut vtxos = Vec::<Vtxo<Full>>::with_capacity(size_hint.1.unwrap_or(size_hint.0));
1782 let mut amount = Amount::ZERO;
1783 for vref in iter {
1784 let id = vref.vtxo_id();
1789 if vtxos.iter().any(|v| v.id() == id) {
1790 bail!("duplicate VTXO id: {}", id);
1791 }
1792 let vtxo = if let Some(vtxo) = vref.into_full_vtxo() {
1793 vtxo
1794 } else {
1795 self.get_vtxo_by_id(id).await
1796 .with_context(|| format!("vtxo with id {} not found", id))?.vtxo
1797 };
1798 amount += vtxo.amount();
1799 vtxos.push(vtxo);
1800 }
1801 (vtxos, amount)
1802 };
1803
1804 if vtxos.is_empty() {
1805 info!("Skipping refresh since no VTXOs are provided.");
1806 return Ok(None);
1807 }
1808 ensure!(total_amount >= P2TR_DUST,
1809 "vtxo amount must be at least {} to participate in a round",
1810 P2TR_DUST,
1811 );
1812
1813 let (_, ark_info) = self.require_server().await?;
1815 let current_height = self.chain.tip().await?;
1816 let vtxo_fee_infos = vtxos.iter()
1817 .map(|v| VtxoFeeInfo::from_vtxo_and_tip(v, current_height));
1818 let fee = ark_info.fees.refresh.calculate(vtxo_fee_infos).context("fee overflowed")?;
1819 let output_amount = validate_and_subtract_fee_min_dust(total_amount, fee)?;
1820
1821 info!("Refreshing {} VTXOs (total amount = {}, fee = {}, output = {}).",
1822 vtxos.len(), total_amount, fee, output_amount,
1823 );
1824 let (user_keypair, _) = self.derive_store_next_keypair().await?;
1825 let req = VtxoRequest {
1826 policy: VtxoPolicy::Pubkey(PubkeyVtxoPolicy { user_pubkey: user_keypair.public_key() }),
1827 amount: output_amount,
1828 };
1829
1830 Ok(Some(RoundParticipation {
1831 inputs: vtxos,
1832 outputs: vec![req],
1833 unblinded_mailbox_id: None,
1834 }))
1835 }
1836
1837 pub async fn refresh_vtxos<V: VtxoRef>(
1842 &self,
1843 vtxos: impl IntoIterator<Item = V>,
1844 ) -> anyhow::Result<Option<RoundStatus>> {
1845 let mut participation = match self.build_refresh_participation(vtxos).await? {
1846 Some(participation) => participation,
1847 None => return Ok(None),
1848 };
1849
1850 if let Err(e) = self.add_should_refresh_vtxos(&mut participation).await {
1851 warn!("Error trying to add additional VTXOs that should be refreshed: {:#}", e);
1852 }
1853
1854 Ok(Some(self.participate_round(participation, Some(RoundMovement::Refresh)).await?))
1855 }
1856
1857 pub async fn refresh_vtxos_delegated<V: VtxoRef>(
1863 &self,
1864 vtxos: impl IntoIterator<Item = V>,
1865 ) -> anyhow::Result<Option<StoredRoundState<Unlocked>>> {
1866 let mut part = match self.build_refresh_participation(vtxos).await? {
1867 Some(participation) => participation,
1868 None => return Ok(None),
1869 };
1870
1871 if let Err(e) = self.add_should_refresh_vtxos(&mut part).await {
1872 warn!("Error trying to add additional VTXOs that should be refreshed: {:#}", e);
1873 }
1874
1875 Ok(Some(self.join_next_round_delegated(part, Some(RoundMovement::Refresh)).await?))
1876 }
1877
1878 pub async fn get_vtxos_to_refresh(&self) -> anyhow::Result<Vec<WalletVtxo>> {
1881 let vtxos = self.spendable_vtxos_with(&RefreshStrategy::should_refresh_if_must(
1882 self,
1883 self.chain.tip().await?,
1884 self.chain.fee_rates().await.fast,
1885 )).await?;
1886 Ok(vtxos)
1887 }
1888
1889 pub async fn get_first_expiring_vtxo_blockheight(
1891 &self,
1892 ) -> anyhow::Result<Option<BlockHeight>> {
1893 Ok(self.spendable_vtxos().await?.iter().map(|v| v.expiry_height()).min())
1894 }
1895
1896 pub async fn get_next_required_refresh_blockheight(
1899 &self,
1900 ) -> anyhow::Result<Option<BlockHeight>> {
1901 let first_expiry = self.get_first_expiring_vtxo_blockheight().await?;
1902 Ok(first_expiry.map(|h| h.saturating_sub(self.config.vtxo_refresh_expiry_threshold)))
1903 }
1904
1905 async fn select_vtxos_to_cover(
1911 &self,
1912 amount: Amount,
1913 ) -> anyhow::Result<Vec<WalletVtxo>> {
1914 let mut vtxos = self.spendable_vtxos().await?;
1915 vtxos.sort_by_key(|v| v.expiry_height());
1916
1917 let mut result = Vec::new();
1919 let mut total_amount = Amount::ZERO;
1920 for input in vtxos {
1921 total_amount += input.amount();
1922 result.push(input);
1923
1924 if total_amount >= amount {
1925 return Ok(result)
1926 }
1927 }
1928
1929 bail!("Insufficient money available. Needed {} but {} is available",
1930 amount, total_amount,
1931 );
1932 }
1933
1934 async fn select_vtxos_to_cover_with_fee<F>(
1940 &self,
1941 amount: Amount,
1942 calc_fee: F,
1943 ) -> anyhow::Result<(Vec<WalletVtxo>, Amount)>
1944 where
1945 F: for<'a> Fn(
1946 Amount, std::iter::Copied<std::slice::Iter<'a, VtxoFeeInfo>>,
1947 ) -> anyhow::Result<Amount>,
1948 {
1949 let tip = self.chain.tip().await?;
1950
1951 const MAX_ITERATIONS: usize = 100;
1954 let mut fee = Amount::ZERO;
1955 let mut fee_info = Vec::new();
1956 for _ in 0..MAX_ITERATIONS {
1957 let required = amount.checked_add(fee)
1958 .context("Amount + fee overflow")?;
1959
1960 let vtxos = self.select_vtxos_to_cover(required).await
1961 .context("Could not find enough suitable VTXOs to cover payment + fees")?;
1962
1963 fee_info.reserve(vtxos.len());
1964 let mut vtxo_amount = Amount::ZERO;
1965 for vtxo in &vtxos {
1966 vtxo_amount += vtxo.amount();
1967 fee_info.push(VtxoFeeInfo::from_vtxo_and_tip(vtxo, tip));
1968 }
1969
1970 fee = calc_fee(amount, fee_info.iter().copied())?;
1971 if amount + fee <= vtxo_amount {
1972 trace!("Selected vtxos to cover amount + fee: amount = {}, fee = {}, total inputs = {}",
1973 amount, fee, vtxo_amount,
1974 );
1975 return Ok((vtxos, fee));
1976 }
1977 trace!("VTXO sum of {} did not exceed amount {} and fee {}, iterating again",
1978 vtxo_amount, amount, fee,
1979 );
1980 fee_info.clear();
1981 }
1982 bail!("Fee calculation did not converge after maximum iterations")
1983 }
1984
1985 pub fn run_daemon(
1991 self: &Arc<Self>,
1992 onchain: Option<Arc<RwLock<dyn DaemonizableOnchainWallet>>>,
1993 ) -> anyhow::Result<DaemonHandle> {
1994 Ok(crate::daemon::start_daemon(self.clone(), onchain))
1997 }
1998
1999 pub async fn register_vtxos_with_server(
2003 &self,
2004 vtxos: &[impl AsRef<Vtxo<Full>>],
2005 ) -> anyhow::Result<()> {
2006 if vtxos.is_empty() {
2007 return Ok(());
2008 }
2009
2010 let (mut srv, _) = self.require_server().await?;
2011 srv.client.register_vtxos(protos::RegisterVtxosRequest {
2012 vtxos: vtxos.iter().map(|v| v.as_ref().serialize()).collect(),
2013 }).await.context("failed to register vtxos")?;
2014
2015 Ok(())
2016 }
2017}