Handle claim replay for payments which reused a payment hash
What changed, and why it matters
This commit fixes a bug in LDK (a Lightning Network implementation in Rust) where the same payment hash could be used for multiple payments. On restart, the software could either crash repeatedly or incorrectly mark a different, unclaimed payment as already claimed. The fix makes sure each payment is tracked by its unique ID, not just by its payment hash, so claims are replayed correctly after a restart.
Review and merge the patch. Run the new regression tests covering reused payment hash scenarios. Consider whether any deployed nodes may have persisted inconsistent state from prior versions and advise operators to upgrade before restarting.
Security signals we found
Payment hash collision handling bug
ChannelManager deserialization failure on startup
Incorrect PaymentClaimed event generation for wrong payment
Stale claimable payment not removed correctly
MonitorUpdateCompletionAction now keyed by PaymentId
Claim replay logic hardened against reused payment hashes
Evidence from the diff
The patch resolves two related issues in ChannelManager claim replay when payment hashes are reused. Previously, replayed claims were matched only by payment_hash against claimable_payments and pending_claiming_payments. This caused ChannelManager::read to fail on every startup if a delayed PaymentClaimed existed, and could drop a different unclaimed payment with the same hash. The fix adds payment_id to MonitorUpdateCompletionAction::PaymentClaimed, queues PaymentClaimed events immediately for replayed claims (since they are durable in ChannelMonitor), and only removes a payment from claimable_payments if it shares an HTLC with the replayed claim. New tests cover MPP and keysend scenarios with reused payment hashes.
Changed components
lightning/src/ln/channelmanager.rslightning/src/ln/chanmon_update_fail_tests.rslightning/src/ln/reload_tests.rsInspect captured patch +552 / −81
### lightning/src/ln/chanmon_update_fail_tests.rs
@@ -6048,3 +6048,104 @@ fn test_force_close_with_blocked_raa_htlc_fail() {
expected_payments.sort();
assert_eq!(failed_payments, expected_payments);
}
+
+#[test]
+fn test_mpp_claim_completion_with_pending_claim_reusing_payment_hash() {
+ // Once the first `ChannelMonitorUpdate` of an MPP claim completes we generate the
+ // `PaymentClaimed` event, allowing another payment with the same payment hash to be received
+ // and claimed while `ChannelMonitorUpdate`s for the MPP claim's other HTLCs are still pending.
+ // Test that those completing doesn't generate the `PaymentClaimed` for the second payment
+ // before its own `ChannelMonitorUpdate` completed.
+ let chanmon_cfgs = create_chanmon_cfgs(4);
+ let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
+ let mut config = test_default_channel_config();
+ // Force the first payment to be split across both paths.
+ config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
+ 10;
+ let configs: [Option<_>; 4] = core::array::from_fn(|_| Some(config.clone()));
+ let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &configs);
+ let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
+ let node_b_id = nodes[1].node.get_our_node_id();
+ let node_c_id = nodes[2].node.get_our_node_id();
+ let node_d_id = nodes[3].node.get_our_node_id();
+
+ create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
+ create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
+ let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0).2;
+ let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0).2;
+
+ let claimable_id = |claimable: Option<Event>| match claimable {
+ Some(Event::PaymentClaimable { payment_id: Some(payment_id), .. }) => payment_id,
+ _ => panic!("Expected a PaymentClaimable"),
+ };
+ let claimed_ids = || -> Vec<PaymentId> {
+ let events = nodes[3].node.get_and_clear_pending_events();
+ let ids = events.into_iter().map(|event| match event {
+ Event::PaymentClaimed { payment_id: Some(payment_id), .. } => payment_id,
+ _ => panic!("Unexpected event {:?}", event),
+ });
+ ids.collect()
+ };
+
+ let amt_msat = 15_000_000;
+ let (route, payment_hash, payment_preimage, payment_secret) =
+ get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
+ assert_eq!(route.paths.len(), 2);
+ let onion = RecipientOnionFields::secret_only(payment_secret, amt_msat);
+ nodes[0].node.send_payment_with_route(route, payment_hash, onion, PaymentId([1; 32])).unwrap();
+ check_added_monitors(&nodes[0], 2);
+ let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
+ let node_b_msgs = remove_first_msg_event_to_node(&node_b_id, &mut send_events);
+ let node_c_msgs = remove_first_msg_event_to_node(&node_c_id, &mut send_events);
+ let path = &[&nodes[1], &nodes[3]];
+ let args = PassAlongPathArgs::new(&nodes[0], path, amt_msat, payment_hash, node_b_msgs)
+ .with_payment_secret(payment_secret)
+ .without_claimable_event();
+ do_pass_along_path(args);
+ let path = &[&nodes[2], &nodes[3]];
+ let args = PassAlongPathArgs::new(&nodes[0], path, amt_msat, payment_hash, node_c_msgs)
+ .with_payment_secret(payment_secret);
+ let mpp_id = claimable_id(do_pass_along_path(args));
+
+ // Claim the MPP payment, completing only the first of its two `ChannelMonitorUpdate`s.
+ chanmon_cfgs[3].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
+ chanmon_cfgs[3].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
+ nodes[3].node.claim_funds(payment_preimage, Default::default());
+ check_added_monitors(&nodes[3], 2);
+ assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
+
+ nodes[3].chain_monitor.complete_sole_pending_chan_update(&chan_id_bd);
+ assert_eq!(claimed_ids(), [mpp_id]);
+ // We don't bother delivering the claims to the other nodes.
+ nodes[3].node.get_and_clear_pending_msg_events();
+
+ // Now receive a second payment with the same payment hash over a new channel, and claim it.
+ let chan_id_ad = create_announced_chan_between_nodes_with_value(&nodes, 0, 3, 1_000_000, 0).2;
+ let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
+ assert_eq!(route.paths.len(), 1);
+ assert_eq!(route.paths[0].hops.len(), 1);
+ let onion = RecipientOnionFields::secret_only(payment_secret, amt_msat);
+ nodes[0].node.send_payment_with_route(route, payment_hash, onion, PaymentId([2; 32])).unwrap();
+ check_added_monitors(&nodes[0], 1);
+ let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
+ let node_d_msgs = remove_first_msg_event_to_node(&node_d_id, &mut send_events);
+ let path = &[&nodes[3]];
+ let args = PassAlongPathArgs::new(&nodes[0], path, amt_msat, payment_hash, node_d_msgs)
+ .with_payment_secret(payment_secret);
+ let second_id = claimable_id(do_pass_along_path(args));
+ assert_ne!(mpp_id, second_id);
+
+ chanmon_cfgs[3].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
+ nodes[3].node.claim_funds(payment_preimage, Default::default());
+ check_added_monitors(&nodes[3], 1);
+ assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
+
+ // The MPP claim's last `ChannelMonitorUpdate` completing shouldn't generate an event.
+ nodes[3].chain_monitor.complete_sole_pending_chan_update(&chan_id_cd);
+ assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
+
+ nodes[3].chain_monitor.complete_sole_pending_chan_update(&chan_id_ad);
+ assert_eq!(claimed_ids(), [second_id]);
+
+ nodes[3].node.get_and_clear_pending_msg_events();
+}
### lightning/src/ln/channelmanager.rs
@@ -1673,6 +1673,10 @@ pub(crate) enum MonitorUpdateCompletionAction {
/// event can be generated.
PaymentClaimed {
payment_hash: PaymentHash,
+ /// The [`PaymentId`] of the claimed payment. As a payment hash may be reused across
+ /// payments, if this is set an [`events::Event::PaymentClaimed`] is only generated for a
+ /// payment being claimed with this [`PaymentId`].
+ payment_id: Option<PaymentId>,
/// A pending MPP claim which hasn't yet completed.
///
/// Not written to disk.
@@ -1712,6 +1716,7 @@ pub(crate) enum MonitorUpdateCompletionAction {
impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
(0, PaymentClaimed) => {
(0, payment_hash, required),
+ (1, payment_id, option),
(9999999999, pending_mpp_claim, (static_value, None)),
},
// Note that FreeDuplicateClaimImmediately should never be written - we were supposed to free
@@ -10424,6 +10429,7 @@ impl<
} else {
None
};
+ let payment_id = claiming_payment.payment_id;
let payment_info = Some(PaymentClaimDetails { mpp_parts, claiming_payment });
for htlc in sources {
let this_mpp_claim =
@@ -10471,6 +10477,7 @@ impl<
(
Some(MonitorUpdateCompletionAction::PaymentClaimed {
payment_hash,
+ payment_id,
pending_mpp_claim: this_mpp_claim,
}),
raa_blocker,
@@ -11207,6 +11214,57 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
);
}
+ /// Queues an [`Event::PaymentClaimed`] for the given claimed payment, unless an identical event
+ /// is already pending.
+ fn queue_payment_claimed_event<LG: Logger>(
+ &self, logger: &LG, payment_hash: PaymentHash, payment: ClaimingPayment,
+ ) {
+ let ClaimingPayment {
+ amount_msat,
+ payment_purpose: purpose,
+ receiver_node_id,
+ htlcs,
+ sender_intended_value: sender_intended_total_msat,
+ onion_fields,
+ payment_id,
+ durable_preimage_channel,
+ } = payment;
+ let event = events::Event::PaymentClaimed {
+ payment_hash,
+ purpose,
+ amount_msat,
+ receiver_node_id: Some(receiver_node_id),
+ htlcs,
+ sender_intended_total_msat,
+ onion_fields: Some(onion_fields),
+ payment_id,
+ };
+ let action =
+ if let Some((outpoint, counterparty_node_id, channel_id)) = durable_preimage_channel {
+ Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
+ channel_funding_outpoint: Some(outpoint),
+ counterparty_node_id,
+ channel_id,
+ monitor_event_source: None,
+ })
+ } else {
+ None
+ };
+ let event_action = (event, action);
+ let mut pending_events = self.pending_events.lock().unwrap();
+ // If we're replaying a claim on startup we may end up duplicating an event that's already
+ // in our queue, so check before we push another one. The `payment_id` should suffice to
+ // ensure we never spuriously drop a second event for a duplicate payment.
+ if !pending_events.contains(&event_action) {
+ log_trace!(
+ logger,
+ "Queuing PaymentClaimed event with event completion action {:?}",
+ event_action.1
+ );
+ pending_events.push_back(event_action);
+ }
+ }
+
fn handle_monitor_update_completion_actions<
I: IntoIterator<Item = MonitorUpdateCompletionAction>,
>(
@@ -11222,6 +11280,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
match action {
MonitorUpdateCompletionAction::PaymentClaimed {
payment_hash,
+ payment_id,
pending_mpp_claim,
} => {
let (peer_id, chan_id) = pending_mpp_claim
@@ -11275,59 +11334,21 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
});
}
- let payment = self
- .claimable_payments
- .lock()
- .unwrap()
- .pending_claiming_payments
- .remove(&payment_hash);
- if let Some(ClaimingPayment {
- amount_msat,
- payment_purpose: purpose,
- receiver_node_id,
- htlcs,
- sender_intended_value: sender_intended_total_msat,
- onion_fields,
- payment_id,
- durable_preimage_channel,
- }) = payment
- {
- let event = events::Event::PaymentClaimed {
- payment_hash,
- purpose,
- amount_msat,
- receiver_node_id: Some(receiver_node_id),
- htlcs,
- sender_intended_total_msat,
- onion_fields: Some(onion_fields),
- payment_id,
- };
- let action = if let Some((outpoint, counterparty_node_id, channel_id)) =
- durable_preimage_channel
- {
- Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
- channel_funding_outpoint: Some(outpoint),
- counterparty_node_id,
- channel_id,
- monitor_event_source: None,
- })
- } else {
- None
- };
- let event_action = (event, action);
- let mut pending_events = self.pending_events.lock().unwrap();
- // If we're replaying a claim on startup we may end up duplicating an event
- // that's already in our queue, so check before we push another one. The
- // `payment_id` should suffice to ensure we never spuriously drop a second
- // event for a duplicate payment.
- if !pending_events.contains(&event_action) {
- log_trace!(
- logger,
- "Queuing PaymentClaimed event with event completion action {:?}",
- event_action.1
- );
- pending_events.push_back(event_action);
+ let payment = {
+ let mut claimable_payments = self.claimable_payments.lock().unwrap();
+ match claimable_payments.pending_claiming_payments.entry(payment_hash) {
+ // The payment being claimed may be a different one which used the
+ // same payment hash, which must wait for its own claim to complete.
+ hash_map::Entry::Occupied(entry)
+ if payment_id.is_none() || entry.get().payment_id == payment_id =>
+ {
+ Some(entry.remove())
+ },
+ _ => None,
}
+ };
+ if let Some(payment) = payment {
+ self.queue_payment_claimed_event(&logger, payment_hash, payment);
}
},
MonitorUpdateCompletionAction::EmitEventOptionAndFreeOtherChannel {
@@ -21651,34 +21672,40 @@ impl<
// preimages eventually timing out from ChannelMonitors to prevent us from
// doing so forever.
- let claim_found = channel_manager
- .claimable_payments
- .lock()
- .unwrap()
- .begin_claiming_payment(
- payment_hash,
- &channel_manager.node_signer,
- &channel_manager.logger,
- &channel_manager.inbound_payment_id_secret,
- true,
- );
- if claim_found.is_err() {
+ {
+ // If the `ChannelManager` was persisted before this payment was
+ // claimed, it may still consider some or all of the payment's HTLCs
+ // claimable. A claimable payment consisting of other HTLCs is a
+ // different payment using the same payment hash, which we leave as-is.
let mut claimable_payments =
channel_manager.claimable_payments.lock().unwrap();
- match claimable_payments.pending_claiming_payments.entry(payment_hash) {
- hash_map::Entry::Occupied(_) => {
- debug_assert!(
- false,
- "Entry was added in begin_claiming_payment"
- );
- return Err(DecodeError::InvalidValue);
- },
- hash_map::Entry::Vacant(entry) => {
- entry.insert(payment_claim.claiming_payment);
- },
+ if let hash_map::Entry::Occupied(claimable) =
+ claimable_payments.claimable_payments.entry(payment_hash)
+ {
+ let is_claimed_payment = claimable.get().htlcs.iter().any(|htlc| {
+ let prev_hop = &htlc.mpp_part.prev_hop;
+ payment_claim.mpp_parts.iter().any(|part| {
+ part.channel_id == prev_hop.channel_id
+ && part.htlc_id == prev_hop.htlc_id
+ })
+ });
+ if is_claimed_payment {
+ claimable.remove();
+ }
}
}
+ // As the claim is durably in the `ChannelMonitor` it was read from, and is
+ // thus replayed on each startup until the preimage is in the
+ // `ChannelMonitor`s of all the payment's HTLCs, we don't wait on the
+ // `ChannelMonitorUpdate`s below to generate the `PaymentClaimed` event.
+ let claim_id = payment_claim.claiming_payment.payment_id;
+ channel_manager.queue_payment_claimed_event(
+ &channel_manager.logger,
+ payment_hash,
+ payment_claim.claiming_payment,
+ );
+
for part in claim_parts {
let pending_mpp_claim = pending_claim_ptr_opt.as_ref().map(|ptr| {
(
@@ -21707,6 +21734,7 @@ impl<
(
Some(MonitorUpdateCompletionAction::PaymentClaimed {
payment_hash,
+ payment_id: claim_id,
pending_mpp_claim,
}),
pending_claim_ptr,
### lightning/src/ln/reload_tests.rs
@@ -18,13 +18,14 @@ use crate::routing::router::{PaymentParameters, RouteParameters};
use crate::sign::EntropySource;
use crate::chain::transaction::OutPoint;
use crate::events::{ClosureReason, Event, HTLCHandlingFailureType};
-use crate::ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder};
-use crate::ln::outbound_payment::RecipientOnionFields;
+use crate::ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, MPP_TIMEOUT_TICKS};
+use crate::ln::outbound_payment::{RecipientOnionFields, Retry};
use crate::ln::msgs;
use crate::ln::types::ChannelId;
use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, RoutingMessageHandler, ErrorAction, MessageSendEvent};
use crate::util::test_channel_signer::TestChannelSigner;
use crate::util::test_utils;
+use crate::types::string::UntrustedString;
use crate::util::errors::APIError;
use crate::util::ser::{Writeable, ReadableArgs};
use crate::util::config::{HTLCInterceptionFlags, UserConfig};
@@ -662,8 +663,6 @@ fn test_manager_serialize_deserialize_inconsistent_monitor() {
#[cfg(feature = "std")]
fn do_test_data_loss_protect(reconnect_panicing: bool, substantially_old: bool, not_stale: bool) {
- use crate::ln::outbound_payment::Retry;
- use crate::types::string::UntrustedString;
// When we get a data_loss_protect proving we're behind, we immediately panic as the
// chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
// panic message informs the user they should force-close without broadcasting, which is tested
@@ -1034,10 +1033,12 @@ fn do_test_partial_claim_before_restart(persist_both_monitors: bool, double_rest
if persist_both_monitors {
if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
if let Event::PaymentClaimed { amount_msat: 15_000_000, .. } = events[3] { } else { panic!(); }
- check_added_monitors(&nodes[3], 4);
+ // The claim is replayed against each closed channel on each restart.
+ check_added_monitors(&nodes[3], if double_restart { 6 } else { 4 });
} else {
if let Event::PaymentClaimed { amount_msat: 15_000_000, .. } = events[2] { } else { panic!(); }
- check_added_monitors(&nodes[3], 3);
+ // The claim is replayed against the closed channel on each restart.
+ check_added_monitors(&nodes[3], if double_restart { 4 } else { 3 });
}
// Now that we've processed background events, the preimage should have been copied into the
@@ -3212,3 +3213,344 @@ fn test_reestablish_rollback_htlc_theft() {
"attacker reclaimed the incoming HTLC after the victim paid downstream, despite the victim knowing the preimage");
assert!(!signed_next_commitment, "reestablishment signed an unmonitored commitment");
}
+
+/// Sends a keysend payment using the given preimage from `sender` to `recipient` over a direct
+/// channel, returning the [`PaymentId`] `recipient` assigned to it in its `PaymentClaimable`.
+fn send_keysend_with_preimage<'a, 'b, 'c>(
+ sender: &Node<'a, 'b, 'c>, recipient: &Node<'a, 'b, 'c>, preimage: PaymentPreimage,
+ sender_payment_id: PaymentId,
+) -> PaymentId {
+ let amt_msat = 100_000;
+ let recipient_id = recipient.node.get_our_node_id();
+ let pay_params = PaymentParameters::for_keysend(recipient_id, TEST_FINAL_CLTV, false);
+ let route_params = RouteParameters::from_payment_params_and_value(pay_params, amt_msat);
+ let onion = RecipientOnionFields::spontaneous_empty(amt_msat);
+ sender.node.send_spontaneous_payment(
+ Some(preimage), onion, sender_payment_id, route_params, Retry::Attempts(0),
+ ).unwrap();
+ check_added_monitors(sender, 1);
+ let mut events = sender.node.get_and_clear_pending_msg_events();
+ let ev = remove_first_msg_event_to_node(&recipient_id, &mut events);
+ let claimable = pass_along_path(
+ sender, &[recipient], amt_msat, preimage.into(), None, ev, true, Some(preimage),
+ );
+ match claimable {
+ Some(Event::PaymentClaimable { payment_id: Some(payment_id), .. }) => payment_id,
+ _ => panic!("Expected a PaymentClaimable"),
+ }
+}
+
+/// Fetches the pending events of `node`, checking that they're all `PaymentClaimed`s and
+/// returning their [`PaymentId`]s.
+fn get_payment_claimed_ids<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> Vec<PaymentId> {
+ node.node.get_and_clear_pending_events().into_iter().map(|event| match event {
+ Event::PaymentClaimed { payment_id: Some(payment_id), .. } => payment_id,
+ _ => panic!("Unexpected event {:?}", event),
+ }).collect()
+}
+
+fn do_test_claim_replay_of_payments_reusing_payment_hash(closed_chan: bool) {
+ // A payment hash may be paid, and claimed, several times, leaving several claims for it in a
+ // `ChannelMonitor`. When replaying those claims on startup, the `PaymentClaimed` for a claim
+ // may not be generated until some `ChannelMonitorUpdate` completes, either because the
+ // channel is closed or because the channel has `ChannelMonitorUpdate`s in flight. Test that
+ // we replay all the claims in such cases, generating a `PaymentClaimed` for each.
+ let chanmon_cfgs = create_chanmon_cfgs(2);
+ let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+ let persister;
+ let new_chain_monitor;
+ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+ let nodes_1_deserialized;
+ let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+ let node_a_id = nodes[0].node.get_our_node_id();
+ let chan_id =
+ create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000).2;
+
+ let preimage = PaymentPreimage([42; 32]);
+ let payment_hash: PaymentHash = preimage.into();
+ let first_id = send_keysend_with_preimage(&nodes[0], &nodes[1], preimage, PaymentId([1; 32]));
+ claim_payment(&nodes[0], &[&nodes[1]], preimage);
+ let second_id = send_keysend_with_preimage(&nodes[0], &nodes[1], preimage, PaymentId([2; 32]));
+ claim_payment(&nodes[0], &[&nodes[1]], preimage);
+ assert_ne!(first_id, second_id);
+ assert_eq!(get_monitor!(nodes[1], chan_id).get_stored_preimages()[&payment_hash].1.len(), 2);
+
+ let mut mon_ser = get_monitor!(nodes[1], chan_id).encode();
+ if closed_chan {
+ let peer_msg = "error".to_owned();
+ let err = msgs::ErrorMessage { channel_id: chan_id, data: peer_msg.clone() };
+ nodes[1].node.handle_error(node_a_id, &err);
+ check_added_monitors(&nodes[1], 1);
+ check_closed_broadcast(&nodes[1], 1, false);
+ let reason = ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg) };
+ check_closed_event(&nodes[1], 1, reason, &[node_a_id], 1_000_000);
+ mon_ser = get_monitor!(nodes[1], chan_id).encode();
+ } else {
+ // Leave a `ChannelMonitorUpdate` in flight which the persisted `ChannelMonitor` hasn't
+ // seen.
+ chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
+ let (route, hash, _, secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
+ let onion = RecipientOnionFields::secret_only(secret, 50_000);
+ nodes[1].node.send_payment_with_route(route, hash, onion, PaymentId(hash.0)).unwrap();
+ check_added_monitors(&nodes[1], 1);
+ assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
+ }
+
+ let node_b_ser = nodes[1].node.encode();
+ reload_node!(nodes[1], &node_b_ser, &[&mon_ser], persister, new_chain_monitor, nodes_1_deserialized);
+
+ let mut claimed_ids = get_payment_claimed_ids(&nodes[1]);
+ claimed_ids.sort_unstable_by_key(|id| id.0);
+ let mut expected_ids = [first_id, second_id];
+ expected_ids.sort_unstable_by_key(|id| id.0);
+ assert_eq!(claimed_ids, expected_ids);
+ if closed_chan {
+ // One preimage-containing `ChannelMonitorUpdate` is generated per replayed claim.
+ check_added_monitors(&nodes[1], 2);
+ } else {
+ // The in-flight `ChannelMonitorUpdate` is replayed.
+ check_added_monitors(&nodes[1], 1);
+ }
+}
+
+#[test]
+fn test_claim_replay_of_payments_reusing_payment_hash() {
+ do_test_claim_replay_of_payments_reusing_payment_hash(true);
+ do_test_claim_replay_of_payments_reusing_payment_hash(false);
+}
+
+#[test]
+fn test_claim_replay_with_claimable_payment_reusing_payment_hash() {
+ // Test that replaying the claim of a payment on startup leaves a second, still-claimable,
+ // payment with the same payment hash untouched, allowing it to be claimed later.
+ let chanmon_cfgs = create_chanmon_cfgs(2);
+ let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+ let persister;
+ let new_chain_monitor;
+ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+ let nodes_1_deserialized;
+ let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+ let node_b_id = nodes[1].node.get_our_node_id();
+ let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
+
+ let preimage = PaymentPreimage([42; 32]);
+ let payment_hash: PaymentHash = preimage.into();
+ let first_id = send_keysend_with_preimage(&nodes[0], &nodes[1], preimage, PaymentId([1; 32]));
+ claim_payment(&nodes[0], &[&nodes[1]], preimage);
+ let second_id = send_keysend_with_preimage(&nodes[0], &nodes[1], preimage, PaymentId([2; 32]));
+ assert_ne!(first_id, second_id);
+ assert_eq!(get_monitor!(nodes[1], chan_id).get_stored_preimages()[&payment_hash].1.len(), 1);
+
+ nodes[0].node.peer_disconnected(node_b_id);
+ let node_b_ser = nodes[1].node.encode();
+ let mon_ser = get_monitor!(nodes[1], chan_id).encode();
+ reload_node!(nodes[1], &node_b_ser, &[&mon_ser], persister, new_chain_monitor, nodes_1_deserialized);
+
+ // Only the first payment was claimed, so only it gets a replayed `PaymentClaimed`.
+ assert_eq!(get_payment_claimed_ids(&nodes[1]), [first_id]);
+ check_added_monitors(&nodes[1], 0);
+
+ reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
+ claim_payment(&nodes[0], &[&nodes[1]], preimage);
+}
+
+#[test]
+fn test_claim_replay_with_stale_claimable_payment_reusing_payment_hash() {
+ // Test replaying two claims of payments with the same payment hash against a closed channel
+ // when the `ChannelManager` was persisted prior to the second payment being claimed, and thus
+ // still considers it claimable. Both claims should be replayed with a `PaymentClaimed` each.
+ let chanmon_cfgs = create_chanmon_cfgs(2);
+ let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+ let persister;
+ let new_chain_monitor;
+ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+ let nodes_1_deserialized;
+ let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+ let node_a_id = nodes[0].node.get_our_node_id();
+ let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
+
+ let preimage = PaymentPreimage([42; 32]);
+ let payment_hash: PaymentHash = preimage.into();
+ let first_id = send_keysend_with_preimage(&nodes[0], &nodes[1], preimage, PaymentId([1; 32]));
+ claim_payment(&nodes[0], &[&nodes[1]], preimage);
+ let second_id = send_keysend_with_preimage(&nodes[0], &nodes[1], preimage, PaymentId([2; 32]));
+ assert_ne!(first_id, second_id);
+
+ let peer_msg = "error".to_owned();
+ let err = msgs::ErrorMessage { channel_id: chan_id, data: peer_msg.clone() };
+ nodes[1].node.handle_error(node_a_id, &err);
+ check_added_monitors(&nodes[1], 1);
+ check_closed_broadcast(&nodes[1], 1, false);
+ let reason = ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg) };
+ check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100_000);
+
+ let node_b_ser = nodes[1].node.encode();
+
+ nodes[1].node.claim_funds(preimage, Default::default());
+ check_added_monitors(&nodes[1], 1);
+ assert_eq!(get_payment_claimed_ids(&nodes[1]), [second_id]);
+ assert_eq!(get_monitor!(nodes[1], chan_id).get_stored_preimages()[&payment_hash].1.len(), 2);
+
+ let mon_ser = get_monitor!(nodes[1], chan_id).encode();
+ reload_node!(nodes[1], &node_b_ser, &[&mon_ser], persister, new_chain_monitor, nodes_1_deserialized);
+
+ let mut claimed_ids = get_payment_claimed_ids(&nodes[1]);
+ claimed_ids.sort_unstable_by_key(|id| id.0);
+ let mut expected_ids = [first_id, second_id];
+ expected_ids.sort_unstable_by_key(|id| id.0);
+ assert_eq!(claimed_ids, expected_ids);
+ check_added_monitors(&nodes[1], 2);
+}
+
+#[test]
+fn test_claim_replay_pending_with_claimable_payment_reusing_payment_hash() {
+ // Test that a second, still-claimable, payment can be claimed while the replay of an earlier
+ // claim of a payment with the same payment hash is still waiting on a `ChannelMonitorUpdate`.
+ let chanmon_cfgs = create_chanmon_cfgs(3);
+ let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
+ let persister;
+ let new_chain_monitor;
+ let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
+ let nodes_1_deserialized;
+ let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
+ let node_a_id = nodes[0].node.get_our_node_id();
+ let node_b_id = nodes[1].node.get_our_node_id();
+ let chan_id_a = create_announced_chan_between_nodes(&nodes, 0, 1).2;
+ let chan_id_c = create_announced_chan_between_nodes(&nodes, 2, 1).2;
+
+ let preimage = PaymentPreimage([42; 32]);
+ let first_id = send_keysend_with_preimage(&nodes[0], &nodes[1], preimage, PaymentId([1; 32]));
+ claim_payment(&nodes[0], &[&nodes[1]], preimage);
+
+ let peer_msg = "error".to_owned();
+ let err = msgs::ErrorMessage { channel_id: chan_id_a, data: peer_msg.clone() };
+ nodes[1].node.handle_error(node_a_id, &err);
+ check_added_monitors(&nodes[1], 1);
+ check_closed_broadcast(&nodes[1], 1, false);
+ let reason = ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg) };
+ check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100_000);
+
+ let second_id = send_keysend_with_preimage(&nodes[2], &nodes[1], preimage, PaymentId([2; 32]));
+ assert_ne!(first_id, second_id);
+
+ nodes[2].node.peer_disconnected(node_b_id);
+ let node_b_ser = nodes[1].node.encode();
+ let mon_a_ser = get_monitor!(nodes[1], chan_id_a).encode();
+ let mon_c_ser = get_monitor!(nodes[1], chan_id_c).encode();
+ reload_node!(nodes[1], &node_b_ser, &[&mon_a_ser, &mon_c_ser], persister, new_chain_monitor, nodes_1_deserialized);
+
+ // Leave the `ChannelMonitorUpdate` replaying the first claim against the closed channel
+ // pending.
+ persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
+ assert_eq!(get_payment_claimed_ids(&nodes[1]), [first_id]);
+ check_added_monitors(&nodes[1], 1);
+
+ persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
+ nodes[1].node.claim_funds(preimage, Default::default());
+ check_added_monitors(&nodes[1], 1);
+ assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
+
+ // The replayed claim completing must not generate a `PaymentClaimed` for the second payment,
+ // as its preimage isn't durably in its channel's `ChannelMonitor` yet.
+ nodes[1].chain_monitor.complete_sole_pending_chan_update(&chan_id_a);
+ assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
+
+ nodes[1].chain_monitor.complete_sole_pending_chan_update(&chan_id_c);
+ assert_eq!(get_payment_claimed_ids(&nodes[1]), [second_id]);
+}
+
+#[test]
+fn test_claim_replay_with_stale_partially_claimable_mpp() {
+ // Test replaying the claim of an MPP payment when the `ChannelManager` was persisted after
+ // only some of the payment's HTLCs arrived. The stale partial payment must not remain
+ // claimable once the claim is replayed, as the sender could otherwise complete it by sending
+ // only the missing part again, getting a second `PaymentClaimable` for the full amount.
+ let chanmon_cfgs = create_chanmon_cfgs(4);
+ let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
+ let persister;
+ let new_chain_monitor;
+ let mut config = test_default_channel_config();
+ // Force the payment to be split across both paths.
+ config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage = 10;
+ let configs: [Option<UserConfig>; 4] = core::array::from_fn(|_| Some(config.clone()));
+ let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &configs);
+ let nodes_3_deserialized;
+ let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
+ let node_b_id = nodes[1].node.get_our_node_id();
+ let node_c_id = nodes[2].node.get_our_node_id();
+ let node_d_id = nodes[3].node.get_our_node_id();
+
+ create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
+ create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
+ let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0).2;
+ let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0).2;
+
+ let (mut route, payment_hash, payment_preimage, payment_secret) =
+ get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
+ assert_eq!(route.paths.len(), 2);
+ route.paths.sort_by(|path_a, _| {
+ // Sort the path so that the path through nodes[1] comes first
+ if path_a.hops[0].pubkey == node_b_id {
+ core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
+ });
+
+ nodes[0].node.send_payment_with_route(route, payment_hash,
+ RecipientOnionFields::secret_only(payment_secret, 15_000_000), PaymentId(payment_hash.0)).unwrap();
+ check_added_monitors(&nodes[0], 2);
+
+ let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
+ assert_eq!(send_events.len(), 2);
+ let node_b_msgs = remove_first_msg_event_to_node(&node_b_id, &mut send_events);
+ let node_c_msgs = remove_first_msg_event_to_node(&node_c_id, &mut send_events);
+ do_pass_along_path(PassAlongPathArgs::new(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, node_b_msgs)
+ .with_payment_secret(payment_secret)
+ .without_claimable_event());
+
+ // Persist the `ChannelManager` with only the first HTLC of the payment.
+ let stale_manager = nodes[3].node.encode();
+
+ let claimable = do_pass_along_path(PassAlongPathArgs::new(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, node_c_msgs)
+ .with_payment_secret(payment_secret));
+ let payment_id = match claimable {
+ Some(Event::PaymentClaimable { payment_id: Some(payment_id), .. }) => payment_id,
+ _ => panic!("Expected a PaymentClaimable"),
+ };
+
+ nodes[3].node.claim_funds(payment_preimage, Default::default());
+ check_added_monitors(&nodes[3], 2);
+ assert_eq!(get_payment_claimed_ids(&nodes[3]), [payment_id]);
+ nodes[3].node.get_and_clear_pending_msg_events();
+
+ let mon_bd_ser = get_monitor!(nodes[3], chan_id_bd).encode();
+ let mon_cd_ser = get_monitor!(nodes[3], chan_id_cd).encode();
+ nodes[1].node.peer_disconnected(node_d_id);
+ nodes[2].node.peer_disconnected(node_d_id);
+ reload_node!(nodes[3], &stale_manager, &[&mon_bd_ser, &mon_cd_ser], persister, new_chain_monitor, nodes_3_deserialized);
+
+ // Both channels are closed as the `ChannelManager` is stale, and the claim is replayed.
+ let events = nodes[3].node.get_and_clear_pending_events();
+ assert_eq!(events.len(), 3, "{:?}", events);
+ let mut claimed = false;
+ for event in events {
+ match event {
+ Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } => {},
+ Event::PaymentClaimed { payment_id: claimed_id, amount_msat: 15_000_000, .. } => {
+ assert_eq!(claimed_id, Some(payment_id));
+ claimed = true;
+ },
+ _ => panic!("Unexpected event {:?}", event),
+ }
+ }
+ assert!(claimed);
+ check_added_monitors(&nodes[3], 4);
+ nodes[3].node.get_and_clear_pending_msg_events();
+ nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
+
+ // The first HTLC is no longer claimable, so there's nothing to time out waiting on further
+ // HTLCs.
+ for _ in 0..MPP_TIMEOUT_TICKS {
+ nodes[3].node.timer_tick_occurred();
+ }
+ nodes[3].node.process_pending_htlc_forwards();
+ assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
+}Why 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.