Skip to content
Merged
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
82 changes: 56 additions & 26 deletions src/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -945,8 +945,9 @@ impl Wallet {
/// Calculates the fee of a given transaction. Returns [`Amount::ZERO`] if `tx` is a coinbase
/// transaction.
///
/// To calculate the fee for a [`Transaction`] with inputs not owned by this wallet you must
/// manually insert the TxOut(s) into the tx graph using the [`insert_txout`] function.
/// To calculate the fee for a [`Transaction`] with inputs not owned by this wallet, register
/// any missing prevouts with [`insert_txout`] or their full parent transactions with
/// [`apply_update`](Self::apply_update).
///
/// Note `tx` does not have to be in the graph for this to work.
///
Expand Down Expand Up @@ -976,8 +977,8 @@ impl Wallet {

/// Calculate the [`FeeRate`] for a given transaction.
///
/// To calculate the fee rate for a [`Transaction`] with inputs not owned by this wallet you
/// must manually insert the TxOut(s) into the tx graph using the [`insert_txout`] function.
/// To calculate the fee rate for a [`Transaction`] with inputs not owned by this wallet,
/// register any missing prevouts as described in [`calculate_fee`](Self::calculate_fee).
///
/// Note `tx` does not have to be in the graph for this to work.
///
Expand All @@ -1000,7 +1001,6 @@ impl Wallet {
/// let tx = &psbt.clone().extract_tx().expect("tx");
/// let fee_rate = wallet.calculate_fee_rate(tx).expect("fee rate");
/// ```
/// [`insert_txout`]: Self::insert_txout
pub fn calculate_fee_rate(&self, tx: &Transaction) -> Result<FeeRate, CalculateFeeError> {
self.calculate_fee(tx).map(|fee| fee / tx.weight())
}
Expand Down Expand Up @@ -1620,7 +1620,23 @@ impl Wallet {
/// *replace by fee* (RBF). If the transaction can be fee bumped then it returns a [`TxBuilder`]
/// pre-populated with the inputs and outputs of the original transaction.
///
/// ## Example
/// # Foreign inputs
///
/// This method reconstructs foreign PSBT inputs from the wallet's transaction graph. Data
/// passed to [`TxBuilder::add_foreign_utxo`](tx_builder::TxBuilder::add_foreign_utxo) when
/// building the original transaction is not stored in that graph automatically.
/// Before calling this method, register each foreign output with [`Self::insert_txout`] or
/// its full parent transaction with [`Self::apply_update`]:
///
/// - Legacy and P2SH inputs require the full parent transaction. With only the output
/// registered, this method returns [`BuildFeeBumpError::TransactionNotFound`].
/// - Native segwit inputs, including Taproot, need only the output to construct the builder.
/// However, for non-Taproot inputs, [`TxBuilder::finish`](tx_builder::TxBuilder::finish)
/// returns [`CreateTxError::MissingNonWitnessUtxo`] unless the full parent was also
/// registered or [`TxBuilder::only_witness_utxo`](tx_builder::TxBuilder::only_witness_utxo)
/// is set on the returned builder.
///
/// # Example
///
/// ```no_run
/// # // TODO: remove norun -- bumping fee seems to need the tx in the wallet database first.
Expand Down Expand Up @@ -1735,25 +1751,32 @@ impl Wallet {
}),
})
}
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()
}),
},
}),
None => {
let witness_utxo = prev_txout
.script_pubkey
.witness_version()
.map(|_| prev_txout);
let non_witness_utxo =
tx_graph.get_tx(outpoint.txid).map(|tx| tx.as_ref().clone());
if witness_utxo.is_none() && non_witness_utxo.is_none() {
return Err(BuildFeeBumpError::TransactionNotFound(outpoint.txid));
}
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,
non_witness_utxo,
..Default::default()
}),
},
})
}
}
})
.collect::<Result<_, _>>()?;
Expand Down Expand Up @@ -1903,7 +1926,14 @@ impl Wallet {
if input.non_witness_utxo.is_none() {
return Err(SignerError::MissingNonWitnessUtxo);
}
if validated_non_witness_prevout(input, txin.previous_output).is_none() {
let prevout = validated_non_witness_prevout(input, txin.previous_output)
.ok_or(SignerError::InvalidNonWitnessUtxo)?;
if input
.witness_utxo
.as_ref()
.is_some_and(|witness| witness != prevout)
{
// Ideally InvalidWitnessUtxo; reuse this error for API compatibility.
return Err(SignerError::InvalidNonWitnessUtxo);
}
}
Expand Down
1 change: 1 addition & 0 deletions src/wallet/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,7 @@ impl InputSigner for SignerWrapper<PrivateKey> {
.as_ref()
.is_some_and(|witness| witness != prevout)
{
// Ideally InvalidWitnessUtxo; reuse this error for API compatibility.
return Err(SignerError::InvalidNonWitnessUtxo);
}
} else if !sign_options.trust_witness_utxo && input.witness_utxo.is_some() {
Expand Down
18 changes: 12 additions & 6 deletions src/wallet/tx_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ use super::utils::shuffle_slice;
use super::{CreateTxError, Wallet};
use crate::collections::{BTreeMap, HashMap, HashSet};
use crate::descriptor::Condition;
use crate::psbt::validated_non_witness_prevout;
use crate::{KeychainKind, LocalOutput, Utxo, WeightedUtxo};

/// A transaction builder
Expand Down Expand Up @@ -465,9 +466,11 @@ impl<'a, Cs> TxBuilder<'a, Cs> {
///
/// This is an **EXPERIMENTAL** feature, API and other major changes are expected.
///
/// In order to use [`Wallet::calculate_fee`] or [`Wallet::calculate_fee_rate`] for a
/// transaction created with foreign UTXO(s) you must manually insert the corresponding
/// TxOut(s) into the tx graph using the [`Wallet::insert_txout`] function.
/// This method adds data to the builder, not to the wallet's transaction graph. To use
/// [`Wallet::calculate_fee`] or [`Wallet::calculate_fee_rate`] on the resulting transaction,
/// also insert the foreign output with [`Wallet::insert_txout`] or its full parent transaction
/// with [`Wallet::apply_update`]. For fee bumping, see the foreign-input requirements on
/// [`Wallet::build_fee_bump`].
///
/// # Errors
///
Expand Down Expand Up @@ -502,7 +505,7 @@ impl<'a, Cs> TxBuilder<'a, Cs> {
pub fn add_foreign_utxo_with_sequence(
&mut self,
outpoint: OutPoint,
psbt_input: psbt::Input,
mut psbt_input: psbt::Input,
satisfaction_weight: Weight,
sequence: Sequence,
) -> Result<&mut Self, AddForeignUtxoError> {
Expand All @@ -514,8 +517,11 @@ impl<'a, Cs> TxBuilder<'a, Cs> {
foreign_utxo: outpoint,
});
}
if tx.output.len() <= outpoint.vout as usize {
return Err(AddForeignUtxoError::InvalidOutpoint(outpoint));
let prevout = validated_non_witness_prevout(&psbt_input, outpoint)
.ok_or(AddForeignUtxoError::InvalidOutpoint(outpoint))?;
// Set the existing witness UTXO to the verified prevout.
if psbt_input.witness_utxo.is_some() {
psbt_input.witness_utxo = Some(prevout.clone());
}
} else if psbt_input.witness_utxo.is_none() {
return Err(AddForeignUtxoError::MissingUtxo);
Expand Down
75 changes: 74 additions & 1 deletion tests/add_foreign_utxo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use bdk_wallet::psbt::PsbtUtils;
use bdk_wallet::signer::SignOptions;
use bdk_wallet::test_utils::*;
use bdk_wallet::tx_builder::AddForeignUtxoError;
use bitcoin::{Address, Amount, psbt};
use bitcoin::{Address, Amount, TxOut, psbt};

mod common;
use common::signers_from_descriptor;
Expand Down Expand Up @@ -183,6 +183,79 @@ fn test_add_foreign_utxo_where_outpoint_doesnt_match_psbt_input() {
);
}

/// Checks that witness_utxo is overridden by verified non_witness_utxo in case of mismatch.
#[test]
fn test_add_foreign_utxo_mismatched_witness_utxo() {
let (mut wallet, _) = get_funded_wallet_wpkh();
let (foreign_wallet, txid) =
get_funded_wallet_single("wpkh(cVbZ8ovhye9AoAHFsqobCf7LxbXDAECy9Kb8TZdfsDYMZGBUyCnm)");
let utxo = foreign_wallet.list_unspent().next().unwrap();
let parent = foreign_wallet.get_tx(txid).unwrap().tx_node.tx;
let weight = foreign_wallet
.public_descriptor(KeychainKind::External)
.max_weight_to_satisfy()
.unwrap();
let recipient = Address::from_str("2N1Ffz3WaNzbeLFBb51xyFMHYSEUXcbiSoX")
.unwrap()
.assume_checked();
let fee = Amount::from_sat(500);
let deflated = TxOut {
value: utxo.txout.value - Amount::from_sat(20_000),
script_pubkey: utxo.txout.script_pubkey.clone(),
};

let mut builder = wallet.build_tx();
builder
.add_recipient(recipient.script_pubkey(), Amount::from_sat(60_000))
.fee_absolute(fee)
.add_foreign_utxo(
utxo.outpoint,
psbt::Input {
non_witness_utxo: Some(parent.as_ref().clone()),
witness_utxo: Some(deflated),
..Default::default()
},
weight,
)
.unwrap();
let psbt = builder.finish().unwrap();
let index = psbt
.unsigned_tx
.input
.iter()
.position(|input| input.previous_output == utxo.outpoint)
.unwrap();
assert_eq!(psbt.inputs[index].witness_utxo, Some(utxo.txout.clone()));
assert_eq!(
psbt.inputs[index].non_witness_utxo.as_ref(),
Some(parent.as_ref())
);
wallet.insert_txout(utxo.outpoint, utxo.txout.clone());
assert_eq!(check_fee!(wallet, psbt), fee);

let mut builder = wallet.build_tx();
builder
.add_recipient(recipient.script_pubkey(), Amount::from_sat(60_000))
.fee_absolute(fee)
.add_foreign_utxo(
utxo.outpoint,
psbt::Input {
non_witness_utxo: Some(parent.as_ref().clone()),
..Default::default()
},
weight,
)
.unwrap();
let psbt = builder.finish().unwrap();
let index = psbt
.unsigned_tx
.input
.iter()
.position(|input| input.previous_output == utxo.outpoint)
.unwrap();
assert!(psbt.inputs[index].witness_utxo.is_none());
}

#[test]
fn test_add_foreign_utxo_only_witness_utxo() {
let (mut wallet1, _) = get_funded_wallet_wpkh();
Expand Down
62 changes: 61 additions & 1 deletion tests/build_fee_bump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use assert_matches::assert_matches;
use bdk_chain::{ChainPosition, ConfirmationBlockTime};
use bdk_wallet::KeychainKind;
use bdk_wallet::coin_selection::LargestFirstCoinSelection;
use bdk_wallet::error::CreateTxError;
use bdk_wallet::error::{BuildFeeBumpError, CreateTxError};
use bdk_wallet::psbt::PsbtUtils;
use bdk_wallet::test_utils::*;
use bitcoin::{
Expand Down Expand Up @@ -945,6 +945,66 @@ fn test_legacy_bump_fee_absolute_add_input() {
assert_eq!(fee, Amount::from_sat(6_000));
}

/// Rejects a legacy foreign fee bump if full parent is not registered.
#[test]
fn test_bump_fee_legacy_foreign_utxo_requires_parent_tx() {
let (mut wallet, _) = get_funded_wallet_wpkh();
let (foreign_wallet, parent_txid) =
get_funded_wallet_single("pkh(cVbZ8ovhye9AoAHFsqobCf7LxbXDAECy9Kb8TZdfsDYMZGBUyCnm)");
let utxo = foreign_wallet.list_unspent().next().unwrap();
let parent = foreign_wallet.get_tx(parent_txid).unwrap().tx_node.tx;
let satisfaction_weight = foreign_wallet
.public_descriptor(KeychainKind::External)
.max_weight_to_satisfy()
.unwrap();
wallet.insert_txout(utxo.outpoint, utxo.txout.clone());

let addr = Address::from_str("2N1Ffz3WaNzbeLFBb51xyFMHYSEUXcbiSoX")
.unwrap()
.assume_checked();
let mut builder = wallet.build_tx();
builder
.add_recipient(addr.script_pubkey(), Amount::from_sat(60_000))
.fee_absolute(Amount::from_sat(500))
.add_foreign_utxo(
utxo.outpoint,
psbt::Input {
non_witness_utxo: Some(parent.as_ref().clone()),
..Default::default()
},
satisfaction_weight,
)
.unwrap();
let tx = builder.finish().unwrap().extract_tx().unwrap();
let txid = tx.compute_txid();
insert_tx(&mut wallet, tx);

assert!(wallet.tx_graph().get_txout(utxo.outpoint).is_some());
assert!(wallet.tx_graph().get_tx(parent_txid).is_none());
assert!(matches!(
wallet.build_fee_bump(txid),
Err(BuildFeeBumpError::TransactionNotFound(missing_txid)) if missing_txid == parent_txid
));

// Registering the full parent through apply_update restores fee bumping.
insert_tx(&mut wallet, parent.as_ref().clone());
let mut builder = wallet.build_fee_bump(txid).unwrap();
builder.fee_absolute(Amount::from_sat(1_000));
let psbt = builder.finish().unwrap();
let index = psbt
.unsigned_tx
.input
.iter()
.position(|input| input.previous_output == utxo.outpoint)
.unwrap();
assert!(psbt.inputs[index].witness_utxo.is_none());
assert_eq!(
psbt.inputs[index].non_witness_utxo.as_ref(),
Some(parent.as_ref())
);
assert_eq!(check_fee!(wallet, psbt), Amount::from_sat(1_000));
}

// Test that we can fee-bump a tx containing a foreign (p2a) utxo.
#[test]
fn test_bump_fee_pay_to_anchor_foreign_utxo() {
Expand Down
36 changes: 36 additions & 0 deletions tests/psbt.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use bdk_wallet::bitcoin::bip32::Xpriv;
use bdk_wallet::bitcoin::psbt::SigningKeys;
use bdk_wallet::psbt::PsbtUtils;
use bdk_wallet::signer::SignerError;
use bdk_wallet::test_utils::*;
use bdk_wallet::{KeychainKind, SignOptions, psbt};
use bitcoin::{Amount, FeeRate, Psbt, TxIn, Witness};
Expand Down Expand Up @@ -115,6 +117,40 @@ fn test_psbt_sign_with_finalized() {
.unwrap();
}

/// Rejects mismatched witness_utxo and non_witness_utxo fields.
#[test]
fn test_sign_with_signers_rejects_mismatched_utxo() {
let descriptor = get_test_wpkh();
let (mut wallet, _) = get_funded_wallet_single(descriptor);
receive_output_in_latest_block(&mut wallet, Amount::from_sat(50_000));
let recipient = wallet.next_unused_address(KeychainKind::External);
let mut builder = wallet.build_tx();
builder.drain_to(recipient.script_pubkey()).drain_wallet();
let psbt = builder.finish().unwrap();
assert_eq!(psbt.inputs.len(), 2);

let signers = signers_from_descriptor(&wallet, descriptor);
for index in 0..psbt.inputs.len() {
let mut mismatched = psbt.clone();
mismatched.inputs[index]
.witness_utxo
.as_mut()
.unwrap()
.value -= Amount::from_sat(20_000);
assert_eq!(mismatched.fee_amount(), None);
let result = wallet.sign_with_signers(&mut mismatched, &[&signers], SignOptions::default());
assert!(matches!(result, Err(SignerError::InvalidNonWitnessUtxo)));
assert!(
mismatched
.inputs
.iter()
.all(|input| input.partial_sigs.is_empty()
&& input.final_script_sig.is_none()
&& input.final_script_witness.is_none())
);
}
}

#[test]
fn test_psbt_fee_rate_with_witness_utxo() {
use psbt::PsbtUtils;
Expand Down
Loading