From f096c013193ab8a7ebf1ca6df0ec973928c99400 Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:48:00 +0300 Subject: [PATCH 1/5] feat(key-wallet): let a build exclude outpoints from coin selection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TransactionBuilder::exclude_outpoints names coins a build must never spend. A funding candidate that is excluded is left out of selection; an input the caller seeded with add_inputs that is excluded fails the build with BuilderError::ExcludedInput, since the caller asked for exactly that coin. Order-independent, accumulates, and records nothing on the wallet. For coins a caller holds back for now — e.g. the outputs of a send whose broadcast outcome is not known yet, which no node would accept a child of. Co-Authored-By: Claude Opus 5.5 --- .../transaction_builder.rs | 139 +++++++++++++++++- 1 file changed, 138 insertions(+), 1 deletion(-) diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index 2a456ca91..b3a6b1fad 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -95,6 +95,11 @@ pub struct TransactionBuilder { /// account that holds the UTXO, so each account reserves its own share of /// the chosen inputs — all under the one token this build is stamped with. funding: Vec<(ReservationSet, HashSet)>, + /// Outpoints coin selection must never spend. See [`Self::exclude_outpoints`]. + excluded: HashSet, + /// Outpoints the caller seeded through [`Self::add_inputs`], told apart + /// from funding candidates so an excluded one is refused, not dropped. + seeded: HashSet, } impl Default for TransactionBuilder { @@ -119,9 +124,26 @@ impl TransactionBuilder { special_payload: None, payload_finalizer: None, funding: Vec::new(), + excluded: HashSet::new(), + seeded: HashSet::new(), } } + /// Never spend these outpoints, whatever the strategy and whichever call + /// offered them. A funding candidate that is excluded is left out of + /// selection, as if the account did not hold it; an input the caller seeded + /// with [`Self::add_inputs`] that is excluded fails the build with + /// [`BuilderError::ExcludedInput`], since the caller asked for exactly that + /// coin. Applies regardless of call order and accumulates across calls. + /// + /// For coins the wallet holds but must not spend for now, decided by the + /// caller (for example the outputs of a transaction whose broadcast outcome + /// is not known yet); nothing is recorded on the wallet. + pub fn exclude_outpoints(mut self, outpoints: impl IntoIterator) -> Self { + self.excluded.extend(outpoints); + self + } + /// Restrict coin selection to final inputs: confirmed or /// InstantSend-locked UTXOs. Per DIP-0010 only such inputs are /// InstantSend-eligible, so transactions that must receive an @@ -233,7 +255,10 @@ impl TransactionBuilder { } pub fn add_inputs(mut self, inputs: impl IntoIterator) -> Self { - self.inputs.extend(inputs); + for utxo in inputs { + self.seeded.insert(utxo.outpoint); + self.inputs.push(utxo); + } self } @@ -553,6 +578,18 @@ impl TransactionBuilder { _ => self.outputs.iter().map(|o| o.value).sum(), }; + if let Some(outpoint) = + self.seeded.iter().find(|outpoint| self.excluded.contains(outpoint)).copied() + { + return Err(BuilderError::ExcludedInput { + outpoint, + }); + } + if !self.excluded.is_empty() { + let excluded = &self.excluded; + self.inputs.retain(|utxo| !excluded.contains(&utxo.outpoint)); + } + if self.require_final_inputs { self.inputs.retain(|utxo| utxo.is_confirmed || utxo.is_instantlocked); } @@ -1124,6 +1161,11 @@ pub enum BuilderError { len: usize, max: usize, }, + /// An input seeded with `add_inputs` is one the caller also excluded with + /// `exclude_outpoints`. + ExcludedInput { + outpoint: OutPoint, + }, } impl fmt::Display for BuilderError { @@ -1156,6 +1198,11 @@ impl fmt::Display for BuilderError { } => { write!(f, "OP_RETURN payload too large: {len} bytes (max {max})") } + Self::ExcludedInput { + outpoint, + } => { + write!(f, "Input {outpoint} is excluded from this transaction") + } } } } @@ -2762,4 +2809,94 @@ mod tests { > TransactionBuilder::estimated_payload_size(&placeholder) ); } + + #[test] + fn excluded_outpoint_is_never_offered_by_funding() { + let ctx = TestWalletContext::new_random(); + let account = + ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44 account").clone(); + + // Both orders: excluding before and after the funding call. + for exclude_first in [true, false] { + let mut funds = ManagedCoreFundsAccount::dummy_bip44(); + let held = Utxo::dummy(0x01, 900_000, 100, false, true); + let free = Utxo::dummy(0x02, 500_000, 100, false, true); + funds.utxos.insert(held.outpoint, held.clone()); + funds.utxos.insert(free.outpoint, free.clone()); + + let builder = TransactionBuilder::new() + .set_current_height(200) + .set_selection_strategy(SelectionStrategy::All); + let builder = if exclude_first { + builder.exclude_outpoints([held.outpoint]).add_funding(&mut funds, &account) + } else { + builder.add_funding(&mut funds, &account).exclude_outpoints([held.outpoint]) + }; + let (tx, _fee, _token) = builder + .add_output(&ctx.receive_address, 100_000) + .build_unsigned_reserved() + .expect("build"); + + let prevouts: Vec = tx.input.iter().map(|i| i.previous_output).collect(); + assert_eq!( + prevouts, + vec![free.outpoint], + "an excluded outpoint must not be selected (exclude_first = {exclude_first})" + ); + assert!(!funds.reservations().reserved(200).contains(&held.outpoint)); + } + } + + #[test] + fn excluded_outpoint_seeded_by_the_caller_is_refused() { + let ctx = TestWalletContext::new_random(); + let account = + ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44 account").clone(); + + let mut funds = ManagedCoreFundsAccount::dummy_bip44(); + let held = Utxo::dummy(0x01, 900_000, 100, false, true); + funds.utxos.insert(held.outpoint, held.clone()); + + // Explicitly seeded and excluded: refused with the outpoint named, not + // silently dropped — the caller asked for exactly this coin. + let result = TransactionBuilder::new() + .set_current_height(200) + .set_selection_strategy(SelectionStrategy::All) + .add_inputs(vec![held.clone()]) + .add_funding_reservation_only(&mut funds, &account) + .exclude_outpoints([held.outpoint]) + .add_output(&ctx.receive_address, 100_000) + .build_unsigned_reserved(); + + assert_eq!( + result.err(), + Some(BuilderError::ExcludedInput { + outpoint: held.outpoint + }) + ); + assert!(funds.reservations().reserved(200).is_empty(), "a refused build reserves nothing"); + } + + #[test] + fn excluding_the_only_coin_reports_insufficient_funds() { + let ctx = TestWalletContext::new_random(); + let account = + ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44 account").clone(); + + let mut funds = ManagedCoreFundsAccount::dummy_bip44(); + let held = Utxo::dummy(0x01, 900_000, 100, false, true); + funds.utxos.insert(held.outpoint, held.clone()); + + let result = TransactionBuilder::new() + .set_current_height(200) + .add_funding(&mut funds, &account) + .exclude_outpoints([held.outpoint]) + .add_output(&ctx.receive_address, 100_000) + .build_unsigned_reserved(); + + assert!( + matches!(result, Err(BuilderError::CoinSelection(_))), + "an excluded coin is not available: {result:?}" + ); + } } From c048c432eaf8221420bb98a1dc3b33a6809be8d9 Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:19:38 +0300 Subject: [PATCH 2/5] fix(key-wallet): name the first excluded seeded input, and test the release path Review follow-ups to exclude_outpoints: - ExcludedInput names the first excluded input in seeding order. It was picked from a HashSet, so with two excluded seeded inputs the reported outpoint changed from run to run. - Seeded inputs are tracked as one index range per add_inputs call and read only when an exclusion is set, instead of a per-input HashSet insert on every build. - The doc says what the exclusion does next to the existing rules: an excluded funding candidate is dropped like a reserved or locked one; an excluded seeded input is refused, unlike a reserved or non-final seeded input, which is dropped. Wallet-level helpers (build_and_sign_transaction and its funded builder) take no exclusions. - The "refused build reserves nothing" assertion could not fail (the refusal returns before selection). Replaced by a test that excludes a funding candidate, fails the sign after selection reserved the other coin, and checks nothing is left reserved. BuilderError is not #[non_exhaustive], so the ExcludedInput variant added in the previous commit breaks downstream code that matches it exhaustively. Co-Authored-By: Claude Opus 5.5 --- .../transaction_builder.rs | 122 +++++++++++++----- 1 file changed, 89 insertions(+), 33 deletions(-) diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index b3a6b1fad..c65ea9d47 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -97,9 +97,10 @@ pub struct TransactionBuilder { funding: Vec<(ReservationSet, HashSet)>, /// Outpoints coin selection must never spend. See [`Self::exclude_outpoints`]. excluded: HashSet, - /// Outpoints the caller seeded through [`Self::add_inputs`], told apart - /// from funding candidates so an excluded one is refused, not dropped. - seeded: HashSet, + /// Index ranges of `inputs` the caller seeded through [`Self::add_inputs`], + /// one per call, in call order — told apart from funding candidates so an + /// excluded one is refused, not dropped. Read only when `excluded` is set. + seeded: Vec>, } impl Default for TransactionBuilder { @@ -125,20 +126,29 @@ impl TransactionBuilder { payload_finalizer: None, funding: Vec::new(), excluded: HashSet::new(), - seeded: HashSet::new(), + seeded: Vec::new(), } } /// Never spend these outpoints, whatever the strategy and whichever call - /// offered them. A funding candidate that is excluded is left out of - /// selection, as if the account did not hold it; an input the caller seeded - /// with [`Self::add_inputs`] that is excluded fails the build with - /// [`BuilderError::ExcludedInput`], since the caller asked for exactly that - /// coin. Applies regardless of call order and accumulates across calls. + /// offered them. Applies regardless of call order and accumulates across + /// calls. + /// + /// - A funding candidate that is excluded is left out of selection, as if + /// the account did not hold it — like a reserved or locked one. + /// - An input the caller seeded with [`Self::add_inputs`] that is excluded + /// fails the build with [`BuilderError::ExcludedInput`], naming the first + /// such input in seeding order. Unlike a seeded input that is reserved or + /// not final (silently dropped), the caller asked for exactly that coin + /// and also said not to spend it, so the build refuses instead of + /// guessing. /// /// For coins the wallet holds but must not spend for now, decided by the /// caller (for example the outputs of a transaction whose broadcast outcome - /// is not known yet); nothing is recorded on the wallet. + /// is not known yet); nothing is recorded on the wallet. Only builds that + /// call this see the exclusion: the wallet-level helpers + /// (`ManagedWalletInfo::build_and_sign_transaction`, the funded builder + /// behind it) construct their own builder and take no exclusions. pub fn exclude_outpoints(mut self, outpoints: impl IntoIterator) -> Self { self.excluded.extend(outpoints); self @@ -255,9 +265,10 @@ impl TransactionBuilder { } pub fn add_inputs(mut self, inputs: impl IntoIterator) -> Self { - for utxo in inputs { - self.seeded.insert(utxo.outpoint); - self.inputs.push(utxo); + let start = self.inputs.len(); + self.inputs.extend(inputs); + if self.inputs.len() > start { + self.seeded.push(start..self.inputs.len()); } self } @@ -578,14 +589,19 @@ impl TransactionBuilder { _ => self.outputs.iter().map(|o| o.value).sum(), }; - if let Some(outpoint) = - self.seeded.iter().find(|outpoint| self.excluded.contains(outpoint)).copied() - { - return Err(BuilderError::ExcludedInput { - outpoint, - }); - } if !self.excluded.is_empty() { + // `inputs` is untouched since seeding, so the ranges still index it. + let refused = self + .seeded + .iter() + .flat_map(|range| self.inputs[range.clone()].iter()) + .map(|utxo| utxo.outpoint) + .find(|outpoint| self.excluded.contains(outpoint)); + if let Some(outpoint) = refused { + return Err(BuilderError::ExcludedInput { + outpoint, + }); + } let excluded = &self.excluded; self.inputs.retain(|utxo| !excluded.contains(&utxo.outpoint)); } @@ -2853,28 +2869,68 @@ mod tests { let account = ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44 account").clone(); + let mut funds = ManagedCoreFundsAccount::dummy_bip44(); + let free = Utxo::dummy(0x03, 300_000, 100, false, true); + let first = Utxo::dummy(0x01, 900_000, 100, false, true); + let second = Utxo::dummy(0x02, 800_000, 100, false, true); + for utxo in [&free, &first, &second] { + funds.utxos.insert(utxo.outpoint, utxo.clone()); + } + + // Explicitly seeded and excluded: refused, not silently dropped — the + // caller asked for exactly these coins. The first excluded one in + // seeding order is named, every run (the exclusion set is unordered). + for _ in 0..8 { + let result = TransactionBuilder::new() + .set_current_height(200) + .set_selection_strategy(SelectionStrategy::All) + .add_inputs(vec![free.clone(), first.clone()]) + .add_inputs(vec![second.clone()]) + .add_funding_reservation_only(&mut funds, &account) + .exclude_outpoints([second.outpoint, first.outpoint]) + .add_output(&ctx.receive_address, 100_000) + .build_unsigned_reserved(); + + assert_eq!( + result.err(), + Some(BuilderError::ExcludedInput { + outpoint: first.outpoint + }) + ); + } + } + + #[tokio::test] + async fn excluded_candidate_with_a_failed_sign_leaves_no_reservation() { + let ctx = TestWalletContext::new_random(); + let account = + ctx.wallet.accounts.standard_bip44_accounts.get(&0).expect("BIP44 account").clone(); + let mut funds = ManagedCoreFundsAccount::dummy_bip44(); let held = Utxo::dummy(0x01, 900_000, 100, false, true); + let free = Utxo::dummy(0x02, 1_000_000, 100, false, true); funds.utxos.insert(held.outpoint, held.clone()); + funds.utxos.insert(free.outpoint, free.clone()); - // Explicitly seeded and excluded: refused with the outpoint named, not - // silently dropped — the caller asked for exactly this coin. - let result = TransactionBuilder::new() + let builder = TransactionBuilder::new() .set_current_height(200) + .set_fee_rate(FeeRate::normal()) .set_selection_strategy(SelectionStrategy::All) - .add_inputs(vec![held.clone()]) - .add_funding_reservation_only(&mut funds, &account) + .add_funding(&mut funds, &account) .exclude_outpoints([held.outpoint]) - .add_output(&ctx.receive_address, 100_000) - .build_unsigned_reserved(); + .set_change_address(Address::dummy(Network::Testnet, 1)) + .add_output(&Address::dummy(Network::Testnet, 0), 500_000); - assert_eq!( - result.err(), - Some(BuilderError::ExcludedInput { - outpoint: held.outpoint - }) + // Selection succeeds on `free` and reserves it; signing then fails. + let result = builder.build_signed(&ctx.wallet, |_addr| None).await; + assert!(result.is_err()); + + // The excluded coin was never reserved, and the selected one is + // released: nothing is left behind either way. + assert!( + funds.reservations().reserved(200).is_empty(), + "a failed build must release what it reserved and never reserve an excluded coin" ); - assert!(funds.reservations().reserved(200).is_empty(), "a refused build reserves nothing"); } #[test] From 1cbb19a09c5cb055796395a510fc37968956ecfc Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:22:05 +0300 Subject: [PATCH 3/5] feat(key-wallet): expose the builder's outputs A caller explaining a failed selection (no candidates left after an exclusion) needs the amount that was requested; the builder kept it private. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/managed_wallet_info/transaction_builder.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index c65ea9d47..cddd7e09e 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -154,6 +154,12 @@ impl TransactionBuilder { self } + /// The outputs added so far, in order — for a caller that needs the + /// requested amount, e.g. to explain a failed selection. + pub fn outputs(&self) -> &[TxOut] { + &self.outputs + } + /// Restrict coin selection to final inputs: confirmed or /// InstantSend-locked UTXOs. Per DIP-0010 only such inputs are /// InstantSend-eligible, so transactions that must receive an From afd97dbeccc99f3ecaee7e5ec1c867c67e3abf75 Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:48:15 +0300 Subject: [PATCH 4/5] fix(key-wallet): track seeded outpoints in order, not index ranges MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The excluded-seeded-input check sliced `inputs` by stored ranges and relied on nothing reordering it in between — a future change could make that panic. An ordered list of the seeded outpoints gives the same "first in seeding order" answer with no index bookkeeping. outputs() now says what it does not include (a special payload's credit outputs; the placeholder amount under SelectionStrategy::All), and the failed-sign release test asserts SigningFailed, so it proves selection ran. Co-Authored-By: Claude Opus 5.5 --- .../transaction_builder.rs | 36 ++++++++++--------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index cddd7e09e..648ffe1d3 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -97,10 +97,10 @@ pub struct TransactionBuilder { funding: Vec<(ReservationSet, HashSet)>, /// Outpoints coin selection must never spend. See [`Self::exclude_outpoints`]. excluded: HashSet, - /// Index ranges of `inputs` the caller seeded through [`Self::add_inputs`], - /// one per call, in call order — told apart from funding candidates so an - /// excluded one is refused, not dropped. Read only when `excluded` is set. - seeded: Vec>, + /// Outpoints the caller seeded through [`Self::add_inputs`], in seeding + /// order — told apart from funding candidates so an excluded one is + /// refused, not dropped. Read only when `excluded` is set. + seeded: Vec, } impl Default for TransactionBuilder { @@ -154,8 +154,11 @@ impl TransactionBuilder { self } - /// The outputs added so far, in order — for a caller that needs the - /// requested amount, e.g. to explain a failed selection. + /// The explicit outputs added so far, in order. Not the full requested + /// amount in every build: a special payload's own outputs (an asset + /// lock's credit outputs) are not included, and under + /// `SelectionStrategy::All` the output amount is a placeholder the drain + /// replaces. pub fn outputs(&self) -> &[TxOut] { &self.outputs } @@ -273,9 +276,8 @@ impl TransactionBuilder { pub fn add_inputs(mut self, inputs: impl IntoIterator) -> Self { let start = self.inputs.len(); self.inputs.extend(inputs); - if self.inputs.len() > start { - self.seeded.push(start..self.inputs.len()); - } + let seeded = self.inputs[start..].iter().map(|utxo| utxo.outpoint); + self.seeded.extend(seeded); self } @@ -596,13 +598,8 @@ impl TransactionBuilder { }; if !self.excluded.is_empty() { - // `inputs` is untouched since seeding, so the ranges still index it. - let refused = self - .seeded - .iter() - .flat_map(|range| self.inputs[range.clone()].iter()) - .map(|utxo| utxo.outpoint) - .find(|outpoint| self.excluded.contains(outpoint)); + let refused = + self.seeded.iter().copied().find(|outpoint| self.excluded.contains(outpoint)); if let Some(outpoint) = refused { return Err(BuilderError::ExcludedInput { outpoint, @@ -2928,8 +2925,13 @@ mod tests { .add_output(&Address::dummy(Network::Testnet, 0), 500_000); // Selection succeeds on `free` and reserves it; signing then fails. + // Asserting the variant proves the build got past selection, so the + // release below is the failed-sign path, not an early return. let result = builder.build_signed(&ctx.wallet, |_addr| None).await; - assert!(result.is_err()); + assert!( + matches!(result, Err(BuilderError::SigningFailed(_))), + "the build must fail at signing, after selection reserved: {result:?}" + ); // The excluded coin was never reserved, and the selected one is // released: nothing is left behind either way. From 2e0202f2b7856d943adb233c9f65e39602e40cbf Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:15:20 +0300 Subject: [PATCH 5/5] feat(key-wallet): expose the builder's fee rate, strategy and payload presence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Read-only getters a caller needs to explain a failed selection at the build's own fee rate, and to tell a drain or a special-payload build — whose requested amount outputs() does not show — apart. Co-Authored-By: Claude Opus 5.5 --- .../managed_wallet_info/transaction_builder.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs index 648ffe1d3..3ac529185 100644 --- a/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs +++ b/key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs @@ -163,6 +163,22 @@ impl TransactionBuilder { &self.outputs } + /// The fee rate the build will pay. + pub fn fee_rate(&self) -> FeeRate { + self.fee_rate + } + + /// The coin-selection strategy the build will use. + pub fn selection_strategy(&self) -> &SelectionStrategy { + &self.selection_strategy + } + + /// Whether the build carries a special-transaction payload — whose own + /// outputs or size [`Self::outputs`] does not show. + pub fn has_special_payload(&self) -> bool { + self.special_payload.is_some() || self.payload_finalizer.is_some() + } + /// Restrict coin selection to final inputs: confirmed or /// InstantSend-locked UTXOs. Per DIP-0010 only such inputs are /// InstantSend-eligible, so transactions that must receive an