Merge PR 'Preserve live HTLCs when rejecting stale counterparty commitment updates' (#5733)
What changed, and why it matters
This patch fixes a bug in the Lightning Dev Kit's channel monitor. When a counterparty's commitment update was rejected (for example, because a pending splice was discarded after the funding was spent on-chain), the monitor could incorrectly fail back HTLCs that were still live on the unchanged current commitment. This could cause a node to incorrectly report a payment as failed and release funds, even though the HTLC was still valid and unspent on-chain. The fix tracks which commitment transaction IDs came from the rejected update so only truly new HTLCs are failed, while HTLCs on the unchanged current commitment are preserved.
Review and merge the patch. Ensure downstream users running channel monitors with splicing and deferred monitor updates upgrade promptly, as the bug can cause incorrect HTLC failure behavior during force-close/splice-discard scenarios.
Security signals we found
Incorrect HTLC failure could lead to premature payment release or funds loss
Channel monitor update rejection edge case during splice discard
Regression test added for rejected counterparty commitment update handling
Logic change in `fail_htlcs_from_update_after_funding_spend` to skip update-carried commitment txids
Evidence from the diff
The change modifies ChannelMonitorImpl::fail_htlcs_from_update_after_funding_spend in channelmonitor.rs to accept an iterator of update_commitment_txids representing the counterparty commitments carried by the monitor update. Previously, the function only checked prev_counterparty_commitment_txid to determine if an HTLC source was already known. After the fix, it checks both current_counterparty_commitment_txid and prev_counterparty_commitment_txid, skipping any whose txid appears in the update. This prevents HTLCs on the unchanged current commitment from being treated as new and failed when an update is rejected before changing commitments. The patch also adds a regression test test_rejected_splice_update_does_not_fail_live_counterparty_htlc that reproduces the splice-discard scenario and asserts the first payment (live on current commitment) is not failed while the second (new in rejected update) is.
Changed components
lightning/src/chain/channelmonitor.rsChannelMonitorImpl::fail_htlcs_from_update_after_funding_spendlightning/src/ln/chanmon_update_fail_tests.rsInspect captured patch +282 / −10
### lightning/src/chain/channelmonitor.rs
@@ -4628,14 +4628,15 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
for update in updates.updates.iter() {
match update {
ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
- htlc_outputs, ..
+ htlc_outputs, commitment_txid, ..
} => {
// Only outbound HTLCs have a source; inbound ones are `None`
// and skipped by the `filter_map`.
self.fail_htlcs_from_update_after_funding_spend(
htlc_outputs.iter().filter_map(|(htlc, source)| {
source.as_ref().map(|s| (&**s, htlc.payment_hash, htlc.amount_msat))
}),
+ core::iter::once(*commitment_txid),
logger,
);
},
@@ -4663,6 +4664,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
});
self.fail_htlcs_from_update_after_funding_spend(
nondust.chain(dust),
+ commitment_txs.iter().map(|tx| tx.trust().txid()),
logger,
);
},
@@ -4800,9 +4802,20 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
/// Only truly new HTLCs (not present in any previously-known commitment) need to be failed
/// here. HTLCs that were already tracked by the monitor will be handled by the existing
/// `fail_unbroadcast_htlcs` logic when the spending transaction confirms.
- fn fail_htlcs_from_update_after_funding_spend<'a, L: Logger>(
+ ///
+ /// `update_commitment_txids` are the txids of the counterparty commitments carried by the
+ /// update. They allow deducing which HTLCs were already known to this monitor prior to the
+ /// update: of the current and prev counterparty commitments we track, any whose txid is not
+ /// among them predates the update. That includes the unchanged current counterparty
+ /// commitment when the update was rejected before changing any commitments, in which case
+ /// HTLCs it carries must not be failed while their on-chain output remains unspent.
+ fn fail_htlcs_from_update_after_funding_spend<
+ 'a,
+ I: Iterator<Item = Txid> + Clone,
+ L: Logger,
+ >(
&mut self, htlcs: impl Iterator<Item = (&'a HTLCSource, PaymentHash, u64)>,
- logger: &WithContext<L>,
+ update_commitment_txids: I, logger: &WithContext<L>,
) {
let pending_spend_entry = self
.onchain_events_awaiting_threshold_conf
@@ -4813,14 +4826,23 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
return;
}
- // Check HTLC sources against all previously-known commitments to find truly new
- // ones. After the update has been applied, `prev_counterparty_commitment_txid` holds
- // what was `current` before this update, so it represents the already-known
- // counterparty state. HTLCs already present in any of these will be handled by
- // `fail_unbroadcast_htlcs` when the spending transaction confirms.
+ // Check HTLC sources against the current and prev counterparty commitments to find
+ // truly new ones, skipping commitments the update introduced. When the update applied
+ // cleanly, the current counterparty commitment is the one it introduced and is skipped,
+ // leaving `prev_counterparty_commitment_txid` as the already-known state. When the
+ // update was rejected before changing any commitments, both predate the update. HTLCs
+ // already present in either will be handled by `fail_unbroadcast_htlcs` when the
+ // spending transaction confirms.
let is_source_known = |source: &HTLCSource| {
- if let Some(ref txid) = self.funding.prev_counterparty_commitment_txid {
- if let Some(htlc_list) = self.funding.counterparty_claimable_outpoints.get(txid) {
+ let known_commitment_txids = [
+ self.funding.current_counterparty_commitment_txid,
+ self.funding.prev_counterparty_commitment_txid,
+ ];
+ for txid in known_commitment_txids.into_iter().flatten() {
+ if update_commitment_txids.clone().any(|update_txid| update_txid == txid) {
+ continue;
+ }
+ if let Some(htlc_list) = self.funding.counterparty_claimable_outpoints.get(&txid) {
if htlc_list.iter().any(|(_, s)| s.as_ref().map(|s| s.as_ref()) == Some(source))
{
return true;
### lightning/src/ln/chanmon_update_fail_tests.rs
@@ -30,6 +30,9 @@ use crate::ln::msgs::{
};
use crate::ln::onion_utils::LocalHTLCFailureReason;
use crate::ln::outbound_payment::{RecipientOnionFields, Retry};
+use crate::ln::splicing_tests::{
+ complete_interactive_funding_negotiation, complete_splice_handshake, initiate_splice_in,
+};
use crate::ln::types::ChannelId;
use crate::routing::router::{PaymentParameters, RouteParameters};
use crate::sign::NodeSigner;
@@ -49,6 +52,7 @@ use crate::util::wakers::Notifier;
use bitcoin::constants::genesis_block;
use bitcoin::hash_types::BlockHash;
use bitcoin::network::Network;
+use bitcoin::Amount;
use crate::ln::functional_test_utils::*;
@@ -5765,6 +5769,252 @@ fn test_late_counterparty_commitment_update_after_funding_spend_fully_confirmed(
do_test_late_counterparty_commitment_update_after_funding_spend(true);
}
+#[test]
+fn test_rejected_splice_update_does_not_fail_live_counterparty_htlc() {
+ // Tests that when a counterparty commitment update is rejected by the monitor, outbound
+ // HTLCs that still live on the unchanged current counterparty commitment are not failed
+ // back while their on-chain output remains unspent, but truly new HTLCs from the rejected
+ // update are.
+ //
+ // The update is rejected by building it against a pending splice whose scope has already
+ // been discarded: B splices its channel with C but leaves the new funding unconfirmed, and
+ // the pending scope is dropped once the pre-splice funding is seen spent on-chain and the
+ // spend irrevocably confirms. C withholds the signature for B's commitment carrying the
+ // first HTLC, so it exists only on B's current counterparty commitment, and the second
+ // payment is sent while the update carrying both HTLCs is queued behind a paused flush.
+ let chanmon_cfgs = create_chanmon_cfgs(2);
+ let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+ // Only B defers its monitor updates, so that the update carrying both HTLCs can be queued
+ // behind a paused flush while C's updates are applied immediately.
+ node_cfgs[0].chain_monitor = test_utils::TestChainMonitor::new_deferred(
+ Some(&chanmon_cfgs[0].chain_source),
+ &chanmon_cfgs[0].tx_broadcaster,
+ &chanmon_cfgs[0].logger,
+ &chanmon_cfgs[0].fee_estimator,
+ &chanmon_cfgs[0].persister,
+ &chanmon_cfgs[0].keys_manager,
+ );
+ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+ let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+ let node_b_id = nodes[0].node.get_our_node_id();
+ let node_c_id = nodes[1].node.get_our_node_id();
+ let flush_and_process = |node: &Node| -> Vec<Event> {
+ let pending_count = node.chain_monitor.chain_monitor.pending_operation_count();
+ node.chain_monitor.chain_monitor.flush(pending_count, &node.logger);
+ // Process the update completions so that actions and messages held pending them are
+ // released.
+ node.node.get_and_clear_pending_events()
+ };
+ let reset_monitor_count = |node: &Node| {
+ node.chain_monitor.added_monitors.lock().unwrap().clear();
+ };
+
+ let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
+
+ provide_utxo_reserves(&nodes, 1, Amount::from_sat(100_000));
+
+ // Splice the channel without confirming the new funding transaction, leaving a pending
+ // funding scope in the monitor. Quiescence ends once the splice transaction is signed, so
+ // HTLC updates resume while the splice is pending.
+ //
+ // The signing dance is inlined from `sign_interactive_funding_tx` as B's deferred monitor
+ // updates must be flushed mid-signing for B to release its `tx_signatures`.
+ let splice_contribution =
+ initiate_splice_in(&nodes[0], &nodes[1], chan_id, Amount::from_sat(25_000));
+ let new_funding_script = complete_splice_handshake(&nodes[0], &nodes[1]);
+ complete_interactive_funding_negotiation(
+ &nodes[0],
+ &nodes[1],
+ chan_id,
+ splice_contribution,
+ new_funding_script,
+ );
+
+ if let Event::FundingTransactionReadyForSigning {
+ channel_id,
+ counterparty_node_id,
+ unsigned_transaction,
+ ..
+ } = get_event!(nodes[0], Event::FundingTransactionReadyForSigning)
+ {
+ let partially_signed_tx = nodes[0].wallet_source.sign_tx(unsigned_transaction).unwrap();
+ nodes[0]
+ .node
+ .funding_transaction_signed(&channel_id, &counterparty_node_id, partially_signed_tx)
+ .unwrap();
+ } else {
+ panic!();
+ }
+
+ let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
+ assert_eq!(msg_events.len(), 1);
+ let initial_commitment_signed =
+ if let MessageSendEvent::UpdateHTLCs { ref updates, .. } = &msg_events[0] {
+ updates.commitment_signed[0].clone()
+ } else {
+ panic!();
+ };
+ let splice_funding_txid = initial_commitment_signed.funding_txid.unwrap();
+ nodes[1].node.handle_commitment_signed(node_b_id, &initial_commitment_signed);
+
+ let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
+ assert_eq!(msg_events.len(), 2);
+ if let MessageSendEvent::UpdateHTLCs { ref updates, .. } = &msg_events[0] {
+ nodes[0].node.handle_commitment_signed(node_c_id, &updates.commitment_signed[0]);
+ } else {
+ panic!();
+ }
+ if let MessageSendEvent::SendTxSignatures { ref msg, .. } = &msg_events[1] {
+ nodes[0].node.handle_tx_signatures(node_c_id, msg);
+ } else {
+ panic!();
+ }
+ // Processing the completions releases B's `tx_signatures` and its `SpliceNegotiated` event.
+ let events = flush_and_process(&nodes[0]);
+ assert!(
+ events.iter().any(|event| matches!(event, Event::SpliceNegotiated { .. })),
+ "{events:?}"
+ );
+
+ let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
+ assert_eq!(msg_events.len(), 1);
+ if let MessageSendEvent::SendTxSignatures { ref msg, .. } = &msg_events[0] {
+ nodes[1].node.handle_tx_signatures(node_b_id, msg);
+ } else {
+ panic!();
+ }
+ flush_and_process(&nodes[0]);
+ flush_and_process(&nodes[1]);
+
+ // Send a payment to C. C revokes its prior commitment but withholds the signature for B's
+ // commitment, leaving the HTLC only on B's current counterparty commitment.
+ let (route_1, payment_hash_1, _, payment_secret_1) =
+ get_route_and_payment_hash!(&nodes[0], &nodes[1], 1_000_000);
+ nodes[0]
+ .node
+ .send_payment_with_route(
+ route_1,
+ payment_hash_1,
+ RecipientOnionFields::secret_only(payment_secret_1, 1_000_000),
+ PaymentId(payment_hash_1.0),
+ )
+ .unwrap();
+ flush_and_process(&nodes[0]);
+
+ let mut events = nodes[0].node.get_and_clear_pending_msg_events();
+ assert_eq!(events.len(), 1);
+ let payment_event_1 = SendEvent::from_event(events.pop().unwrap());
+ nodes[1].node.handle_update_add_htlc(node_b_id, &payment_event_1.msgs[0]);
+ nodes[1].node.handle_commitment_signed_batch_test(node_b_id, &payment_event_1.commitment_msg);
+ flush_and_process(&nodes[1]);
+ let (cs_raa, cs_commitment_signed) = get_revoke_commit_msgs(&nodes[1], &node_b_id);
+
+ // Deliver only C's revoke_and_ack, withholding the commitment_signed for B's commitment.
+ nodes[0].node.handle_revoke_and_ack(node_c_id, &cs_raa);
+ flush_and_process(&nodes[0]);
+ drop(cs_commitment_signed);
+
+ // Pause flushing so the next counterparty commitment update stays queued, then send a second
+ // payment without delivering the messages to C, so C never learns of it.
+ nodes[0].chain_monitor.pause_flush.store(true, Ordering::Release);
+ let (route_2, payment_hash_2, _, payment_secret_2) =
+ get_route_and_payment_hash!(&nodes[0], &nodes[1], 1_000_000);
+ nodes[0]
+ .node
+ .send_payment_with_route(
+ route_2,
+ payment_hash_2,
+ RecipientOnionFields::secret_only(payment_secret_2, 1_000_000),
+ PaymentId(payment_hash_2.0),
+ )
+ .unwrap();
+ drop(nodes[0].node.get_and_clear_pending_msg_events());
+
+ reset_monitor_count(&nodes[0]);
+
+ // C force-closes, broadcasting its commitment transaction carrying the first HTLC.
+ let cs_commitment_tx = get_local_commitment_txn!(nodes[1], chan_id);
+ assert_eq!(cs_commitment_tx.len(), 1);
+ nodes[1]
+ .node
+ .force_close_broadcasting_latest_txn(
+ &chan_id,
+ &node_b_id,
+ "Channel force-closed".to_owned(),
+ )
+ .unwrap();
+ drop(nodes[1].node.get_and_clear_pending_msg_events());
+ let events = nodes[1].node.get_and_clear_pending_events();
+ assert!(
+ events.iter().any(|event| matches!(
+ event,
+ Event::ChannelClosed { reason: ClosureReason::HolderForceClosed { .. }, .. }
+ )),
+ "{events:?}"
+ );
+ reset_monitor_count(&nodes[1]);
+
+ mine_transaction(&nodes[0], &cs_commitment_tx[0]);
+ connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
+
+ // The funding spend irrevocably confirmed, closing the channel and discarding the pending
+ // splice scope.
+ let events = nodes[0].node.get_and_clear_pending_events();
+ assert!(
+ events.iter().any(|event| matches!(
+ event,
+ Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. }
+ )),
+ "{events:?}"
+ );
+ check_added_monitors(&nodes[0], 1);
+ check_closed_broadcast(&nodes[0], 1, true);
+
+ // Flush the queued updates. The batch carries commitments for the discarded splice scope and
+ // is therefore rejected, but the HTLCs it carries are still processed.
+ nodes[0].chain_monitor.pause_flush.store(false, Ordering::Release);
+ let pending_count = nodes[0].chain_monitor.chain_monitor.pending_operation_count();
+ nodes[0].chain_monitor.chain_monitor.flush(pending_count, &nodes[0].logger);
+
+ // The HTLC still living on the unchanged current counterparty commitment must not be failed
+ // back, while the truly new HTLC from the rejected update must be.
+ let mut events = Vec::new();
+ for _ in 0..10 {
+ let drained = nodes[0].node.get_and_clear_pending_events();
+ if drained.is_empty() {
+ break;
+ }
+ events.extend(drained);
+ }
+ for event in &events {
+ if let Event::PaymentPathFailed { payment_hash: failed_hash, .. } = event {
+ assert_ne!(
+ failed_hash, &payment_hash_1,
+ "HTLCs on the unchanged current counterparty commitment must not be failed back"
+ );
+ }
+ }
+ let failed_events = events
+ .into_iter()
+ .filter(|event| {
+ matches!(event, Event::PaymentPathFailed { .. } | Event::PaymentFailed { .. })
+ })
+ .collect::<Vec<_>>();
+ expect_payment_failed_conditions_event(
+ failed_events,
+ payment_hash_2,
+ false,
+ PaymentFailedConditions::new(),
+ );
+ // Failing the payment back releases it, generating a `ReleasePaymentComplete` update.
+ check_added_monitors(&nodes[0], 1);
+
+ // The discarded splice scope's funding output is no longer tracked by the monitor, but the
+ // chain source retains its registration.
+ nodes[0].chain_source.remove_watched_by_txid(splice_funding_txid);
+}
+
fn do_test_late_counterparty_commitment_update_after_holder_commitment_spend(dust: bool) {
// Tests that when the confirmed spending transaction is a holder commitment, HTLCs that
// have non-dust outputs in the holder commitment are NOT failed byWhy this scored 66/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.