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
3 changes: 3 additions & 0 deletions src/persist_test_utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Utilities for testing custom persistence backends for `bdk_wallet`

use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::sync::Arc;
use core::fmt;
use core::str::FromStr;
Expand Down Expand Up @@ -358,6 +359,7 @@ fn get_changeset(tx1: Transaction) -> ChangeSet {
tx_graph: tx_graph_changeset,
indexer: keychain_txout_changeset,
locked_outpoints: locked_outpoints_changeset,
self_payment_recipients: BTreeMap::new(),
}
}

Expand Down Expand Up @@ -418,6 +420,7 @@ fn get_changeset_two(tx2: Transaction) -> ChangeSet {
tx_graph: tx_graph_changeset,
indexer: keychain_txout_changeset,
locked_outpoints: locked_outpoints_changeset,
self_payment_recipients: BTreeMap::new(),
}
}

Expand Down
28 changes: 28 additions & 0 deletions src/wallet/changeset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ use serde::{Deserialize, Serialize};

use crate::locked_outpoints;

use alloc::collections::{BTreeMap, BTreeSet};
use bitcoin::Txid;

type IndexedTxGraphChangeSet =
indexed_tx_graph::ChangeSet<ConfirmationBlockTime, keychain_txout::ChangeSet>;

Expand Down Expand Up @@ -150,6 +153,14 @@ pub struct ChangeSet {
/// Changes to locked outpoints.
#[serde(default)]
pub locked_outpoints: locked_outpoints::ChangeSet,
/// Outputs that were intentionally added as recipients (not auto-generated
/// change) when sending to the wallet's own addresses. Used by
/// `build_fee_bump` to distinguish self-payment recipients from change.
///
/// `Some(indices)` = add these output indices as self-payment recipients.
/// `None` = remove this txid's tracking entirely (on confirmation/eviction).
#[serde(default)]
pub self_payment_recipients: BTreeMap<Txid, Option<BTreeSet<u32>>>,
}

impl Merge for ChangeSet {
Expand Down Expand Up @@ -184,6 +195,22 @@ impl Merge for ChangeSet {
// merge locked outpoints
self.locked_outpoints.merge(other.locked_outpoints);

// merge self-payment recipients
for (txid, change) in other.self_payment_recipients {
match change {
Some(indices) => {
self.self_payment_recipients
.entry(txid)
.or_default()
.get_or_insert_with(BTreeSet::new)
.extend(indices);
}
None => {
self.self_payment_recipients.remove(&txid);
}
}
}

Merge::merge(&mut self.local_chain, other.local_chain);
Merge::merge(&mut self.tx_graph, other.tx_graph);
Merge::merge(&mut self.indexer, other.indexer);
Expand All @@ -197,6 +224,7 @@ impl Merge for ChangeSet {
&& self.tx_graph.is_empty()
&& self.indexer.is_empty()
&& self.locked_outpoints.is_empty()
&& self.self_payment_recipients.is_empty()
}
}

Expand Down
13 changes: 13 additions & 0 deletions src/wallet/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,12 @@ pub enum CreateTxError {
MissingNonWitnessUtxo(OutPoint),
/// Miniscript PSBT error
MiniscriptPsbt(MiniscriptPsbtError),
/// A recipient output matches an address owned by the wallet.
/// Call `TxBuilder::allow_self_payment()` to proceed.
PaymentToOwnAddress {
/// Index of the recipient that matches the wallet's own address.
index: usize,
},
}

impl fmt::Display for CreateTxError {
Expand Down Expand Up @@ -286,6 +292,13 @@ impl fmt::Display for CreateTxError {
CreateTxError::MiniscriptPsbt(err) => {
write!(f, "Miniscript PSBT error: {err}")
}
CreateTxError::PaymentToOwnAddress { index } => {
write!(
f,
"Recipient at index {index} matches an address owned by this wallet. \
Call `TxBuilder::allow_self_payment()` to proceed"
)
}
}
}
}
Expand Down
141 changes: 138 additions & 3 deletions src/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub mod signer;
pub mod tx_builder;
pub(crate) mod utils;

use crate::collections::{BTreeMap, HashMap, HashSet};
use crate::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use crate::descriptor::{
DerivedDescriptor, DescriptorMeta, ExtendedDescriptor, ExtractPolicy, IntoWalletDescriptor,
Policy, XKeyUtils, calc_checksum, check_wallet_descriptor, error::Error as DescriptorError,
Expand Down Expand Up @@ -142,6 +142,10 @@ pub struct Wallet {
network: Network,
secp: SecpCtx,
locked_outpoints: HashSet<OutPoint>,
/// Tracks which transaction outputs were intentionally added as recipients
/// (not auto-generated change) when sending to the wallet's own addresses.
/// Used by `build_fee_bump` to distinguish self-payment recipients from change.
self_payment_recipients: BTreeMap<Txid, BTreeSet<u32>>,
}

/// An update to [`Wallet`].
Expand Down Expand Up @@ -399,6 +403,7 @@ impl Wallet {
stage,
secp,
locked_outpoints,
self_payment_recipients: BTreeMap::new(),
})
}

Expand Down Expand Up @@ -601,6 +606,11 @@ impl Wallet {
network,
secp,
locked_outpoints,
self_payment_recipients: changeset
.self_payment_recipients
.into_iter()
.filter_map(|(txid, opt)| opt.map(|set| (txid, set)))
.collect(),
}))
}

Expand Down Expand Up @@ -1479,6 +1489,19 @@ impl Wallet {
let recipients = params.recipients.iter().map(|(r, v)| (r, *v));

for (index, (script_pubkey, value)) in recipients.enumerate() {
// Check for self-payments — recipients that match the wallet's own addresses.
// This prevents accidental self-payments that build_fee_bump can mishandle
// by stripping internal-keychain outputs as change.
if !params.allow_self_payment
&& self
.tx_graph
.index
.index_of_spk(script_pubkey.clone())
.is_some()
{
return Err(CreateTxError::PaymentToOwnAddress { index });
}

if !params.allow_dust && value.is_dust(script_pubkey) && !script_pubkey.is_op_return() {
return Err(CreateTxError::OutputBelowDustLimit(index));
}
Expand Down Expand Up @@ -1603,8 +1626,45 @@ impl Wallet {
// Sort inputs/outputs according to the chosen algorithm.
params.ordering.sort_tx_with_aux_rand(&mut tx, rng);

// Clone recipients before complete_transaction consumes params
let recipients_for_tracking = params.recipients.clone();

let psbt = self.complete_transaction(tx, coin_selection.selected, params)?;

// Record self-payment recipient output indices for build_fee_bump.
// Only track outputs that were explicitly added as recipients (not
// auto-generated change) AND belong to the wallet's own keychains.
if !recipients_for_tracking.is_empty() {
let txid = psbt.unsigned_tx.compute_txid();
let mut self_payment_indices = BTreeSet::new();
for (output_index, txout) in psbt.unsigned_tx.output.iter().enumerate() {
// Check if this output is an explicit recipient (not change)
let is_recipient = recipients_for_tracking
.iter()
.any(|(spk, val)| *spk == txout.script_pubkey && *val == txout.value);
// Check if this output belongs to the wallet
if is_recipient
&& self
.tx_graph
.index
.index_of_spk(txout.script_pubkey.clone())
.is_some()
{
self_payment_indices.insert(output_index as u32);
}
}
if !self_payment_indices.is_empty() {
self.self_payment_recipients
.insert(txid, self_payment_indices.clone());
let mut sp_map = BTreeMap::new();
sp_map.insert(txid, Some(self_payment_indices));
self.stage.merge(ChangeSet {
self_payment_recipients: sp_map,
..Default::default()
});
}
}

// Recording changes to the change keychain.
if let (Excess::Change { .. }, Some((keychain, index))) = (excess, drain_index) {
if let Some((_, index_changeset)) =
Expand Down Expand Up @@ -1763,9 +1823,14 @@ impl Wallet {
.collect::<Result<_, _>>()?;

if tx.output.len() > 1 {
let self_payment_info = self.self_payment_recipients.get(&txid);
let change_keychain = self.map_keychain(KeychainKind::Internal);
let mut change_index = None;
for (index, txout) in tx.output.iter().enumerate() {
let change_keychain = self.map_keychain(KeychainKind::Internal);
// Skip outputs tracked as self-payment recipients
if self_payment_info.is_some_and(|set| set.contains(&(index as u32))) {
continue;
}
match txout_index.index_of_spk(txout.script_pubkey.clone()) {
Some((keychain, _)) if *keychain == change_keychain => {
change_index = Some(index)
Expand Down Expand Up @@ -2420,9 +2485,53 @@ impl Wallet {
changeset.merge(index_changeset.into());
changeset.merge(self.tx_graph.apply_update(update.tx_update).into());
self.stage.merge(changeset);

// Clean up self-payment tracking for confirmed transactions
self.cleanup_confirmed_self_payments();

Ok(())
}

/// Remove self-payment tracking entries for transactions that are now confirmed.
/// `build_fee_bump` only operates on unconfirmed transactions, so confirmed
/// entries are no longer needed.
fn cleanup_confirmed_self_payments(&mut self) {
if self.self_payment_recipients.is_empty() {
return;
}

let chain_tip = self.chain.tip().block_id();
let chain_positions: HashMap<Txid, ChainPosition<ConfirmationBlockTime>> = self
.tx_graph
.graph()
.list_canonical_txs(&self.chain, chain_tip, CanonicalizationParams::default())
.map(|c| (c.tx_node.txid, c.chain_position))
.collect();

let to_remove: Vec<Txid> = self
.self_payment_recipients
.keys()
.filter_map(|txid| {
chain_positions
.get(txid)
.filter(|pos| pos.is_confirmed())
.map(|_| *txid)
})
.collect();

if !to_remove.is_empty() {
let mut sp_map = BTreeMap::new();
for txid in &to_remove {
self.self_payment_recipients.remove(txid);
sp_map.insert(*txid, None);
}
self.stage.merge(ChangeSet {
self_payment_recipients: sp_map,
..Default::default()
});
}
}

/// Applies an update to the wallet, stages the changes, and returns events.
///
/// Usually you create an `update` by interacting with some blockchain data source and inserting
Expand Down Expand Up @@ -2764,6 +2873,7 @@ impl Wallet {
/// [`apply_unconfirmed_txs`]: Wallet::apply_unconfirmed_txs
/// [`start_sync_with_revealed_spks`]: Wallet::start_sync_with_revealed_spks
pub fn apply_evicted_txs(&mut self, evicted_txs: impl IntoIterator<Item = (Txid, u64)>) {
let evicted_txs: Vec<(Txid, u64)> = evicted_txs.into_iter().collect();
let chain = &self.chain;
let canon_txids: Vec<Txid> = self
.tx_graph
Expand All @@ -2778,11 +2888,36 @@ impl Wallet {

let changeset = self.tx_graph.batch_insert_relevant_evicted_at(
evicted_txs
.into_iter()
.iter()
.cloned()
.filter(|(txid, _)| canon_txids.contains(txid)),
);

self.stage.merge(changeset.into());

// Clean up self-payment tracking for evicted transactions
let to_remove: Vec<Txid> = self
.self_payment_recipients
.keys()
.filter(|txid| {
evicted_txs
.iter()
.any(|(evicted_txid, _)| evicted_txid == *txid)
})
.cloned()
.collect();

if !to_remove.is_empty() {
let mut sp_map = BTreeMap::new();
for txid in &to_remove {
self.self_payment_recipients.remove(txid);
sp_map.insert(*txid, None);
}
self.stage.merge(ChangeSet {
self_payment_recipients: sp_map,
..Default::default()
});
}
}

/// Apply evictions of the given transaction IDs with their associated timestamps and returns
Expand Down
15 changes: 15 additions & 0 deletions src/wallet/tx_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ pub(crate) struct TxParams {
pub(crate) bumping_fee: Option<PreviousFee>,
pub(crate) current_height: Option<absolute::LockTime>,
pub(crate) allow_dust: bool,
/// Whether to allow sending to an address owned by this wallet.
pub(crate) allow_self_payment: bool,
}

#[derive(Clone, Copy, Debug)]
Expand Down Expand Up @@ -759,6 +761,18 @@ impl<'a, Cs> TxBuilder<'a, Cs> {
self
}

/// Allow sending to an address owned by this wallet.
///
/// By default, `create_tx` returns an error if a recipient output matches an address
/// owned by the wallet. This prevents accidental self-payments that could be mishandled
/// by `build_fee_bump` (which strips internal-keychain outputs as change). Call this
/// method to override that check; the self-payment outputs will be tracked so that
/// `build_fee_bump` preserves them.
pub fn allow_self_payment(&mut self) -> &mut Self {
self.params.allow_self_payment = true;
self
}

/// Replace the recipients already added with a new list
pub fn set_recipients(&mut self, recipients: Vec<(ScriptBuf, Amount)>) -> &mut Self {
self.params.recipients = recipients;
Expand Down Expand Up @@ -1444,6 +1458,7 @@ mod test {
.unwrap()
.add_recipient(send_to.script_pubkey(), Amount::from_sat(60_000))
.fee_rate(FeeRate::from_sat_per_vb(1).unwrap())
.allow_self_payment()
.ordering(crate::TxOrdering::Untouched);
let psbt = tx_builder.finish().unwrap();

Expand Down
Loading