Files
bft-crdt-experiment/crdt-node/src/bitcoin/clients/esplora.rs
2024-10-19 16:50:45 +01:00

189 lines
6.1 KiB
Rust

use std::{collections::BTreeSet, fs, io::Write};
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;
/// A wallet that uses the Esplora client to interact with the Bitcoin network.
pub struct EsploraWallet {
client: AsyncClient,
db: Store<KeychainKind, ConfirmationTimeHeightAnchor>,
name: String,
wallet: Wallet,
}
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_and_sign_send_tx(
&mut self,
recipient: Address,
amount: Amount,
) -> Result<bitcoin::Transaction, anyhow::Error> {
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::<KeychainKind>::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)?;
self.persist_local()?;
println!("Sync complete for {}", self.name);
Ok(())
}
fn persist_local(&mut self) -> Result<(), anyhow::Error> {
Ok(if let Some(changeset) = self.wallet.take_staged() {
self.db.write(&changeset)?;
})
}
/// Gets the next unused address from the wallet.
pub(crate) fn next_unused_address(&mut self) -> Result<AddressInfo, anyhow::Error> {
let address = self.wallet.next_unused_address(KeychainKind::External);
self.persist_local()?;
println!(
"Generated address: https://mutinynet.com/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> {
println!(
"{} broadcasting tx https://mutinynet.com/tx/{}",
self.name,
tx.compute_txid()
);
self.client.broadcast(tx).await
}
}
/// Creates a Bitcoin descriptor wallet with the mnemonic in the given user directory.
pub(crate) fn create_wallet(name: &str, network: Network) -> anyhow::Result<EsploraWallet> {
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,
)
.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 {
name: name.to_string(),
wallet,
db,
client,
};
Ok(esplora)
}