Starting a refactor into more functional modules

This commit is contained in:
Dave Hrycyszyn
2024-06-25 13:31:02 +01:00
parent d4809a48e6
commit 037fc27b7b
14 changed files with 54 additions and 21 deletions

View File

@@ -0,0 +1,101 @@
use crate::{ utils, bitcoin};
use bdk::bitcoin::psbt::PartiallySignedTransaction;
use bdk::bitcoin::Network;
use bdk::database::MemoryDatabase;
use bdk::keys::ExtendedKey;
use bdk::template::Bip84;
use bdk::wallet::AddressIndex::{self, New};
use bdk::wallet::AddressInfo;
use bdk::{blockchain::ElectrumBlockchain, electrum_client, SyncOptions};
use bdk::{FeeRate, KeychainKind, SignOptions, TransactionDetails, Wallet};
/// Run the Bitcoin wallet example
///
/// This is a bdk example that uses the Electrum client to interact with the Bitcoin network.
/// Electrum is a light client that connects to a server to get information about the Bitcoin network.
/// The BDK itself does not have the ability to connect to e.g. esplora servers. As the Blockstream Electrum Signet
/// server does not appear to be picking up transactions properly at the moment, I've shifted over to using
/// the (more complex) `bdk_wallet` crate and the esplora client there (see the other RPC client).
///
/// Note:the types below are all completely different than the types in `bdk_wallet`.
pub async fn run() -> Result<(), anyhow::Error> {
let dave = utils::home(&"dave".to_string());
let sammy = utils::home(&"sammy".to_string());
let dave_key = bitcoin::bitcoin_keys::load_from_file(&dave).unwrap();
let sammy_key = bitcoin::bitcoin_keys::load_from_file(&sammy).unwrap();
let dave_wallet = create_wallet(dave_key)?;
let sammy_wallet = create_wallet(sammy_key)?;
let dave_address = dave_wallet.get_address(AddressIndex::Peek(0))?.to_string();
let sammy_address = sammy_wallet.get_address(AddressIndex::Peek(0))?.to_string();
println!("Dave's address: {}", dave_address);
println!("Sammy's address: {}", sammy_address);
let blockchain = ElectrumBlockchain::from(electrum_client::Client::new(
"ssl://electrum.blockstream.info:60002",
)?);
println!("Syncing...");
dave_wallet.sync(&blockchain, SyncOptions::default())?;
display_balance(&dave_wallet);
display_balance(&sammy_wallet);
let (mut psbt, details) =
build_sending_tx(&dave_wallet, sammy_wallet.get_address(New)?).expect("psbt build error");
println!("About to sign the transaction: {:?}", details);
dave_wallet.sign(&mut psbt, SignOptions::default())?;
let _signed_tx = psbt.extract_tx();
// println!("Broadcasting...");
// blockchain.broadcast(&signed_tx).expect("broadcast error");
// println!("Transaction ID: {:?}", signed_tx.txid());
Ok(())
}
/// Create a BDK wallet using BIP 84 descriptor ("m/84h/1h/0h/0" and "m/84h/1h/0h/1")
pub fn create_wallet(xkey: ExtendedKey) -> anyhow::Result<Wallet<MemoryDatabase>> {
let xprv = xkey
.into_xprv(Network::Testnet)
.expect("couldn't turn xkey into xprv");
let external_descriptor = Bip84(xprv, KeychainKind::External);
let internal_descriptor = Some(Bip84(xprv, KeychainKind::Internal));
let wallet = Wallet::new(
external_descriptor,
internal_descriptor,
Network::Testnet,
MemoryDatabase::default(),
)?;
Ok(wallet)
}
fn display_balance(wallet: &Wallet<MemoryDatabase>) {
println!(
"Wallet balance for {} after syncing: {:?} sats on network {}",
wallet
.get_address(bdk::wallet::AddressIndex::Peek(0))
.expect("couldn't get address"),
wallet.get_balance().expect("couldn't show balance"),
wallet.network(),
);
}
fn build_sending_tx(
wallet: &Wallet<MemoryDatabase>,
recipient: AddressInfo,
) -> anyhow::Result<(PartiallySignedTransaction, TransactionDetails), anyhow::Error> {
let mut builder = wallet.build_tx();
builder
.add_recipient(recipient.script_pubkey(), 1000)
.enable_rbf()
.do_not_spend_change()
.fee_rate(FeeRate::from_sat_per_vb(7.0));
Ok(builder.finish()?)
}

View File

@@ -0,0 +1,147 @@
use std::{collections::BTreeSet, fs, io::Write, str::FromStr};
use bdk::keys::bip39::Mnemonic;
use bdk_esplora::{esplora_client, EsploraAsyncExt};
use bdk_wallet::{
bitcoin::{Address, Amount, Network, Script},
keys::{DerivableKey, ExtendedKey},
KeychainKind, SignOptions, Wallet,
};
use bdk_sqlite::{rusqlite::Connection, Store};
use crate::utils;
const SEND_AMOUNT: Amount = Amount::from_sat(5000);
const STOP_GAP: usize = 50;
const PARALLEL_REQUESTS: usize = 5;
/// Demonstrates the use of bdk with the Esplora client.
///
/// This is more complex than the bare `bdk` crate, but the esplora client works.
///
/// Also, it very nadily works with the mutinynet.com esplora server, which is configured
/// with 30 second block times.
pub async fn run() -> Result<(), anyhow::Error> {
let dave_dir = utils::home(&"dave".to_string());
let mnemonic_path = crate::utils::side_paths(dave_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");
let db_path = "/tmp/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 mut wallet = Wallet::new_or_load(
&external_descriptor,
&internal_descriptor,
changeset,
Network::Signet,
)
.expect("problem setting up wallet");
let address = wallet.next_unused_address(KeychainKind::External);
if let Some(changeset) = wallet.take_staged() {
db.write(&changeset)?;
}
println!("Generated Address: {}", address);
let balance = wallet.balance();
println!("Wallet balance before syncing: {} sats", balance.total());
print!("Syncing...");
let client = esplora_client::Builder::new("https://mutinynet.com/api")
.build_async()
.expect("couldn't build esplora client");
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 = 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 = 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);
wallet.apply_update(update)?;
if let Some(changeset) = wallet.take_staged() {
db.write(&changeset)?;
}
println!();
let balance = wallet.balance();
println!("Wallet balance after syncing: {} sats", balance.total());
if balance.total() < SEND_AMOUNT {
println!(
"Please send at least {} sats to the receiving address",
SEND_AMOUNT
);
std::process::exit(0);
}
let faucet_address = Address::from_str("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt")?
.require_network(Network::Signet)?;
let mut tx_builder = wallet.build_tx();
tx_builder
.add_recipient(faucet_address.script_pubkey(), SEND_AMOUNT)
.enable_rbf();
let mut psbt = tx_builder.finish()?;
let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
assert!(finalized);
let tx = psbt.extract_tx()?;
client.broadcast(&tx).await?;
println!("Tx broadcasted! Txid: {}", tx.compute_txid());
Ok(())
}

View File

@@ -0,0 +1,2 @@
pub mod btc_electrum_client;
pub mod btc_esplora_client;