use std::{collections::BTreeSet, fs, io::Write, str::FromStr}; use bdk::keys::bip39::Mnemonic; use bdk_esplora::{ esplora_client::{self, AsyncClient}, EsploraAsyncExt, }; use bdk_wallet::{ bitcoin::{Address, Amount, Network, Script}, chain::ConfirmationTimeHeightAnchor, keys::{DerivableKey, ExtendedKey}, wallet::AddressInfo, KeychainKind, SignOptions, Wallet, }; use bdk_sqlite::{rusqlite::Connection, Store}; use crate::utils; const STOP_GAP: usize = 50; const PARALLEL_REQUESTS: usize = 5; pub struct EsploraWallet { wallet: Wallet, db: Store, client: AsyncClient, } impl EsploraWallet { /// Builds and signs a send transaction to send coins between addresses. /// /// Does NOT send it, you must call `broadcast` to do that. /// /// We could split the creation and signing easily if needed. pub(crate) fn build_send_tx( &mut self, recipient: Address, amount: Amount, ) -> Result { let mut tx_builder = self.wallet.build_tx(); tx_builder .add_recipient(recipient.script_pubkey(), amount) .enable_rbf(); let mut psbt = tx_builder.finish()?; let finalized = self.wallet.sign(&mut psbt, SignOptions::default())?; assert!(finalized); let tx = psbt.extract_tx()?; Ok(tx) } /// Syncs the wallet with the latest state of the Bitcoin blockchain pub(crate) async fn sync(&mut self) -> Result<(), anyhow::Error> { print!("Syncing..."); fn generate_inspect( kind: KeychainKind, ) -> impl FnMut(u32, &Script) + Send + Sync + 'static { let mut once = Some(()); let mut stdout = std::io::stdout(); move |spk_i, _| { match once.take() { Some(_) => print!("\nScanning keychain [{:?}]", kind), None => print!(" {:<3}", spk_i), }; stdout.flush().expect("must flush"); } } let request = self .wallet .start_full_scan() .inspect_spks_for_all_keychains({ let mut once = BTreeSet::::new(); move |keychain, spk_i, _| { match once.insert(keychain) { true => print!("\nScanning keychain [{:?}]", keychain), false => print!(" {:<3}", spk_i), } std::io::stdout().flush().expect("must flush") } }) .inspect_spks_for_keychain( KeychainKind::External, 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(()) } /// Gets the next unused address from the wallet. pub(crate) fn next_unused_address(&mut self) -> Result { 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) } /// Returns the balance of the wallet. pub(crate) fn balance(&self) -> bdk_wallet::wallet::Balance { self.wallet.balance() } /// Broadcasts a signed transaction to the network. pub(crate) async fn broadcast( &self, tx: &bitcoin::Transaction, ) -> Result<(), esplora_client::Error> { self.client.broadcast(tx).await } } /// Creates a Bitcoin Signet descriptor wallet with the mnemonic in the given user directory. pub(crate) fn create_wallet(name: &str) -> anyhow::Result { let keys_dir = utils::home(name); let mnemonic_path = crate::utils::side_paths(keys_dir).1; // TODO: this tuple stinks let mnemonic_words = fs::read_to_string(mnemonic_path).expect("couldn't read bitcoin key file"); println!("Creating wallet from mnemonic: {mnemonic_words}"); let mnemonic = Mnemonic::parse(mnemonic_words).unwrap(); // Generate the extended key let xkey: ExtendedKey = mnemonic .into_extended_key() .expect("couldn't turn mnemonic into xkey"); let xprv = xkey .into_xprv(Network::Signet) .expect("problem converting xkey to xprv") .to_string(); println!("Setting up esplora database for {name}"); let db_path = format!("/tmp/{name}-bdk-esplora-async-example.sqlite"); let conn = Connection::open(db_path)?; let mut db = Store::new(conn)?; let external_descriptor = format!("wpkh({xprv}/84'/1'/0'/0/*)"); let internal_descriptor = format!("wpkh({xprv}/84'/1'/0'/1/*)"); let changeset = db.read().expect("couldn't read esplora database"); let wallet = Wallet::new_or_load( &external_descriptor, &internal_descriptor, changeset, Network::Signet, ) .expect("problem setting up wallet"); 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) }