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,31 +20,35 @@ use crate::utils;
const STOP_GAP: usize = 50; const STOP_GAP: usize = 50;
const PARALLEL_REQUESTS: usize = 5; const PARALLEL_REQUESTS: usize = 5;
pub struct EsploraWallet {
wallet: Wallet,
db: Store<KeychainKind, ConfirmationTimeHeightAnchor>,
client: AsyncClient,
}
impl EsploraWallet {
pub(crate) fn build_send_tx( pub(crate) fn build_send_tx(
mut wallet: Wallet, &mut self,
faucet_address: Address, faucet_address: Address,
amount: Amount, amount: Amount,
) -> Result<bitcoin::Transaction, anyhow::Error> { ) -> Result<bitcoin::Transaction, anyhow::Error> {
let mut tx_builder = wallet.build_tx(); let mut tx_builder = self.wallet.build_tx();
tx_builder tx_builder
.add_recipient(faucet_address.script_pubkey(), amount) .add_recipient(faucet_address.script_pubkey(), amount)
.enable_rbf(); .enable_rbf();
let mut psbt = tx_builder.finish()?; let mut psbt = tx_builder.finish()?;
let finalized = wallet.sign(&mut psbt, SignOptions::default())?; let finalized = self.wallet.sign(&mut psbt, SignOptions::default())?;
assert!(finalized); assert!(finalized);
let tx = psbt.extract_tx()?; let tx = psbt.extract_tx()?;
Ok(tx) Ok(tx)
} }
pub(crate) async fn sync( pub(crate) async fn sync(&mut self) -> Result<(), anyhow::Error> {
wallet: &mut Wallet,
db: &mut Store<KeychainKind, ConfirmationTimeHeightAnchor>,
) -> Result<esplora_client::AsyncClient, anyhow::Error> {
print!("Syncing..."); print!("Syncing...");
let client = esplora_client::Builder::new("https://mutinynet.com/api")
.build_async() fn generate_inspect(
.expect("couldn't build esplora client"); kind: KeychainKind,
fn generate_inspect(kind: KeychainKind) -> impl FnMut(u32, &Script) + Send + Sync + 'static { ) -> impl FnMut(u32, &Script) + Send + Sync + 'static {
let mut once = Some(()); let mut once = Some(());
let mut stdout = std::io::stdout(); let mut stdout = std::io::stdout();
move |spk_i, _| { move |spk_i, _| {
@@ -52,7 +59,8 @@ pub(crate) async fn sync(
stdout.flush().expect("must flush"); stdout.flush().expect("must flush");
} }
} }
let request = wallet let request = self
.wallet
.start_full_scan() .start_full_scan()
.inspect_spks_for_all_keychains({ .inspect_spks_for_all_keychains({
let mut once = BTreeSet::<KeychainKind>::new(); let mut once = BTreeSet::<KeychainKind>::new();
@@ -72,34 +80,42 @@ pub(crate) async fn sync(
KeychainKind::Internal, KeychainKind::Internal,
generate_inspect(KeychainKind::Internal), generate_inspect(KeychainKind::Internal),
); );
let mut update = client let mut update = self
.client
.full_scan(request, STOP_GAP, PARALLEL_REQUESTS) .full_scan(request, STOP_GAP, PARALLEL_REQUESTS)
.await?; .await?;
let now = std::time::UNIX_EPOCH.elapsed().unwrap().as_secs(); let now = std::time::UNIX_EPOCH.elapsed().unwrap().as_secs();
let _ = update.graph_update.update_last_seen_unconfirmed(now); let _ = update.graph_update.update_last_seen_unconfirmed(now);
wallet.apply_update(update)?; self.wallet.apply_update(update)?;
if let Some(changeset) = wallet.take_staged() { if let Some(changeset) = self.wallet.take_staged() {
db.write(&changeset)?; self.db.write(&changeset)?;
} }
println!(); println!();
Ok(client) Ok(())
} }
pub(crate) fn next_unused_address( pub(crate) fn next_unused_address(&mut self) -> Result<AddressInfo, anyhow::Error> {
wallet: &mut Wallet, let address = self.wallet.next_unused_address(KeychainKind::External);
db: &mut Store<KeychainKind, ConfirmationTimeHeightAnchor>, if let Some(changeset) = self.wallet.take_staged() {
) -> Result<AddressInfo, anyhow::Error> { self.db.write(&changeset)?;
let address = wallet.next_unused_address(KeychainKind::External);
if let Some(changeset) = wallet.take_staged() {
db.write(&changeset)?;
} }
println!("Generated Address: {}", address); println!("Generated Address: {}", address);
Ok(address) Ok(address)
} }
pub(crate) fn create_wallet( pub(crate) fn balance(&self) -> bdk_wallet::wallet::Balance {
name: &str, self.wallet.balance()
) -> anyhow::Result<(Wallet, Store<KeychainKind, ConfirmationTimeHeightAnchor>)> { }
pub(crate) async fn broadcast(
&self,
tx: &bitcoin::Transaction,
) -> Result<(), esplora_client::Error> {
self.client.broadcast(tx).await
}
}
pub(crate) fn create_wallet(name: &str) -> anyhow::Result<EsploraWallet> {
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(())