Skip to content

Commit dcd2d47

Browse files
committed
Merge #1411: feat: update keychain::Balance to use bitcoin::Amount
22aa534 feat: use `Amount` on `TxBuilder::add_recipient` (Leonardo Lima) d5c0e72 feat: use `Amount` on `spk_txout_index` and related (Leonardo Lima) 8a33d98 feat: update `wallet::Balance` to use `bitcoin::Amount` (Leonardo Lima) Pull request description: fixes #823 <!-- You can erase any parts of this template not applicable to your Pull Request. --> ### Description It's being used on `Balance`, and throughout the code, an `u64` represents the amount, which relies on the user to infer its sats, not millisats, or any other representation. It updates the usage of `u64` on `Balance`, and other APIs: - `TxParams::add_recipient` - `KeyChainTxOutIndex::sent_and_received`, `KeyChainTxOutIndex::net_value` - `SpkTxOutIndex::sent_and_received`, `SpkTxOutIndex::net_value` <!-- Describe the purpose of this PR, what's being adding and/or fixed --> ### Notes to the reviewers <!-- In this section you can include notes directed to the reviewers, like explaining why some parts of the PR were done in a specific way --> It updates some of the APIs to expect the `bitcoin::Amount`, but it does not update internal usage of u64, such as `TxParams` still expects and uses `u64`, please see the PR comments for related discussion. ### Changelog notice <!-- Notice the release manager should include in the release tag message changelog --> <!-- See https://keepachangelog.com/en/1.0.0/ for examples --> - Changed the `keychain::Balance` struct fields to use `Amount` instead of `u64`. - Changed the `add_recipient` method on `TxBuilder` implementation to expect `bitcoin::Amount`. - Changed the `sent_and_received`, and `net_value` methods on `KeyChainTxOutIndex` to expect `bitcoin::Amount`. - Changed the `sent_and_received`, and `net_value` methods on `SpkTxOutIndex` to expect `bitcoin::Amount`. ### Checklists #### All Submissions: * [x] I've signed all my commits * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md) * [x] I ran `cargo fmt` and `cargo clippy` before committing #### New Features: * [x] I've added tests for the new feature * [x] I've added docs for the new feature #### Bugfixes: * [x] This pull request breaks the existing API * [ ] I've added tests to reproduce the issue which are now passing * [x] I'm linking the issue being fixed by this PR ACKs for top commit: evanlinjin: ACK 22aa534 Tree-SHA512: c4e8198d96c0d66cc3d2e4149e8a56bb7565b9cd49ff42113eaebd24b1d7bfeecd7124db0b06524b78b8891ee1bde1546705b80afad408f48495cf3c02446d02
2 parents 23538c4 + 22aa534 commit dcd2d47

File tree

18 files changed

+333
-270
lines changed

18 files changed

+333
-270
lines changed

crates/bdk/src/wallet/coin_selection.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@
9292
//! .unwrap();
9393
//! let psbt = {
9494
//! let mut builder = wallet.build_tx().coin_selection(AlwaysSpendEverything);
95-
//! builder.add_recipient(to_address.script_pubkey(), 50_000);
95+
//! builder.add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000));
9696
//! builder.finish()?
9797
//! };
9898
//!

crates/bdk/src/wallet/mod.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,14 @@ use bdk_chain::{
3232
IndexedTxGraph,
3333
};
3434
use bdk_persist::{Persist, PersistBackend};
35-
use bitcoin::constants::genesis_block;
3635
use bitcoin::secp256k1::{All, Secp256k1};
3736
use bitcoin::sighash::{EcdsaSighashType, TapSighashType};
3837
use bitcoin::{
3938
absolute, psbt, Address, Block, FeeRate, Network, OutPoint, Script, ScriptBuf, Sequence,
4039
Transaction, TxOut, Txid, Witness,
4140
};
42-
use bitcoin::{consensus::encode::serialize, transaction, Amount, BlockHash, Psbt};
41+
use bitcoin::{consensus::encode::serialize, transaction, BlockHash, Psbt};
42+
use bitcoin::{constants::genesis_block, Amount};
4343
use core::fmt;
4444
use core::ops::Deref;
4545
use descriptor::error::Error as DescriptorError;
@@ -950,10 +950,10 @@ impl Wallet {
950950
/// [`insert_txout`]: Self::insert_txout
951951
pub fn calculate_fee_rate(&self, tx: &Transaction) -> Result<FeeRate, CalculateFeeError> {
952952
self.calculate_fee(tx)
953-
.map(|fee| bitcoin::Amount::from_sat(fee) / tx.weight())
953+
.map(|fee| Amount::from_sat(fee) / tx.weight())
954954
}
955955

956-
/// Compute the `tx`'s sent and received amounts (in satoshis).
956+
/// Compute the `tx`'s sent and received [`Amount`]s.
957957
///
958958
/// This method returns a tuple `(sent, received)`. Sent is the sum of the txin amounts
959959
/// that spend from previous txouts tracked by this wallet. Received is the summation
@@ -978,7 +978,7 @@ impl Wallet {
978978
/// let tx = &psbt.clone().extract_tx().expect("tx");
979979
/// let (sent, received) = wallet.sent_and_received(tx);
980980
/// ```
981-
pub fn sent_and_received(&self, tx: &Transaction) -> (u64, u64) {
981+
pub fn sent_and_received(&self, tx: &Transaction) -> (Amount, Amount) {
982982
self.indexed_graph.index.sent_and_received(tx, ..)
983983
}
984984

@@ -1197,7 +1197,7 @@ impl Wallet {
11971197
/// let psbt = {
11981198
/// let mut builder = wallet.build_tx();
11991199
/// builder
1200-
/// .add_recipient(to_address.script_pubkey(), 50_000);
1200+
/// .add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000));
12011201
/// builder.finish()?
12021202
/// };
12031203
///
@@ -1579,7 +1579,7 @@ impl Wallet {
15791579
/// let mut psbt = {
15801580
/// let mut builder = wallet.build_tx();
15811581
/// builder
1582-
/// .add_recipient(to_address.script_pubkey(), 50_000)
1582+
/// .add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000))
15831583
/// .enable_rbf();
15841584
/// builder.finish()?
15851585
/// };
@@ -1752,7 +1752,7 @@ impl Wallet {
17521752
/// # let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap().assume_checked();
17531753
/// let mut psbt = {
17541754
/// let mut builder = wallet.build_tx();
1755-
/// builder.add_recipient(to_address.script_pubkey(), 50_000);
1755+
/// builder.add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000));
17561756
/// builder.finish()?
17571757
/// };
17581758
/// let finalized = wallet.sign(&mut psbt, SignOptions::default())?;

crates/bdk/src/wallet/tx_builder.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
//!
3030
//! tx_builder
3131
//! // Create a transaction with one output to `to_address` of 50_000 satoshi
32-
//! .add_recipient(to_address.script_pubkey(), 50_000)
32+
//! .add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000))
3333
//! // With a custom fee rate of 5.0 satoshi/vbyte
3434
//! .fee_rate(FeeRate::from_sat_per_vb(5).expect("valid feerate"))
3535
//! // Only spend non-change outputs
@@ -47,7 +47,7 @@ use core::marker::PhantomData;
4747

4848
use bitcoin::psbt::{self, Psbt};
4949
use bitcoin::script::PushBytes;
50-
use bitcoin::{absolute, FeeRate, OutPoint, ScriptBuf, Sequence, Transaction, Txid};
50+
use bitcoin::{absolute, Amount, FeeRate, OutPoint, ScriptBuf, Sequence, Transaction, Txid};
5151

5252
use super::coin_selection::{CoinSelectionAlgorithm, DefaultCoinSelectionAlgorithm};
5353
use super::{CreateTxError, Wallet};
@@ -94,8 +94,8 @@ impl TxBuilderContext for BumpFee {}
9494
/// let mut builder = wallet.build_tx();
9595
/// builder
9696
/// .ordering(TxOrdering::Untouched)
97-
/// .add_recipient(addr1.script_pubkey(), 50_000)
98-
/// .add_recipient(addr2.script_pubkey(), 50_000);
97+
/// .add_recipient(addr1.script_pubkey(), Amount::from_sat(50_000))
98+
/// .add_recipient(addr2.script_pubkey(), Amount::from_sat(50_000));
9999
/// builder.finish()?
100100
/// };
101101
///
@@ -104,7 +104,7 @@ impl TxBuilderContext for BumpFee {}
104104
/// let mut builder = wallet.build_tx();
105105
/// builder.ordering(TxOrdering::Untouched);
106106
/// for addr in &[addr1, addr2] {
107-
/// builder.add_recipient(addr.script_pubkey(), 50_000);
107+
/// builder.add_recipient(addr.script_pubkey(), Amount::from_sat(50_000));
108108
/// }
109109
/// builder.finish()?
110110
/// };
@@ -274,7 +274,7 @@ impl<'a, Cs, Ctx> TxBuilder<'a, Cs, Ctx> {
274274
///
275275
/// let builder = wallet
276276
/// .build_tx()
277-
/// .add_recipient(to_address.script_pubkey(), 50_000)
277+
/// .add_recipient(to_address.script_pubkey(), Amount::from_sat(50_000))
278278
/// .policy_path(path, KeychainKind::External);
279279
///
280280
/// # Ok::<(), anyhow::Error>(())
@@ -713,21 +713,26 @@ impl std::error::Error for AllowShrinkingError {}
713713

714714
impl<'a, Cs: CoinSelectionAlgorithm> TxBuilder<'a, Cs, CreateTx> {
715715
/// Replace the recipients already added with a new list
716-
pub fn set_recipients(&mut self, recipients: Vec<(ScriptBuf, u64)>) -> &mut Self {
717-
self.params.recipients = recipients;
716+
pub fn set_recipients(&mut self, recipients: Vec<(ScriptBuf, Amount)>) -> &mut Self {
717+
self.params.recipients = recipients
718+
.into_iter()
719+
.map(|(script, amount)| (script, amount.to_sat()))
720+
.collect();
718721
self
719722
}
720723

721724
/// Add a recipient to the internal list
722-
pub fn add_recipient(&mut self, script_pubkey: ScriptBuf, amount: u64) -> &mut Self {
723-
self.params.recipients.push((script_pubkey, amount));
725+
pub fn add_recipient(&mut self, script_pubkey: ScriptBuf, amount: Amount) -> &mut Self {
726+
self.params
727+
.recipients
728+
.push((script_pubkey, amount.to_sat()));
724729
self
725730
}
726731

727732
/// Add data as an output, using OP_RETURN
728733
pub fn add_data<T: AsRef<PushBytes>>(&mut self, data: &T) -> &mut Self {
729734
let script = ScriptBuf::new_op_return(data);
730-
self.add_recipient(script, 0u64);
735+
self.add_recipient(script, Amount::ZERO);
731736
self
732737
}
733738

crates/bdk/tests/psbt.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ fn test_psbt_malformed_psbt_input_legacy() {
1414
let (mut wallet, _) = get_funded_wallet(get_test_wpkh());
1515
let send_to = wallet.peek_address(KeychainKind::External, 0);
1616
let mut builder = wallet.build_tx();
17-
builder.add_recipient(send_to.script_pubkey(), 10_000);
17+
builder.add_recipient(send_to.script_pubkey(), Amount::from_sat(10_000));
1818
let mut psbt = builder.finish().unwrap();
1919
psbt.inputs.push(psbt_bip.inputs[0].clone());
2020
let options = SignOptions {
@@ -31,7 +31,7 @@ fn test_psbt_malformed_psbt_input_segwit() {
3131
let (mut wallet, _) = get_funded_wallet(get_test_wpkh());
3232
let send_to = wallet.peek_address(KeychainKind::External, 0);
3333
let mut builder = wallet.build_tx();
34-
builder.add_recipient(send_to.script_pubkey(), 10_000);
34+
builder.add_recipient(send_to.script_pubkey(), Amount::from_sat(10_000));
3535
let mut psbt = builder.finish().unwrap();
3636
psbt.inputs.push(psbt_bip.inputs[1].clone());
3737
let options = SignOptions {
@@ -47,7 +47,7 @@ fn test_psbt_malformed_tx_input() {
4747
let (mut wallet, _) = get_funded_wallet(get_test_wpkh());
4848
let send_to = wallet.peek_address(KeychainKind::External, 0);
4949
let mut builder = wallet.build_tx();
50-
builder.add_recipient(send_to.script_pubkey(), 10_000);
50+
builder.add_recipient(send_to.script_pubkey(), Amount::from_sat(10_000));
5151
let mut psbt = builder.finish().unwrap();
5252
psbt.unsigned_tx.input.push(TxIn::default());
5353
let options = SignOptions {
@@ -63,7 +63,7 @@ fn test_psbt_sign_with_finalized() {
6363
let (mut wallet, _) = get_funded_wallet(get_test_wpkh());
6464
let send_to = wallet.peek_address(KeychainKind::External, 0);
6565
let mut builder = wallet.build_tx();
66-
builder.add_recipient(send_to.script_pubkey(), 10_000);
66+
builder.add_recipient(send_to.script_pubkey(), Amount::from_sat(10_000));
6767
let mut psbt = builder.finish().unwrap();
6868

6969
// add a finalized input
@@ -201,7 +201,7 @@ fn test_psbt_multiple_internalkey_signers() {
201201
// the prevout we're spending
202202
let prevouts = &[TxOut {
203203
script_pubkey: send_to.script_pubkey(),
204-
value: Amount::from_sat(to_spend),
204+
value: to_spend,
205205
}];
206206
let prevouts = Prevouts::All(prevouts);
207207
let input_index = 0;

0 commit comments

Comments
 (0)