Extracted the Esplora wallet into a struct

This commit is contained in:
Dave Hrycyszyn
2024-06-25 14:58:13 +01:00
parent 2474f5186d
commit 35deb4a75c
2 changed files with 106 additions and 83 deletions

View File

@@ -1,7 +1,10 @@
use std::{collections::BTreeSet, fs, io::Write, str::FromStr}; use std::{collections::BTreeSet, fs, io::Write, str::FromStr};
use bdk::keys::bip39::Mnemonic; use bdk::keys::bip39::Mnemonic;
use bdk_esplora::{esplora_client, EsploraAsyncExt}; use bdk_esplora::{
esplora_client::{self, AsyncClient},
EsploraAsyncExt,
};
use bdk_wallet::{ use bdk_wallet::{
bitcoin::{Address, Amount, Network, Script}, bitcoin::{Address, Amount, Network, Script},
chain::ConfirmationTimeHeightAnchor, chain::ConfirmationTimeHeightAnchor,
@@ -17,89 +20,102 @@ use crate::utils;
const STOP_GAP: usize = 50; const STOP_GAP: usize = 50;
const PARALLEL_REQUESTS: usize = 5; const PARALLEL_REQUESTS: usize = 5;
pub(crate) fn build_send_tx( pub struct EsploraWallet {
mut wallet: Wallet, wallet: Wallet,
faucet_address: Address, db: Store<KeychainKind, ConfirmationTimeHeightAnchor>,
amount: Amount, client: AsyncClient,
) -> Result<bitcoin::Transaction, anyhow::Error> {
let mut tx_builder = wallet.build_tx();
tx_builder
.add_recipient(faucet_address.script_pubkey(), amount)
.enable_rbf();
let mut psbt = tx_builder.finish()?;
let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
assert!(finalized);
let tx = psbt.extract_tx()?;
Ok(tx)
} }
pub(crate) async fn sync( impl EsploraWallet {
wallet: &mut Wallet, pub(crate) fn build_send_tx(
db: &mut Store<KeychainKind, ConfirmationTimeHeightAnchor>, &mut self,
) -> Result<esplora_client::AsyncClient, anyhow::Error> { faucet_address: Address,
print!("Syncing..."); amount: Amount,
let client = esplora_client::Builder::new("https://mutinynet.com/api") ) -> Result<bitcoin::Transaction, anyhow::Error> {
.build_async() let mut tx_builder = self.wallet.build_tx();
.expect("couldn't build esplora client"); tx_builder
fn generate_inspect(kind: KeychainKind) -> impl FnMut(u32, &Script) + Send + Sync + 'static { .add_recipient(faucet_address.script_pubkey(), amount)
let mut once = Some(()); .enable_rbf();
let mut stdout = std::io::stdout(); let mut psbt = tx_builder.finish()?;
move |spk_i, _| { let finalized = self.wallet.sign(&mut psbt, SignOptions::default())?;
match once.take() { assert!(finalized);
Some(_) => print!("\nScanning keychain [{:?}]", kind), let tx = psbt.extract_tx()?;
None => print!(" {:<3}", spk_i), Ok(tx)
};
stdout.flush().expect("must flush");
}
} }
let request = wallet
.start_full_scan() pub(crate) async fn sync(&mut self) -> Result<(), anyhow::Error> {
.inspect_spks_for_all_keychains({ print!("Syncing...");
let mut once = BTreeSet::<KeychainKind>::new();
move |keychain, spk_i, _| { fn generate_inspect(
match once.insert(keychain) { kind: KeychainKind,
true => print!("\nScanning keychain [{:?}]", keychain), ) -> impl FnMut(u32, &Script) + Send + Sync + 'static {
false => print!(" {:<3}", spk_i), let mut once = Some(());
} let mut stdout = std::io::stdout();
std::io::stdout().flush().expect("must flush") move |spk_i, _| {
match once.take() {
Some(_) => print!("\nScanning keychain [{:?}]", kind),
None => print!(" {:<3}", spk_i),
};
stdout.flush().expect("must flush");
} }
}) }
.inspect_spks_for_keychain( let request = self
KeychainKind::External, .wallet
generate_inspect(KeychainKind::External), .start_full_scan()
) .inspect_spks_for_all_keychains({
.inspect_spks_for_keychain( let mut once = BTreeSet::<KeychainKind>::new();
KeychainKind::Internal, move |keychain, spk_i, _| {
generate_inspect(KeychainKind::Internal), match once.insert(keychain) {
); true => print!("\nScanning keychain [{:?}]", keychain),
let mut update = client false => print!(" {:<3}", spk_i),
.full_scan(request, STOP_GAP, PARALLEL_REQUESTS) }
.await?; std::io::stdout().flush().expect("must flush")
let now = std::time::UNIX_EPOCH.elapsed().unwrap().as_secs(); }
let _ = update.graph_update.update_last_seen_unconfirmed(now); })
wallet.apply_update(update)?; .inspect_spks_for_keychain(
if let Some(changeset) = wallet.take_staged() { KeychainKind::External,
db.write(&changeset)?; generate_inspect(KeychainKind::External),
)
.inspect_spks_for_keychain(
KeychainKind::Internal,
generate_inspect(KeychainKind::Internal),
);
let mut update = self
.client
.full_scan(request, STOP_GAP, PARALLEL_REQUESTS)
.await?;
let now = std::time::UNIX_EPOCH.elapsed().unwrap().as_secs();
let _ = update.graph_update.update_last_seen_unconfirmed(now);
self.wallet.apply_update(update)?;
if let Some(changeset) = self.wallet.take_staged() {
self.db.write(&changeset)?;
}
println!();
Ok(())
}
pub(crate) fn next_unused_address(&mut self) -> Result<AddressInfo, anyhow::Error> {
let address = self.wallet.next_unused_address(KeychainKind::External);
if let Some(changeset) = self.wallet.take_staged() {
self.db.write(&changeset)?;
}
println!("Generated Address: {}", address);
Ok(address)
}
pub(crate) fn balance(&self) -> bdk_wallet::wallet::Balance {
self.wallet.balance()
}
pub(crate) async fn broadcast(
&self,
tx: &bitcoin::Transaction,
) -> Result<(), esplora_client::Error> {
self.client.broadcast(tx).await
} }
println!();
Ok(client)
} }
pub(crate) fn next_unused_address( pub(crate) fn create_wallet(name: &str) -> anyhow::Result<EsploraWallet> {
wallet: &mut Wallet,
db: &mut Store<KeychainKind, ConfirmationTimeHeightAnchor>,
) -> Result<AddressInfo, anyhow::Error> {
let address = wallet.next_unused_address(KeychainKind::External);
if let Some(changeset) = wallet.take_staged() {
db.write(&changeset)?;
}
println!("Generated Address: {}", address);
Ok(address)
}
pub(crate) fn create_wallet(
name: &str,
) -> anyhow::Result<(Wallet, Store<KeychainKind, ConfirmationTimeHeightAnchor>)> {
let keys_dir = utils::home(name); let keys_dir = utils::home(name);
let mnemonic_path = crate::utils::side_paths(keys_dir).1; // TODO: this tuple stinks let mnemonic_path = crate::utils::side_paths(keys_dir).1; // TODO: this tuple stinks
@@ -135,5 +151,11 @@ pub(crate) fn create_wallet(
) )
.expect("problem setting up wallet"); .expect("problem setting up wallet");
Ok((wallet, db)) let client = esplora_client::Builder::new("https://mutinynet.com/api")
.build_async()
.expect("couldn't build esplora client");
let esplora = EsploraWallet { wallet, db, client };
Ok(esplora)
} }

View File

@@ -11,14 +11,14 @@ use crate::bitcoin::clients;
/// Also, it very handily works with the mutinynet.com esplora server, which is configured /// Also, it very handily works with the mutinynet.com esplora server, which is configured
/// with 30 second block times. /// with 30 second block times.
pub(crate) async fn run() -> Result<(), anyhow::Error> { pub(crate) async fn run() -> Result<(), anyhow::Error> {
let (mut wallet, mut db) = clients::esplora::create_wallet("dave")?; let mut wallet = clients::esplora::create_wallet("dave")?;
let _next_address = clients::esplora::next_unused_address(&mut wallet, &mut db)?; let _next_address = wallet.next_unused_address()?;
let balance = wallet.balance(); let balance = wallet.balance();
println!("Wallet balance before syncing: {} sats", balance.total()); println!("Wallet balance before syncing: {} sats", balance.total());
let client = clients::esplora::sync(&mut wallet, &mut db).await?; wallet.sync().await?;
let balance = wallet.balance(); let balance = wallet.balance();
println!("Wallet balance after syncing: {} sats", balance.total()); println!("Wallet balance after syncing: {} sats", balance.total());
@@ -35,8 +35,9 @@ pub(crate) async fn run() -> Result<(), anyhow::Error> {
std::process::exit(0); std::process::exit(0);
} }
let tx = clients::esplora::build_send_tx(wallet, faucet_address, send_amount)?; let tx = wallet.build_send_tx(faucet_address, send_amount)?;
client.broadcast(&tx).await?; wallet.broadcast(&tx).await?;
println!("Tx broadcasted! Txid: {}", tx.compute_txid()); println!("Tx broadcasted! Txid: {}", tx.compute_txid());
Ok(()) Ok(())