Files
bft-crdt-experiment/side-node/src/bitcoin/driver.rs
2024-07-25 12:34:26 +01:00

90 lines
2.7 KiB
Rust

use crate::bitcoin::clients;
use bdk_wallet::bitcoin::{Amount, Network};
use tracing_subscriber::filter::EnvFilter;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, layer::SubscriberExt};
use super::clients::esplora::EsploraWallet;
pub(crate) async fn simple_transfer() -> Result<(), anyhow::Error> {
let (mut dave, mut sammy) = setup().await?;
let send_amount = Amount::from_sat(500);
ensure_enough_sats(&dave, send_amount);
let sammy_address = sammy.next_unused_address()?.address;
let tx = dave.build_and_sign_send_tx(sammy_address, send_amount)?;
dave.broadcast(&tx).await?;
Ok(())
}
async fn setup() -> Result<(EsploraWallet, EsploraWallet), anyhow::Error> {
tracing_setup();
let mut dave = clients::esplora::create_wallet("dave", Network::Signet)?;
let mut sammy = clients::esplora::create_wallet("sammy", Network::Signet)?;
let _ = dave.balance();
dave.sync().await?;
let _ = dave.balance();
let _sammy = sammy.balance();
sammy.sync().await?;
let _ = sammy.balance();
Ok((dave, sammy))
}
/// Exit if the wallet does not have enough sats to send.
fn ensure_enough_sats(wallet: &EsploraWallet, send_amount: bitcoin::Amount) {
if wallet.balance().total() < send_amount {
tracing::error!(
"Please send at least {} sats to the receiving address. Exiting.",
send_amount
);
std::process::exit(0);
}
}
pub(crate) async fn htlc() -> anyhow::Result<()> {
let (mut dave, mut sammy) = setup().await?;
// format a new commitment transaction like in Lightning
let mut commitment_builder = dave.build_tx()?;
let amount = Amount::from_sat(500);
let recipient = sammy.next_unused_address()?.script_pubkey();
commitment_builder.add_recipient(recipient, amount);
commitment_builder.enable_rbf();
let psbt = commitment_builder
.finish()
.expect("unable to build commitment");
// sign the commitment transaction
let mut dave_psbt = dave.sign(&mut psbt.clone(), false)?;
let sammy_psbt = sammy.sign(&mut psbt.clone(), false)?;
dave_psbt
.combine(sammy_psbt)
.expect("problem combining bitcoin PSBTs"); // these guys love mutability
let finalized = dave
.wallet()
.finalize_psbt(&mut dave_psbt, bdk_wallet::SignOptions::default())
.expect("couldn't finalize");
assert!(finalized);
let tx = dave_psbt.extract_tx()?;
let _ = dave.broadcast(&tx).await.expect("couldn't broadcast");
let _ = sammy.sync();
sammy.balance();
Ok(())
}
fn tracing_setup() {
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env())
.init();
tracing::info!("Tracing initialized.");
}