feat: expose new methods on txbuilder

This commit is contained in:
thunderbiscuit 2023-11-15 10:31:29 -05:00
parent e79ce98295
commit 787152e0b4
No known key found for this signature in database
GPG Key ID: 88253696EB836462
6 changed files with 184 additions and 116 deletions

View File

@ -15,6 +15,8 @@ class LiveWalletTest {
val update = esploraClient.scan(wallet, 10uL, 1uL)
wallet.applyUpdate(update)
println("Balance: ${wallet.getBalance().total()}")
val balance: Balance = wallet.getBalance()
println("Balance: $balance")
assert(wallet.getBalance().total() > 0uL)
}

View File

@ -1,6 +1,7 @@
package org.bitcoindevkit
import kotlin.test.Test
import kotlin.test.assertEquals
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.runner.RunWith
import kotlin.test.assertEquals

View File

@ -43,6 +43,12 @@ enum BdkError {
"Psbt",
};
enum ChangeSpendPolicy {
"ChangeAllowed",
"OnlyChange",
"ChangeForbidden"
};
interface Balance {
u64 immature();
@ -95,8 +101,24 @@ interface TxBuilder {
TxBuilder add_recipient(Script script, u64 amount);
TxBuilder set_recipients(sequence<ScriptAmount> script_amount);
TxBuilder add_unspendable(OutPoint unspendable);
TxBuilder add_utxo(OutPoint outpoint);
TxBuilder change_policy(ChangeSpendPolicy change_policy);
TxBuilder do_not_spend_change();
TxBuilder only_spend_change();
TxBuilder manually_selected_only();
TxBuilder fee_rate(float sat_per_vbyte);
TxBuilder drain_wallet();
[Throws=BdkError]
PartiallySignedTransaction finish([ByRef] Wallet wallet);
};
@ -198,6 +220,15 @@ interface EsploraClient {
Update scan(Wallet wallet, u64 stop_gap, u64 parallel_requests);
};
// ------------------------------------------------------------------------
// bdk-ffi-defined types
// ------------------------------------------------------------------------
dictionary ScriptAmount {
Script script;
u64 amount;
};
// ------------------------------------------------------------------------
// bdk crate - bitcoin re-exports
// ------------------------------------------------------------------------
@ -263,3 +294,8 @@ interface PartiallySignedTransaction {
Transaction extract_tx();
};
dictionary OutPoint {
string txid;
u32 vout;
};

View File

@ -4,7 +4,9 @@ use bdk::bitcoin::consensus::Decodable;
use bdk::bitcoin::network::constants::Network as BdkNetwork;
use bdk::bitcoin::psbt::PartiallySignedTransaction as BdkPartiallySignedTransaction;
use bdk::bitcoin::Address as BdkAddress;
use bdk::bitcoin::OutPoint as BdkOutPoint;
use bdk::bitcoin::Transaction as BdkTransaction;
use bdk::bitcoin::Txid;
use bdk::Error as BdkError;
use std::io::Cursor;
@ -283,3 +285,21 @@ impl From<BdkPartiallySignedTransaction> for PartiallySignedTransaction {
}
}
}
/// A reference to a transaction output.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct OutPoint {
/// The referenced transaction's txid.
pub txid: String,
/// The index of the referenced output in its transaction's vout.
pub vout: u32,
}
impl From<&OutPoint> for BdkOutPoint {
fn from(outpoint: &OutPoint) -> Self {
BdkOutPoint {
txid: Txid::from_str(&outpoint.txid).unwrap(),
vout: outpoint.vout,
}
}
}

View File

@ -7,6 +7,7 @@ mod wallet;
// TODO 6: Why are these imports required?
use crate::bitcoin::Address;
use crate::bitcoin::Network;
use crate::bitcoin::OutPoint;
use crate::bitcoin::PartiallySignedTransaction;
use crate::bitcoin::Script;
use crate::bitcoin::Transaction;
@ -21,6 +22,7 @@ use crate::wallet::Update;
use crate::wallet::Wallet;
use bdk::keys::bip39::WordCount;
use bdk::wallet::tx_builder::ChangeSpendPolicy;
use bdk::wallet::AddressIndex as BdkAddressIndex;
use bdk::wallet::AddressInfo as BdkAddressInfo;
use bdk::wallet::Balance as BdkBalance;
@ -32,10 +34,10 @@ use std::sync::Arc;
uniffi::include_scaffolding!("bdk");
/// A output script and an amount of satoshis.
// pub struct ScriptAmount {
// pub script: Arc<Script>,
// pub amount: u64,
// }
pub struct ScriptAmount {
pub script: Arc<Script>,
pub amount: u64,
}
/// A derived address and the index it was found at.
pub struct AddressInfo {

View File

@ -1,13 +1,16 @@
use crate::bitcoin::PartiallySignedTransaction;
use crate::bitcoin::{OutPoint, PartiallySignedTransaction};
use crate::descriptor::Descriptor;
use crate::{AddressIndex, AddressInfo, Network};
use crate::{AddressIndex, AddressInfo, Network, ScriptAmount};
use crate::{Balance, Script};
use std::collections::HashSet;
use bdk::bitcoin::blockdata::script::ScriptBuf as BdkScriptBuf;
use bdk::bitcoin::OutPoint as BdkOutPoint;
use bdk::wallet::Update as BdkUpdate;
use bdk::Wallet as BdkWallet;
use bdk::{Error as BdkError, FeeRate};
use bdk::wallet::tx_builder::ChangeSpendPolicy;
use std::sync::{Arc, Mutex, MutexGuard};
#[derive(Debug)]
@ -261,13 +264,13 @@ pub struct Update(pub(crate) BdkUpdate);
#[derive(Clone, Debug)]
pub struct TxBuilder {
pub(crate) recipients: Vec<(BdkScriptBuf, u64)>,
// pub(crate) utxos: Vec<OutPoint>,
// pub(crate) unspendable: HashSet<OutPoint>,
// pub(crate) change_policy: ChangeSpendPolicy,
// pub(crate) manually_selected_only: bool,
pub(crate) utxos: Vec<OutPoint>,
pub(crate) unspendable: HashSet<OutPoint>,
pub(crate) change_policy: ChangeSpendPolicy,
pub(crate) manually_selected_only: bool,
pub(crate) fee_rate: Option<f32>,
// pub(crate) fee_absolute: Option<u64>,
// pub(crate) drain_wallet: bool,
pub(crate) drain_wallet: bool,
// pub(crate) drain_to: Option<BdkScript>,
// pub(crate) rbf: Option<RbfValue>,
// pub(crate) data: Vec<u8>,
@ -277,13 +280,13 @@ impl TxBuilder {
pub(crate) fn new() -> Self {
TxBuilder {
recipients: Vec::new(),
// utxos: Vec::new(),
// unspendable: HashSet::new(),
// change_policy: ChangeSpendPolicy::ChangeAllowed,
// manually_selected_only: false,
utxos: Vec::new(),
unspendable: HashSet::new(),
change_policy: ChangeSpendPolicy::ChangeAllowed,
manually_selected_only: false,
fee_rate: None,
// fee_absolute: None,
// drain_wallet: false,
drain_wallet: false,
// drain_to: None,
// rbf: None,
// data: Vec::new(),
@ -301,71 +304,78 @@ impl TxBuilder {
})
}
// pub(crate) fn set_recipients(&self, recipients: Vec<ScriptAmount>) -> Arc<Self> {
// let recipients = recipients
// .iter()
// .map(|script_amount| (script_amount.script.inner.clone(), script_amount.amount))
// .collect();
// Arc::new(TxBuilder {
// recipients,
// ..self.clone()
// })
// }
pub(crate) fn set_recipients(&self, recipients: Vec<ScriptAmount>) -> Arc<Self> {
let recipients = recipients
.iter()
.map(|script_amount| (script_amount.script.0.clone(), script_amount.amount))
.collect();
Arc::new(TxBuilder {
recipients,
..self.clone()
})
}
/// Add a utxo to the internal list of unspendable utxos. Its important to note that the "must-be-spent"
/// utxos added with [TxBuilder.addUtxo] have priority over this. See the Rust docs of the two linked methods for more details.
pub(crate) fn add_unspendable(&self, unspendable: OutPoint) -> Arc<Self> {
let mut unspendable_hash_set = self.unspendable.clone();
unspendable_hash_set.insert(unspendable);
Arc::new(TxBuilder {
unspendable: unspendable_hash_set,
..self.clone()
})
}
/// Add an outpoint to the internal list of UTXOs that must be spent. These have priority over the "unspendable"
/// utxos, meaning that if a utxo is present both in the "utxos" and the "unspendable" list, it will be spent.
pub(crate) fn add_utxo(&self, outpoint: OutPoint) -> Arc<Self> {
self.add_utxos(vec![outpoint])
}
/// Add the list of outpoints to the internal list of UTXOs that must be spent. If an error occurs while adding
/// any of the UTXOs then none of them are added and the error is returned. These have priority over the "unspendable"
/// utxos, meaning that if a utxo is present both in the "utxos" and the "unspendable" list, it will be spent.
pub(crate) fn add_utxos(&self, mut outpoints: Vec<OutPoint>) -> Arc<Self> {
let mut utxos = self.utxos.to_vec();
utxos.append(&mut outpoints);
Arc::new(TxBuilder {
utxos,
..self.clone()
})
}
pub(crate) fn change_policy(&self, change_policy: ChangeSpendPolicy) -> Arc<Self> {
Arc::new(TxBuilder {
change_policy,
..self.clone()
})
}
/// Do not spend change outputs. This effectively adds all the change outputs to the "unspendable" list. See TxBuilder.unspendable.
pub(crate) fn do_not_spend_change(&self) -> Arc<Self> {
Arc::new(TxBuilder {
change_policy: ChangeSpendPolicy::ChangeForbidden,
..self.clone()
})
}
/// Only spend change outputs. This effectively adds all the non-change outputs to the "unspendable" list. See TxBuilder.unspendable.
pub(crate) fn only_spend_change(&self) -> Arc<Self> {
Arc::new(TxBuilder {
change_policy: ChangeSpendPolicy::OnlyChange,
..self.clone()
})
}
/// Only spend utxos added by [add_utxo]. The wallet will not add additional utxos to the transaction even if they are
/// needed to make the transaction valid.
pub(crate) fn manually_selected_only(&self) -> Arc<Self> {
Arc::new(TxBuilder {
manually_selected_only: true,
..self.clone()
})
}
// /// Add a utxo to the internal list of unspendable utxos. Its important to note that the "must-be-spent"
// /// utxos added with [TxBuilder.addUtxo] have priority over this. See the Rust docs of the two linked methods for more details.
// pub(crate) fn add_unspendable(&self, unspendable: OutPoint) -> Arc<Self> {
// let mut unspendable_hash_set = self.unspendable.clone();
// unspendable_hash_set.insert(unspendable);
// Arc::new(TxBuilder {
// unspendable: unspendable_hash_set,
// ..self.clone()
// })
// }
//
// /// Add an outpoint to the internal list of UTXOs that must be spent. These have priority over the "unspendable"
// /// utxos, meaning that if a utxo is present both in the "utxos" and the "unspendable" list, it will be spent.
// pub(crate) fn add_utxo(&self, outpoint: OutPoint) -> Arc<Self> {
// self.add_utxos(vec![outpoint])
// }
//
// /// Add the list of outpoints to the internal list of UTXOs that must be spent. If an error occurs while adding
// /// any of the UTXOs then none of them are added and the error is returned. These have priority over the "unspendable"
// /// utxos, meaning that if a utxo is present both in the "utxos" and the "unspendable" list, it will be spent.
// pub(crate) fn add_utxos(&self, mut outpoints: Vec<OutPoint>) -> Arc<Self> {
// let mut utxos = self.utxos.to_vec();
// utxos.append(&mut outpoints);
// Arc::new(TxBuilder {
// utxos,
// ..self.clone()
// })
// }
//
// /// Do not spend change outputs. This effectively adds all the change outputs to the "unspendable" list. See TxBuilder.unspendable.
// pub(crate) fn do_not_spend_change(&self) -> Arc<Self> {
// Arc::new(TxBuilder {
// change_policy: ChangeSpendPolicy::ChangeForbidden,
// ..self.clone()
// })
// }
//
// /// Only spend utxos added by [add_utxo]. The wallet will not add additional utxos to the transaction even if they are
// /// needed to make the transaction valid.
// pub(crate) fn manually_selected_only(&self) -> Arc<Self> {
// Arc::new(TxBuilder {
// manually_selected_only: true,
// ..self.clone()
// })
// }
//
// /// Only spend change outputs. This effectively adds all the non-change outputs to the "unspendable" list. See TxBuilder.unspendable.
// pub(crate) fn only_spend_change(&self) -> Arc<Self> {
// Arc::new(TxBuilder {
// change_policy: ChangeSpendPolicy::OnlyChange,
// ..self.clone()
// })
// }
//
// /// Replace the internal list of unspendable utxos with a new list. Its important to note that the "must-be-spent" utxos added with
// /// TxBuilder.addUtxo have priority over these. See the Rust docs of the two linked methods for more details.
// pub(crate) fn unspendable(&self, unspendable: Vec<OutPoint>) -> Arc<Self> {
@ -374,7 +384,7 @@ impl TxBuilder {
// ..self.clone()
// })
// }
//
/// Set a custom fee rate.
pub(crate) fn fee_rate(&self, sat_per_vb: f32) -> Arc<Self> {
Arc::new(TxBuilder {
@ -382,7 +392,7 @@ impl TxBuilder {
..self.clone()
})
}
//
// /// Set an absolute fee.
// pub(crate) fn fee_absolute(&self, fee_amount: u64) -> Arc<Self> {
// Arc::new(TxBuilder {
@ -390,15 +400,15 @@ impl TxBuilder {
// ..self.clone()
// })
// }
//
// /// Spend all the available inputs. This respects filters like TxBuilder.unspendable and the change policy.
// pub(crate) fn drain_wallet(&self) -> Arc<Self> {
// Arc::new(TxBuilder {
// drain_wallet: true,
// ..self.clone()
// })
// }
//
/// Spend all the available inputs. This respects filters like TxBuilder.unspendable and the change policy.
pub(crate) fn drain_wallet(&self) -> Arc<Self> {
Arc::new(TxBuilder {
drain_wallet: true,
..self.clone()
})
}
// /// Sets the address to drain excess coins to. Usually, when there are excess coins they are sent to a change address
// /// generated by the wallet. This option replaces the usual change address with an arbitrary ScriptPubKey of your choosing.
// /// Just as with a change output, if the drain output is not needed (the excess coins are too small) it will not be included
@ -431,17 +441,16 @@ impl TxBuilder {
// ..self.clone()
// })
// }
//
// /// Add data as an output using OP_RETURN.
// pub(crate) fn add_data(&self, data: Vec<u8>) -> Arc<Self> {
// Arc::new(TxBuilder {
// data,
// ..self.clone()
// })
// }
//
/// Add data as an output using OP_RETURN.
// pub(crate) fn add_data(&self, data: Vec<u8>) -> Arc<Self> {
// Arc::new(TxBuilder {
// data,
// ..self.clone()
// })
// }
/// Finish building the transaction. Returns the BIP174 PSBT.
/// TODO: The TxBuilder in bdk returns a Psbt type
pub(crate) fn finish(
&self,
wallet: &Wallet,
@ -449,34 +458,32 @@ impl TxBuilder {
// TODO: I had to change the wallet here to be mutable. Why is that now required with the 1.0 API?
let mut wallet = wallet.get_wallet();
let mut tx_builder = wallet.build_tx();
// TODO: I'm not yet clear on the Script/ScriptBuf differences and whether this is the best
// way to do this.
for (script, amount) in &self.recipients {
tx_builder.add_recipient(script.clone(), *amount);
}
// tx_builder.change_policy(self.change_policy);
// if !self.utxos.is_empty() {
// let bdk_utxos: Vec<BdkOutPoint> = self.utxos.iter().map(BdkOutPoint::from).collect();
// let utxos: &[BdkOutPoint] = &bdk_utxos;
// tx_builder.add_utxos(utxos)?;
// }
tx_builder.change_policy(self.change_policy);
if !self.utxos.is_empty() {
let bdk_utxos: Vec<BdkOutPoint> = self.utxos.iter().map(BdkOutPoint::from).collect();
let utxos: &[BdkOutPoint] = &bdk_utxos;
tx_builder.add_utxos(utxos)?;
}
// if !self.unspendable.is_empty() {
// let bdk_unspendable: Vec<BdkOutPoint> =
// self.unspendable.iter().map(BdkOutPoint::from).collect();
// tx_builder.unspendable(bdk_unspendable);
// }
// if self.manually_selected_only {
// tx_builder.manually_selected_only();
// }
if self.manually_selected_only {
tx_builder.manually_selected_only();
}
if let Some(sat_per_vb) = self.fee_rate {
tx_builder.fee_rate(FeeRate::from_sat_per_vb(sat_per_vb));
}
// if let Some(fee_amount) = self.fee_absolute {
// tx_builder.fee_absolute(fee_amount);
// }
// if self.drain_wallet {
// tx_builder.drain_wallet();
// }
if self.drain_wallet {
tx_builder.drain_wallet();
}
// if let Some(script) = &self.drain_to {
// tx_builder.drain_to(script.clone());
// }
@ -501,7 +508,7 @@ impl TxBuilder {
Ok(Arc::new(psbt.into()))
}
}
//
// /// The BumpFeeTxBuilder is used to bump the fee on a transaction that has been broadcast and has its RBF flag set to true.
// #[derive(Clone)]
// pub(crate) struct BumpFeeTxBuilder {