Merge PR 'Release wallet UTXOs when FundingBuilder rejects a coin selection' (#5634)
What changed, and why it matters
This change fixes a wallet bug in rust-lightning where a UTXO could be selected for a Lightning funding transaction, then rejected because its previous transaction was too large to fit in a Lightning peer message. Previously, that rejection could leave the UTXO locked or unavailable. The fix adds a size check during coin selection so oversized UTXOs are skipped before being selected, keeping them available for other uses. It also updates the public wallet API with a new parameter for this size limit.
Review downstream wallet implementations of CoinSelectionSource/CoinSelectionSourceSync to ensure they accept and honor the new max_input_prevtx_serialized_len parameter, especially custom wallets that may not inherit WalletSync's filtering. Monitor for any remaining paths where a selected UTXO can be rejected after selection without explicit lock release.
Security signals we found
API change to CoinSelectionSource::select_confirmed_utxos adding max_input_prevtx_serialized_len
WalletSync filters UTXOs by prevtx serialized length before selection
FundingBuilder enforces Lightning tx_add_input message-size limit at selection time
New regression test verifies oversized-prevtx UTXO remains available after coin-selection failure
Existing test renamed/updated from PrevTxTooLarge to CoinSelectionFailed path
Changelog frames this as an API update and UTXO-lock leak fix
Evidence from the diff
The commit extends CoinSelectionSource::select_confirmed_utxos and CoinSelectionSourceSync::select_confirmed_utxos with a new max_input_prevtx_serialized_len parameter. WalletSync now filters listed UTXOs by fetching each prevtx and comparing its serialized length against the limit before passing candidates to coin selection. FundingBuilder calls this with a limit derived from LN_MAX_MSG_LEN minus the tx_add_input message overhead, so UTXOs whose prevtx would exceed the message size are never selected. This prevents a FundingContributionError::PrevTxTooLarge path that could leak or strand UTXO locks. Bump-transaction callers pass u64::MAX because their inputs are not constrained by Lightning peer-message limits. Tests are added for both the oversized-prevtx rejection and the UTXO-availability-after-rejection behavior.
Changed components
lightning/src/util/wallet_utils.rs (CoinSelectionSource, CoinSelectionSourceSync, Wallet, WalletSync)lightning/src/ln/funding.rs (FundingBuilder, validation, tests)lightning/src/events/bump_transaction/mod.rs (bump-transaction coin-selection calls)lightning/src/ln/splicing_tests.rs (test wallet adapter)Inspect captured patch +148 / −15
### lightning/src/events/bump_transaction/mod.rs
@@ -423,6 +423,7 @@ impl<B: BroadcasterInterface, C: CoinSelectionSource, SP: SignerProvider, L: Log
// We added the commitment tx weight to the input satisfaction weight above, so
// increase the max_tx_weight by the same delta here.
+ commitment_tx_weight,
+ u64::MAX,
)
.await
.map_err(|()| {
@@ -708,6 +709,7 @@ impl<B: BroadcasterInterface, C: CoinSelectionSource, SP: SignerProvider, L: Log
&htlc_tx.output,
target_feerate_sat_per_1000_weight,
max_tx_weight,
+ u64::MAX,
)
.await
{
@@ -928,6 +930,7 @@ mod tests {
fn select_confirmed_utxos(
&self, _claim_id: Option<ClaimId>, must_spend: Vec<Input>, _must_pay_to: &[TxOut],
target_feerate_sat_per_1000_weight: u32, _max_tx_weight: u64,
+ _max_input_prevtx_serialized_len: u64,
) -> Result<CoinSelection, ()> {
let mut expected_selects = self.expected_selects.lock().unwrap();
let (weight, value, feerate, res) = expected_selects.remove(0);
### lightning/src/ln/funding.rs
@@ -529,7 +529,30 @@ fn estimate_transaction_fee(
Weight::from_wu(weight) * feerate
}
+// Every lightning message is prefixed with a 2-byte message type.
+const MESSAGE_TYPE_PREFIX_LEN: usize = 2;
+
+// A `tx_add_input` message template with an omitted `prevtx`, used to calculate the per-message
+// overhead when determining whether an input's previous transaction fits in a message.
+const TX_ADD_INPUT_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
+ channel_id: ChannelId([0; 32]),
+ serial_id: 0,
+ prevtx: None,
+ prevtx_out: 0,
+ sequence: 0,
+ // Mutually exclusive with prevtx, which is accounted for separately.
+ shared_input_txid: None,
+};
+
+/// The maximum serialized length of an input's previous transaction for the input to still fit
+/// within a `tx_add_input` message.
+fn max_input_prevtx_serialized_len() -> u64 {
+ use crate::util::ser::Writeable;
+ (LN_MAX_MSG_LEN - MESSAGE_TYPE_PREFIX_LEN - TX_ADD_INPUT_TEMPLATE.serialized_length()) as u64
+}
+
fn validate_inputs(inputs: &[ConfirmedUtxo]) -> Result<(), FundingContributionError> {
+ use crate::util::ser::Writeable;
let mut total_value = Amount::ZERO;
for (idx, input) in inputs.iter().enumerate() {
if inputs[..idx]
@@ -539,19 +562,8 @@ fn validate_inputs(inputs: &[ConfirmedUtxo]) -> Result<(), FundingContributionEr
return Err(FundingContributionError::InvalidSpliceValue);
}
- use crate::util::ser::Writeable;
- const MESSAGE_TYPE_PREFIX_LEN: usize = 2;
- const MESSAGE_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
- channel_id: ChannelId([0; 32]),
- serial_id: 0,
- prevtx: None,
- prevtx_out: 0,
- sequence: 0,
- // Mutually exclusive with prevtx, which is accounted for below.
- shared_input_txid: None,
- };
let message_len = MESSAGE_TYPE_PREFIX_LEN
- + MESSAGE_TEMPLATE.serialized_length()
+ + TX_ADD_INPUT_TEMPLATE.serialized_length()
+ input.prevtx.serialized_length();
(message_len <= LN_MAX_MSG_LEN)
.then(|| ())
@@ -1991,6 +2003,7 @@ impl<W: CoinSelectionSource + MaybeSend> AsyncFundingBuilder<W> {
&must_pay_to,
inner.feerate.to_sat_per_kwu() as u32,
u64::MAX,
+ max_input_prevtx_serialized_len(),
)
.await
.map_err(|_| FundingContributionError::CoinSelectionFailed)?;
@@ -2104,6 +2117,7 @@ impl<W: CoinSelectionSourceSync> SyncFundingBuilder<W> {
&must_pay_to,
inner.feerate.to_sat_per_kwu() as u32,
u64::MAX,
+ max_input_prevtx_serialized_len(),
)
.map_err(|_| FundingContributionError::CoinSelectionFailed)?;
@@ -2255,6 +2269,7 @@ mod tests {
fn select_confirmed_utxos(
&self, _claim_id: Option<ClaimId>, _must_spend: Vec<Input>, _must_pay_to: &[TxOut],
_target_feerate_sat_per_1000_weight: u32, _max_tx_weight: u64,
+ _max_input_prevtx_serialized_len: u64,
) -> Result<CoinSelection, ()> {
unreachable!("should not reach coin selection")
}
@@ -2273,6 +2288,7 @@ mod tests {
fn select_confirmed_utxos(
&self, _claim_id: Option<ClaimId>, _must_spend: Vec<Input>, must_pay_to: &[TxOut],
_target_feerate_sat_per_1000_weight: u32, _max_tx_weight: u64,
+ _max_input_prevtx_serialized_len: u64,
) -> Result<CoinSelection, ()> {
assert_eq!(
must_pay_to.iter().map(|output| output.value).collect::<Vec<_>>(),
@@ -3095,20 +3111,72 @@ mod tests {
assert_eq!(msg.serialized_length() + 2, crate::ln::LN_MAX_MSG_LEN + 1);
let wallet = SingleUtxoWallet {
- utxo: ConfirmedUtxo::new_p2wpkh(prevtx, 0).unwrap(),
+ utxo: ConfirmedUtxo::new_p2wpkh(prevtx.clone(), 0).unwrap(),
change_output: None,
};
assert!(matches!(
FundingTemplate::new(None, None, None, Amount::ZERO)
.with_prior_contribution(feerate, feerate)
- .with_coin_selection_source_sync(wallet)
+ .with_coin_selection_source_sync(&wallet)
.add_value(Amount::from_sat(10_000))
.unwrap()
.build(),
Err(FundingContributionError::PrevTxTooLarge),
));
}
+ #[test]
+ fn test_build_funding_contribution_skips_oversized_prevtx_utxo() {
+ use crate::util::test_utils::{TestLogger, TestWalletSource};
+ use crate::util::wallet_utils::WalletSync;
+ use bitcoin::secp256k1::SecretKey;
+
+ // A wallet UTXO whose prevtx does not fit in a `tx_add_input` message.
+ let feerate = FeeRate::from_sat_per_kwu(2000);
+ let prevtx = Transaction {
+ input: vec![],
+ output: vec![
+ funding_output_sats(50_000),
+ TxOut {
+ value: Amount::ZERO,
+ script_pubkey: ScriptBuf::from_bytes(vec![0; 65_430]),
+ },
+ ],
+ version: Version::TWO,
+ lock_time: bitcoin::absolute::LockTime::ZERO,
+ };
+ let wallet_source = TestWalletSource::new(SecretKey::from_slice(&[42; 32]).unwrap());
+ wallet_source.add_utxo(prevtx.clone(), 0);
+ let logger = TestLogger::new();
+ let wallet = WalletSync::new(&wallet_source, &logger);
+
+ // The wallet skips the UTXO up front, so coin selection fails instead of ever selecting
+ // an input that couldn't be sent in a `tx_add_input` message.
+ assert!(matches!(
+ FundingTemplate::new(None, None, None, Amount::ZERO)
+ .with_prior_contribution(feerate, feerate)
+ .with_coin_selection_source_sync(&wallet)
+ .add_value(Amount::from_sat(10_000))
+ .unwrap()
+ .build(),
+ Err(FundingContributionError::CoinSelectionFailed),
+ ));
+
+ // The UTXO was never selected, so it remains available, e.g., to fund a claim.
+ let claim_selection = wallet
+ .select_confirmed_utxos(
+ Some(ClaimId([42; 32])),
+ Vec::new(),
+ &[funding_output_sats(10_000)],
+ feerate.to_sat_per_kwu() as u32,
+ u64::MAX,
+ u64::MAX,
+ )
+ .unwrap();
+ let utxo = ConfirmedUtxo::new_p2wpkh(prevtx, 0).unwrap();
+ assert_eq!(claim_selection.confirmed_utxos[0].outpoint(), utxo.outpoint());
+ }
+
#[test]
fn test_for_acceptor_at_feerate_higher_change_adjusted() {
// Splice-in: higher target feerate reduces the change output.
@@ -4038,6 +4106,7 @@ mod tests {
fn select_confirmed_utxos(
&self, _claim_id: Option<ClaimId>, _must_spend: Vec<Input>, _must_pay_to: &[TxOut],
_target_feerate_sat_per_1000_weight: u32, _max_tx_weight: u64,
+ _max_input_prevtx_serialized_len: u64,
) -> Result<CoinSelection, ()> {
Ok(CoinSelection {
confirmed_utxos: vec![self.utxo.clone()],
### lightning/src/ln/splicing_tests.rs
@@ -145,6 +145,7 @@ impl CoinSelectionSourceSync for TightBudgetWallet {
fn select_confirmed_utxos(
&self, _claim_id: Option<crate::chain::ClaimId>, _must_spend: Vec<Input>,
_must_pay_to: &[TxOut], _target_feerate_sat_per_1000_weight: u32, _max_tx_weight: u64,
+ _max_input_prevtx_serialized_len: u64,
) -> Result<CoinSelection, ()> {
let prevout = TxOut {
value: self.utxo_value,
@@ -17574,6 +17575,7 @@ fn splice_abort_releases_wallet_utxos() {
&[claim_output],
FEERATE_FLOOR_SATS_PER_KW,
u64::MAX,
+ u64::MAX,
)
.unwrap();
assert_eq!(claim_selection.confirmed_utxos, first.inputs());
### lightning/src/util/wallet_utils.rs
@@ -374,6 +374,10 @@ pub trait CoinSelectionSource {
/// anchor transactions, we will try your coin selection again with the same input-output
/// set when you call [`ChannelMonitor::rebroadcast_pending_claims`], as anchor transactions
/// cannot be downsized.
+ /// 5. Each selected input's previous transaction must serialize to at most
+ /// `max_input_prevtx_serialized_len` bytes, e.g., because the input needs to fit in a
+ /// lightning peer message. If this constraint can't be met, return an `Err`. `u64::MAX`
+ /// indicates that no constraint applies.
///
/// Implementations must take note that [`Input::satisfaction_weight`] only tracks the weight of
/// the input's `script_sig` and `witness`. Some wallets, like Bitcoin Core's, may require
@@ -395,6 +399,7 @@ pub trait CoinSelectionSource {
fn select_confirmed_utxos<'a>(
&'a self, claim_id: Option<ClaimId>, must_spend: Vec<Input>, must_pay_to: &'a [TxOut],
target_feerate_sat_per_1000_weight: u32, max_tx_weight: u64,
+ max_input_prevtx_serialized_len: u64,
) -> impl Future<Output = Result<CoinSelection, ()>> + MaybeSend + 'a;
/// Signs and provides the full witness for all inputs within the transaction known to the
/// trait (i.e., any provided via [`CoinSelectionSource::select_confirmed_utxos`]).
@@ -419,13 +424,15 @@ where
fn select_confirmed_utxos<'a>(
&'a self, claim_id: Option<ClaimId>, must_spend: Vec<Input>, must_pay_to: &'a [TxOut],
target_feerate_sat_per_1000_weight: u32, max_tx_weight: u64,
+ max_input_prevtx_serialized_len: u64,
) -> impl Future<Output = Result<CoinSelection, ()>> + MaybeSend + 'a {
self.deref().select_confirmed_utxos(
claim_id,
must_spend,
must_pay_to,
target_feerate_sat_per_1000_weight,
max_tx_weight,
+ max_input_prevtx_serialized_len,
)
}
fn sign_psbt<'a>(
@@ -731,9 +738,43 @@ where
fn select_confirmed_utxos<'a>(
&'a self, claim_id: Option<ClaimId>, must_spend: Vec<Input>, must_pay_to: &'a [TxOut],
target_feerate_sat_per_1000_weight: u32, max_tx_weight: u64,
+ max_input_prevtx_serialized_len: u64,
) -> impl Future<Output = Result<CoinSelection, ()>> + MaybeSend + 'a {
async move {
let utxos = self.source.list_confirmed_utxos().await?;
+ let utxos = if max_input_prevtx_serialized_len != u64::MAX {
+ use crate::util::ser::Writeable;
+ let mut candidate_utxos = Vec::with_capacity(utxos.len());
+ for utxo in &utxos {
+ match self.source.get_prevtx(utxo.outpoint).await {
+ Ok(prevtx)
+ if prevtx.serialized_length() as u64
+ <= max_input_prevtx_serialized_len =>
+ {
+ candidate_utxos.push(utxo.clone());
+ },
+ Ok(prevtx) => {
+ log_debug!(
+ self.logger,
+ "Skipping UTXO {}: prevtx serializes to {} bytes, exceeding the maximum of {} bytes",
+ utxo.outpoint,
+ prevtx.serialized_length(),
+ max_input_prevtx_serialized_len,
+ );
+ },
+ Err(()) => {
+ log_error!(
+ self.logger,
+ "Skipping UTXO {}: failed to fetch prevtx while enforcing the prevtx length constraint",
+ utxo.outpoint,
+ );
+ },
+ }
+ }
+ candidate_utxos
+ } else {
+ utxos
+ };
// TODO: Use fee estimation utils when we upgrade to bitcoin v0.30.0.
let total_output_size: u64 = must_pay_to
.iter()
@@ -926,13 +967,15 @@ where
fn select_confirmed_utxos(
&self, claim_id: Option<ClaimId>, must_spend: Vec<Input>, must_pay_to: &[TxOut],
target_feerate_sat_per_1000_weight: u32, max_tx_weight: u64,
+ max_input_prevtx_serialized_len: u64,
) -> Result<CoinSelection, ()> {
let fut = self.wallet.select_confirmed_utxos(
claim_id,
must_spend,
must_pay_to,
target_feerate_sat_per_1000_weight,
max_tx_weight,
+ max_input_prevtx_serialized_len,
);
let mut waker = dummy_waker();
let mut ctx = task::Context::from_waker(&mut waker);
@@ -987,6 +1030,10 @@ pub trait CoinSelectionSourceSync {
/// anchor transactions, we will try your coin selection again with the same input-output
/// set when you call [`ChannelMonitor::rebroadcast_pending_claims`], as anchor transactions
/// cannot be downsized.
+ /// 5. Each selected input's previous transaction must serialize to at most
+ /// `max_input_prevtx_serialized_len` bytes, e.g., because the input needs to fit in a
+ /// lightning peer message. If this constraint can't be met, return an `Err`. `u64::MAX`
+ /// indicates that no constraint applies.
///
/// Implementations must take note that [`Input::satisfaction_weight`] only tracks the weight of
/// the input's `script_sig` and `witness`. Some wallets, like Bitcoin Core's, may require
@@ -1005,6 +1052,7 @@ pub trait CoinSelectionSourceSync {
fn select_confirmed_utxos(
&self, claim_id: Option<ClaimId>, must_spend: Vec<Input>, must_pay_to: &[TxOut],
target_feerate_sat_per_1000_weight: u32, max_tx_weight: u64,
+ max_input_prevtx_serialized_len: u64,
) -> Result<CoinSelection, ()>;
/// Signs and provides the full witness for all inputs within the transaction known to the
@@ -1028,13 +1076,15 @@ where
fn select_confirmed_utxos(
&self, claim_id: Option<ClaimId>, must_spend: Vec<Input>, must_pay_to: &[TxOut],
target_feerate_sat_per_1000_weight: u32, max_tx_weight: u64,
+ max_input_prevtx_serialized_len: u64,
) -> Result<CoinSelection, ()> {
self.deref().select_confirmed_utxos(
claim_id,
must_spend,
must_pay_to,
target_feerate_sat_per_1000_weight,
max_tx_weight,
+ max_input_prevtx_serialized_len,
)
}
fn sign_psbt(&self, psbt: Psbt) -> Result<Transaction, ()> {
@@ -1048,13 +1098,15 @@ impl<T: CoinSelectionSourceSync> CoinSelectionSource for CoinSelectionSourceSync
fn select_confirmed_utxos<'a>(
&'a self, claim_id: Option<ClaimId>, must_spend: Vec<Input>, must_pay_to: &'a [TxOut],
target_feerate_sat_per_1000_weight: u32, max_tx_weight: u64,
+ max_input_prevtx_serialized_len: u64,
) -> impl Future<Output = Result<CoinSelection, ()>> + MaybeSend + 'a {
let coins = self.0.select_confirmed_utxos(
claim_id,
must_spend,
must_pay_to,
target_feerate_sat_per_1000_weight,
max_tx_weight,
+ max_input_prevtx_serialized_len,
);
async move { coins }
}
@@ -1126,7 +1178,7 @@ mod tests {
value: Amount::from_sat(50_000),
script_pubkey: wallet.wallet.source.0.get_change_script().unwrap(),
}];
- wallet.select_confirmed_utxos(claim_id, Vec::new(), &must_pay_to, 253, u64::MAX)
+ wallet.select_confirmed_utxos(claim_id, Vec::new(), &must_pay_to, 253, u64::MAX, u64::MAX)
}
#[test]
### pending_changelog/5624-funding-builder-utxo-lock-leak.txt
@@ -0,0 +1,7 @@
+# API Updates
+
+ * `CoinSelectionSource::select_confirmed_utxos` and
+ `CoinSelectionSourceSync::select_confirmed_utxos` take a new `max_input_prevtx_serialized_len`
+ parameter bounding the serialized length of the previous transaction of each selected input,
+ e.g., for inputs that need to fit in a lightning peer message. `Wallet` and `WalletSync` exclude
+ UTXOs exceeding it from coin selection.Why this scored 48/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.