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..3ac529185 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,12 @@ 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`], 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 { @@ -119,9 +125,60 @@ impl TransactionBuilder { special_payload: None, payload_finalizer: None, funding: Vec::new(), + excluded: HashSet::new(), + seeded: Vec::new(), } } + /// Never spend these outpoints, whatever the strategy and whichever call + /// 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. 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 + } + + /// 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 + } + + /// 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 @@ -233,7 +290,10 @@ impl TransactionBuilder { } pub fn add_inputs(mut self, inputs: impl IntoIterator) -> Self { + let start = self.inputs.len(); self.inputs.extend(inputs); + let seeded = self.inputs[start..].iter().map(|utxo| utxo.outpoint); + self.seeded.extend(seeded); self } @@ -553,6 +613,18 @@ impl TransactionBuilder { _ => self.outputs.iter().map(|o| o.value).sum(), }; + if !self.excluded.is_empty() { + let refused = + self.seeded.iter().copied().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)); + } + if self.require_final_inputs { self.inputs.retain(|utxo| utxo.is_confirmed || utxo.is_instantlocked); } @@ -1124,6 +1196,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 +1233,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 +2844,139 @@ 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 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()); + + let builder = TransactionBuilder::new() + .set_current_height(200) + .set_fee_rate(FeeRate::normal()) + .set_selection_strategy(SelectionStrategy::All) + .add_funding(&mut funds, &account) + .exclude_outpoints([held.outpoint]) + .set_change_address(Address::dummy(Network::Testnet, 1)) + .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!( + 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. + assert!( + funds.reservations().reserved(200).is_empty(), + "a failed build must release what it reserved and never reserve an excluded coin" + ); + } + + #[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:?}" + ); + } }