Skip to content

fix: make sure tx_build does not change the order of add_utxos when u… #252

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 64 additions & 2 deletions wallet/src/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1511,7 +1511,7 @@ impl Wallet {

let (required_utxos, optional_utxos) = {
// NOTE: manual selection overrides unspendable
let mut required: Vec<WeightedUtxo> = params.utxos.values().cloned().collect();
let mut required: Vec<WeightedUtxo> = params.utxos.order_weighted_utxos();
let optional = self.filter_utxos(&params, current_height.to_consensus_u32());

// if drain_wallet is true, all UTxOs are required
Expand Down Expand Up @@ -1785,7 +1785,7 @@ impl Wallet {
}
})
})
.collect::<Result<HashMap<OutPoint, WeightedUtxo>, BuildFeeBumpError>>()?;
.collect::<Result<OrderUtxos, BuildFeeBumpError>>()?;

if tx.output.len() > 1 {
let mut change_index = None;
Expand Down Expand Up @@ -2574,6 +2574,68 @@ impl Wallet {
}
}

#[derive(Debug, Default, Clone)]
pub(crate) struct OrderUtxos {
utxos: Vec<OutPoint>,
utxos_map: HashMap<OutPoint, WeightedUtxo>,
}

impl Deref for OrderUtxos {
type Target = HashMap<OutPoint, WeightedUtxo>;

fn deref(&self) -> &Self::Target {
&self.utxos_map
}
}

impl OrderUtxos {
fn insert(&mut self, outpoint: OutPoint, weighted_utxo: WeightedUtxo) -> Option<WeightedUtxo> {
let v = self.utxos_map.insert(outpoint, weighted_utxo);
if v.is_none() {
self.utxos.push(outpoint);
}
debug_assert!(self.utxos.len() == self.utxos_map.len());
v
}

fn order_weighted_utxos(&self) -> Vec<WeightedUtxo> {
self.utxos
.iter()
.map(|outpoint| self.utxos_map.get(outpoint).cloned().unwrap())
.collect::<Vec<_>>()
}
}

impl FromIterator<(OutPoint, WeightedUtxo)> for OrderUtxos {
fn from_iter<T: IntoIterator<Item = (OutPoint, WeightedUtxo)>>(iter: T) -> Self {
let mut r = OrderUtxos::default();
for (outpoint, weighted_utxo) in iter {
r.insert(outpoint, weighted_utxo);
}
r
}
}

impl IntoIterator for OrderUtxos {
type Item = (OutPoint, WeightedUtxo);
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(mut self) -> Self::IntoIter {
self.utxos
.into_iter()
.map(|outpoint| (outpoint, self.utxos_map.remove(&outpoint).unwrap()))
.collect::<Vec<_>>()
.into_iter()
}
}

impl Extend<(OutPoint, WeightedUtxo)> for OrderUtxos {
fn extend<T: IntoIterator<Item = (OutPoint, WeightedUtxo)>>(&mut self, iter: T) {
for (outpoint, weighted_utxo) in iter {
self.insert(outpoint, weighted_utxo);
}
}
}

impl AsRef<bdk_chain::tx_graph::TxGraph<ConfirmationBlockTime>> for Wallet {
fn as_ref(&self) -> &bdk_chain::tx_graph::TxGraph<ConfirmationBlockTime> {
self.indexed_graph.graph()
Expand Down
8 changes: 4 additions & 4 deletions wallet/src/wallet/tx_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ use rand_core::RngCore;
use super::coin_selection::CoinSelectionAlgorithm;
use super::utils::shuffle_slice;
use super::{CreateTxError, Wallet};
use crate::collections::{BTreeMap, HashMap, HashSet};
use crate::{KeychainKind, LocalOutput, Utxo, WeightedUtxo};
use crate::collections::{BTreeMap, HashSet};
use crate::{KeychainKind, LocalOutput, OrderUtxos, Utxo, WeightedUtxo};

/// A transaction builder
///
Expand Down Expand Up @@ -126,7 +126,7 @@ pub(crate) struct TxParams {
pub(crate) fee_policy: Option<FeePolicy>,
pub(crate) internal_policy_path: Option<BTreeMap<String, Vec<usize>>>,
pub(crate) external_policy_path: Option<BTreeMap<String, Vec<usize>>>,
pub(crate) utxos: HashMap<OutPoint, WeightedUtxo>,
pub(crate) utxos: OrderUtxos,
pub(crate) unspendable: HashSet<OutPoint>,
pub(crate) manually_selected_only: bool,
pub(crate) sighash: Option<psbt::PsbtSighashType>,
Expand Down Expand Up @@ -297,7 +297,7 @@ impl<'a, Cs> TxBuilder<'a, Cs> {
)
})
})
.collect::<Result<HashMap<OutPoint, WeightedUtxo>, AddUtxoError>>()?;
.collect::<Result<OrderUtxos, AddUtxoError>>()?;
self.params.utxos.extend(utxo_batch);

Ok(self)
Expand Down
65 changes: 65 additions & 0 deletions wallet/tests/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4699,3 +4699,68 @@ fn test_tx_details_method() {
let tx_details_2_option = test_wallet.tx_details(txid_2);
assert!(tx_details_2_option.is_none());
}

#[test]
fn test_build_tx_untouch() {
let (mut wallet, txid) = get_funded_wallet_wpkh();
let script_pubkey = wallet
.next_unused_address(KeychainKind::External)
.address
.script_pubkey();
let tx1 = Transaction {
input: vec![TxIn {
previous_output: OutPoint { txid, vout: 0 },
..Default::default()
}],
output: vec![
TxOut {
value: Amount::from_sat(500),
script_pubkey: script_pubkey.clone(),
};
4
],
..new_tx(0)
};

let txid1 = tx1.compute_txid();
insert_tx(&mut wallet, tx1);
insert_anchor(
&mut wallet,
txid1,
ConfirmationBlockTime {
block_id: BlockId {
height: 2_100,
hash: BlockHash::all_zeros(),
},
confirmation_time: 300,
},
);
let utxos = wallet
.list_unspent()
.map(|o| o.outpoint)
.collect::<Vec<_>>();
assert!(utxos.len() == 4);

let mut builder = wallet.build_tx();
builder
.ordering(bdk_wallet::TxOrdering::Untouched)
.add_utxos(&utxos)
.unwrap()
.add_recipient(script_pubkey.clone(), Amount::from_sat(400))
.add_recipient(script_pubkey.clone(), Amount::from_sat(300))
.add_recipient(script_pubkey.clone(), Amount::from_sat(500));
let tx = builder.finish().unwrap().unsigned_tx;
let txins = tx
.input
.iter()
.map(|txin| txin.previous_output)
.collect::<Vec<_>>();
assert!(txins == utxos);
let txouts = tx
.output
.iter()
.take(3)
.map(|txout| txout.value.to_sat())
.collect::<Vec<_>>();
assert!(txouts == vec![400, 300, 500]);
}
Loading