Skip to content
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
116 changes: 52 additions & 64 deletions src/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1711,15 +1711,15 @@ impl Wallet {
&mut self,
txid: Txid,
) -> Result<TxBuilder<'_, DefaultCoinSelectionAlgorithm>, BuildFeeBumpError> {
let graph = self.indexed_graph.graph();
let tx_graph = self.indexed_graph.graph();
let txout_index = &self.indexed_graph.index;
let chain_tip = self.chain.tip().block_id();
let chain_positions = graph
let chain_positions: HashMap<Txid, ChainPosition<_>> = tx_graph
.list_canonical_txs(&self.chain, chain_tip, CanonicalizationParams::default())
.map(|canon_tx| (canon_tx.tx_node.txid, canon_tx.chain_position))
.collect::<HashMap<Txid, _>>();
.collect();

let mut tx = graph
let mut tx = tx_graph
.get_tx(txid)
.ok_or(BuildFeeBumpError::TransactionNotFound(txid))?
.as_ref()
Expand All @@ -1746,73 +1746,62 @@ impl Wallet {
let fee = self
.calculate_fee(&tx)
.map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
let fee_rate = self
.calculate_fee_rate(&tx)
.map_err(|_| BuildFeeBumpError::FeeRateUnavailable)?;
let fee_rate = fee / tx.weight();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the rationale to not use calculate_fee_rate?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seemed redundant since calculate_fee_rate already calls calculate_fee, so I chose to inline the implementation here.


// Remove the inputs from the tx and process them.
let utxos = tx
let utxos: Vec<WeightedUtxo> = tx
.input
.drain(..)
.map(|txin| -> Result<_, BuildFeeBumpError> {
graph
// Get previous transaction.
.get_tx(txin.previous_output.txid)
.ok_or(BuildFeeBumpError::UnknownUtxo(txin.previous_output))
// Get chain position.
.and_then(|prev_tx| {
let outpoint = txin.previous_output;
let prev_txout = tx_graph
.get_txout(outpoint)
.cloned()
.ok_or(BuildFeeBumpError::UnknownUtxo(outpoint))?;
match txout_index.index_of_spk(prev_txout.script_pubkey.clone()) {
Some(&(keychain, derivation_index)) => {
let txout = prev_txout;
let chain_position = chain_positions
.get(&txin.previous_output.txid)
.get(&outpoint.txid)
.cloned()
.ok_or(BuildFeeBumpError::UnknownUtxo(txin.previous_output))?;
let prev_txout = prev_tx
.output
.get(txin.previous_output.vout as usize)
.ok_or(BuildFeeBumpError::InvalidOutputIndex(txin.previous_output))
.cloned()?;
Ok((prev_tx, prev_txout, chain_position))
})
.map(|(prev_tx, prev_txout, chain_position)| {
match txout_index.index_of_spk(prev_txout.script_pubkey.clone()) {
Some(&(keychain, derivation_index)) => WeightedUtxo {
satisfaction_weight: self
.public_descriptor(keychain)
.max_weight_to_satisfy()
.unwrap(),
utxo: Utxo::Local(LocalOutput {
outpoint: txin.previous_output,
txout: prev_txout.clone(),
keychain,
is_spent: true,
derivation_index,
chain_position,
}),
},
None => {
let satisfaction_weight = Weight::from_wu_usize(
serialize(&txin.script_sig).len() * 4
+ serialize(&txin.witness).len(),
);
WeightedUtxo {
utxo: Utxo::Foreign {
outpoint: txin.previous_output,
sequence: txin.sequence,
psbt_input: Box::new(psbt::Input {
witness_utxo: prev_txout
.script_pubkey
.witness_version()
.map(|_| prev_txout.clone()),
non_witness_utxo: Some(prev_tx.as_ref().clone()),
..Default::default()
}),
},
satisfaction_weight,
}
}
}
})
.ok_or(BuildFeeBumpError::TransactionNotFound(outpoint.txid))?;
Ok(WeightedUtxo {
satisfaction_weight: self
.public_descriptor(keychain)
.max_weight_to_satisfy()
.expect("descriptor should be satisfiable"),
utxo: Utxo::Local(LocalOutput {
outpoint,
txout,
keychain,
is_spent: true,
derivation_index,
chain_position,
}),
})
}
None => Ok(WeightedUtxo {
satisfaction_weight: Weight::from_wu_usize(
serialize(&txin.script_sig).len() * 4 + serialize(&txin.witness).len(),
),
utxo: Utxo::Foreign {
outpoint,
sequence: txin.sequence,
psbt_input: Box::new(psbt::Input {
witness_utxo: prev_txout
.script_pubkey
.witness_version()
.map(|_| prev_txout),
non_witness_utxo: tx_graph
.get_tx(outpoint.txid)
.map(|tx| tx.as_ref().clone()),
..Default::default()
}),
},
}),
}
})
.collect::<Result<Vec<WeightedUtxo>, BuildFeeBumpError>>()?;
.collect::<Result<_, _>>()?;

if tx.output.len() > 1 {
let mut change_index = None;
Expand All @@ -1832,7 +1821,6 @@ impl Wallet {
}

let params = TxParams {
// TODO: figure out what rbf option should be?
version: Some(tx.version),
recipients: tx
.output
Expand Down
54 changes: 53 additions & 1 deletion tests/add_foreign_utxo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use bdk_wallet::signer::SignOptions;
use bdk_wallet::test_utils::*;
use bdk_wallet::tx_builder::AddForeignUtxoError;
use bdk_wallet::KeychainKind;
use bitcoin::{psbt, Address, Amount};
use bitcoin::{hashes::Hash, psbt, Address, Amount, FeeRate, OutPoint, TxOut, Weight};

use common::parse_descriptor;

mod common;

Expand Down Expand Up @@ -290,3 +292,53 @@ fn test_taproot_foreign_utxo() {
"foreign_utxo should be in there"
);
}

// Test that we can fee-bump a tx containing a foreign utxo
#[test]
fn test_add_foreign_utxo_build_fee_bump() {
let (mut wallet, _) = get_funded_wallet_wpkh();
let drain_spk = wallet
.next_unused_address(KeychainKind::External)
.script_pubkey();

let (desc, _) = parse_descriptor(get_test_tr_single_sig());
let spk = desc.at_derivation_index(0).unwrap().script_pubkey();
let witness_utxo = TxOut {
value: Amount::ONE_SAT,
script_pubkey: spk,
};
// Remember to include this as a "floating" txout in the wallet.
let outpoint = OutPoint::new(Hash::hash(b"prev"), 1);
wallet.insert_txout(outpoint, witness_utxo.clone());
let satisfaction_weight = Weight::from_wu(71);
let psbt_input = psbt::Input {
witness_utxo: Some(witness_utxo),
..Default::default()
};

let mut tx_builder = wallet.build_tx();
tx_builder
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default fee rate of this tx is important but not expressed in the creation of the first tx of the test. A comment may be necessary here.

.add_foreign_utxo(outpoint, psbt_input, satisfaction_weight)
.unwrap()
.only_witness_utxo()
.fee_rate(FeeRate::from_sat_per_vb_unchecked(2))
.drain_to(drain_spk.clone());
let psbt = tx_builder.finish().unwrap();
let tx = psbt.unsigned_tx.clone();
assert!(tx.input.iter().any(|txin| txin.previous_output == outpoint));
let txid1 = tx.compute_txid();
wallet.apply_unconfirmed_txs([(tx, 123456)]);

// Now build fee bump.
let mut tx_builder = wallet
.build_fee_bump(txid1)
.expect("`build_fee_bump` should succeed");
tx_builder
.set_recipients(vec![])
.drain_to(drain_spk)
.only_witness_utxo()
.fee_rate(FeeRate::from_sat_per_vb_unchecked(5));
let psbt = tx_builder.finish().unwrap();
let tx = &psbt.unsigned_tx;
assert!(tx.input.iter().any(|txin| txin.previous_output == outpoint));
}