2024-07-24 18:14:08 +01:00
|
|
|
use std::fs;
|
2024-06-21 17:00:01 +01:00
|
|
|
|
2024-06-24 18:41:55 +01:00
|
|
|
use bdk::keys::bip39::Mnemonic;
|
2024-06-25 14:58:13 +01:00
|
|
|
use bdk_esplora::{
|
|
|
|
|
esplora_client::{self, AsyncClient},
|
|
|
|
|
EsploraAsyncExt,
|
|
|
|
|
};
|
2024-06-21 17:00:01 +01:00
|
|
|
use bdk_wallet::{
|
2024-07-24 18:14:08 +01:00
|
|
|
bitcoin::{Address, Amount, Network},
|
2024-06-25 14:35:42 +01:00
|
|
|
chain::ConfirmationTimeHeightAnchor,
|
2024-06-24 18:41:55 +01:00
|
|
|
keys::{DerivableKey, ExtendedKey},
|
2024-06-25 14:35:42 +01:00
|
|
|
wallet::AddressInfo,
|
2024-06-21 17:00:01 +01:00
|
|
|
KeychainKind, SignOptions, Wallet,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
use bdk_sqlite::{rusqlite::Connection, Store};
|
|
|
|
|
|
2024-06-24 18:47:27 +01:00
|
|
|
use crate::utils;
|
2024-06-24 18:41:55 +01:00
|
|
|
|
2024-06-21 17:00:01 +01:00
|
|
|
const STOP_GAP: usize = 50;
|
|
|
|
|
const PARALLEL_REQUESTS: usize = 5;
|
|
|
|
|
|
2024-06-25 15:05:33 +01:00
|
|
|
/// A wallet that uses the Esplora client to interact with the Bitcoin network.
|
2024-06-25 14:58:13 +01:00
|
|
|
pub struct EsploraWallet {
|
|
|
|
|
client: AsyncClient,
|
2024-06-25 15:18:30 +01:00
|
|
|
db: Store<KeychainKind, ConfirmationTimeHeightAnchor>,
|
|
|
|
|
name: String,
|
|
|
|
|
wallet: Wallet,
|
2024-06-25 14:35:42 +01:00
|
|
|
}
|
2024-06-21 17:00:01 +01:00
|
|
|
|
2024-06-25 14:58:13 +01:00
|
|
|
impl EsploraWallet {
|
2024-06-25 15:02:50 +01:00
|
|
|
/// 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.
|
2024-06-25 17:32:44 +01:00
|
|
|
pub(crate) fn build_and_sign_send_tx(
|
2024-06-25 14:58:13 +01:00
|
|
|
&mut self,
|
2024-06-25 15:02:50 +01:00
|
|
|
recipient: Address,
|
2024-06-25 14:58:13 +01:00
|
|
|
amount: Amount,
|
|
|
|
|
) -> Result<bitcoin::Transaction, anyhow::Error> {
|
2024-07-25 12:34:26 +01:00
|
|
|
let mut tx_builder = self.build_tx()?;
|
2024-06-25 14:58:13 +01:00
|
|
|
tx_builder
|
2024-06-25 15:02:50 +01:00
|
|
|
.add_recipient(recipient.script_pubkey(), amount)
|
2024-06-25 14:58:13 +01:00
|
|
|
.enable_rbf();
|
|
|
|
|
let mut psbt = tx_builder.finish()?;
|
2024-07-25 12:34:26 +01:00
|
|
|
let tx = self.sign(&mut psbt, true)?.extract_tx()?;
|
2024-06-25 14:58:13 +01:00
|
|
|
Ok(tx)
|
2024-06-21 17:00:01 +01:00
|
|
|
}
|
2024-06-25 14:58:13 +01:00
|
|
|
|
2024-07-25 12:34:26 +01:00
|
|
|
pub(crate) fn build_tx(
|
|
|
|
|
&mut self,
|
|
|
|
|
) -> Result<
|
|
|
|
|
bdk_wallet::TxBuilder<bdk_wallet::wallet::coin_selection::BranchAndBoundCoinSelection>,
|
|
|
|
|
anyhow::Error,
|
|
|
|
|
> {
|
|
|
|
|
Ok(self.wallet.build_tx())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub(crate) fn sign(
|
|
|
|
|
&self,
|
|
|
|
|
psbt: &mut bitcoin::Psbt,
|
|
|
|
|
finalize: bool,
|
|
|
|
|
) -> Result<bitcoin::Psbt, anyhow::Error> {
|
|
|
|
|
tracing::info!("{} signing PSBT", self.name);
|
|
|
|
|
|
|
|
|
|
let options = SignOptions {
|
|
|
|
|
try_finalize: finalize,
|
|
|
|
|
..Default::default()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let finalized = self.wallet.sign(psbt, options)?;
|
|
|
|
|
|
|
|
|
|
// make sure the PSBT is finalized if we asked for it
|
|
|
|
|
if finalize {
|
|
|
|
|
assert!(finalized)
|
|
|
|
|
}
|
|
|
|
|
Ok(psbt.to_owned())
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-25 15:02:50 +01:00
|
|
|
/// Syncs the wallet with the latest state of the Bitcoin blockchain
|
2024-06-25 14:58:13 +01:00
|
|
|
pub(crate) async fn sync(&mut self) -> Result<(), anyhow::Error> {
|
2024-07-24 17:33:40 +01:00
|
|
|
tracing::info!("{} full scan sync start", self.name);
|
|
|
|
|
let request = self.wallet.start_full_scan();
|
2024-06-25 14:58:13 +01:00
|
|
|
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)?;
|
2024-06-25 15:23:52 +01:00
|
|
|
self.persist_local()?;
|
2024-07-24 17:33:40 +01:00
|
|
|
tracing::info!("{} sync complete", self.name);
|
2024-06-25 14:58:13 +01:00
|
|
|
Ok(())
|
2024-06-21 17:00:01 +01:00
|
|
|
}
|
|
|
|
|
|
2024-06-25 15:23:52 +01:00
|
|
|
fn persist_local(&mut self) -> Result<(), anyhow::Error> {
|
|
|
|
|
Ok(if let Some(changeset) = self.wallet.take_staged() {
|
|
|
|
|
self.db.write(&changeset)?;
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-25 15:02:50 +01:00
|
|
|
/// Gets the next unused address from the wallet.
|
2024-06-25 14:58:13 +01:00
|
|
|
pub(crate) fn next_unused_address(&mut self) -> Result<AddressInfo, anyhow::Error> {
|
|
|
|
|
let address = self.wallet.next_unused_address(KeychainKind::External);
|
2024-06-25 15:23:52 +01:00
|
|
|
self.persist_local()?;
|
2024-07-24 17:33:40 +01:00
|
|
|
tracing::info!(
|
2024-06-25 15:18:30 +01:00
|
|
|
"Generated address: https://mutinynet.com/address/{}",
|
|
|
|
|
address
|
|
|
|
|
);
|
2024-06-25 14:58:13 +01:00
|
|
|
Ok(address)
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-25 15:02:50 +01:00
|
|
|
/// Returns the balance of the wallet.
|
2024-06-25 14:58:13 +01:00
|
|
|
pub(crate) fn balance(&self) -> bdk_wallet::wallet::Balance {
|
2024-07-24 17:33:40 +01:00
|
|
|
tracing::info!(
|
|
|
|
|
"{}'s balance is {}",
|
|
|
|
|
self.name,
|
|
|
|
|
self.wallet.balance().total()
|
|
|
|
|
);
|
2024-06-25 14:58:13 +01:00
|
|
|
self.wallet.balance()
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-25 15:02:50 +01:00
|
|
|
/// Broadcasts a signed transaction to the network.
|
2024-06-25 14:58:13 +01:00
|
|
|
pub(crate) async fn broadcast(
|
|
|
|
|
&self,
|
|
|
|
|
tx: &bitcoin::Transaction,
|
|
|
|
|
) -> Result<(), esplora_client::Error> {
|
2024-07-24 17:33:40 +01:00
|
|
|
tracing::info!(
|
2024-06-25 15:18:30 +01:00
|
|
|
"{} broadcasting tx https://mutinynet.com/tx/{}",
|
|
|
|
|
self.name,
|
|
|
|
|
tx.compute_txid()
|
|
|
|
|
);
|
2024-06-25 14:58:13 +01:00
|
|
|
self.client.broadcast(tx).await
|
2024-06-21 17:00:01 +01:00
|
|
|
}
|
2024-07-25 12:34:26 +01:00
|
|
|
|
|
|
|
|
pub(crate) fn wallet(&mut self) -> &Wallet {
|
|
|
|
|
&self.wallet
|
|
|
|
|
}
|
2024-06-25 14:35:42 +01:00
|
|
|
}
|
2024-06-21 17:00:01 +01:00
|
|
|
|
2024-06-25 15:05:33 +01:00
|
|
|
/// 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> {
|
2024-06-25 14:35:42 +01:00
|
|
|
let keys_dir = utils::home(name);
|
2024-06-21 17:00:01 +01:00
|
|
|
|
2024-06-25 14:35:42 +01:00
|
|
|
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");
|
2024-06-21 17:00:01 +01:00
|
|
|
|
2024-07-24 17:33:40 +01:00
|
|
|
tracing::info!("Creating {name}'s wallet from mnemonic: {mnemonic_words}");
|
2024-06-25 14:35:42 +01:00
|
|
|
let mnemonic = Mnemonic::parse(mnemonic_words).unwrap();
|
2024-06-21 17:00:01 +01:00
|
|
|
|
2024-06-25 14:35:42 +01:00
|
|
|
// Generate the extended key
|
|
|
|
|
let xkey: ExtendedKey = mnemonic
|
|
|
|
|
.into_extended_key()
|
|
|
|
|
.expect("couldn't turn mnemonic into xkey");
|
2024-06-21 17:00:01 +01:00
|
|
|
|
2024-06-25 14:35:42 +01:00
|
|
|
let xprv = xkey
|
|
|
|
|
.into_xprv(Network::Signet)
|
|
|
|
|
.expect("problem converting xkey to xprv")
|
|
|
|
|
.to_string();
|
|
|
|
|
|
2024-07-24 17:33:40 +01:00
|
|
|
tracing::info!("Setting up esplora database for {name}");
|
2024-06-25 14:35:42 +01:00
|
|
|
|
|
|
|
|
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,
|
2024-06-25 15:05:33 +01:00
|
|
|
network,
|
2024-06-25 14:35:42 +01:00
|
|
|
)
|
|
|
|
|
.expect("problem setting up wallet");
|
|
|
|
|
|
2024-06-25 14:58:13 +01:00
|
|
|
let client = esplora_client::Builder::new("https://mutinynet.com/api")
|
|
|
|
|
.build_async()
|
|
|
|
|
.expect("couldn't build esplora client");
|
|
|
|
|
|
2024-06-25 15:18:30 +01:00
|
|
|
let esplora = EsploraWallet {
|
|
|
|
|
name: name.to_string(),
|
|
|
|
|
wallet,
|
|
|
|
|
db,
|
|
|
|
|
client,
|
|
|
|
|
};
|
2024-06-25 14:58:13 +01:00
|
|
|
|
|
|
|
|
Ok(esplora)
|
2024-06-20 19:46:56 +01:00
|
|
|
}
|