Skip to content

Commit 4d936b1

Browse files
committed
Block the mon update removing a preimage until upstream mon writes
When we forward a payment and receive an `update_fulfill_htlc` message from the downstream channel, we immediately claim the HTLC on the upstream channel, before even doing a `commitment_signed` dance on the downstream channel. This implies that our `ChannelMonitorUpdate`s "go out" in the right order - first we ensure we'll get our money by writing the preimage down, then we write the update that resolves giving money on the downstream node. This is safe as long as `ChannelMonitorUpdate`s complete in the order in which they are generated, but of course looking forward we want to support asynchronous updates, which may complete in any order. Thus, here, we enforce the correct ordering by blocking the downstream `ChannelMonitorUpdate` until the upstream one completes. Like the `PaymentSent` event handling we do so only for the `revoke_and_ack` `ChannelMonitorUpdate`, ensuring the preimage-containing upstream update has a full RTT to complete before we actually manage to slow anything down.
1 parent ef0e1a6 commit 4d936b1

File tree

3 files changed

+217
-40
lines changed

3 files changed

+217
-40
lines changed

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 133 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3053,18 +3053,27 @@ fn test_blocked_chan_preimage_release() {
30533053
check_added_monitors(&nodes[1], 1); // We generate only a preimage monitor update
30543054
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
30553055

3056-
// Finish the CS dance between nodes[0] and nodes[1].
3057-
commitment_signed_dance!(nodes[1], nodes[0], as_htlc_fulfill_updates.commitment_signed, false);
3056+
// Finish the CS dance between nodes[0] and nodes[1]. Note that until the final RAA CS is held
3057+
// until the full set of `ChannelMonitorUpdate`s on the nodes[1] <-> nodes[2] channel are
3058+
// complete, while the preimage that we care about ensuring is on disk did make it there above,
3059+
// the holding logic doesn't care about the type of update, it just cares that there is one.
3060+
nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_htlc_fulfill_updates.commitment_signed);
3061+
check_added_monitors(&nodes[1], 1);
3062+
let (a, raa) = do_main_commitment_signed_dance(&nodes[1], &nodes[0], false);
3063+
assert!(a.is_none());
3064+
3065+
nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
30583066
check_added_monitors(&nodes[1], 0);
3067+
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
30593068

30603069
let events = nodes[1].node.get_and_clear_pending_events();
30613070
assert_eq!(events.len(), 3);
30623071
if let Event::PaymentSent { .. } = events[0] {} else { panic!(); }
30633072
if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
30643073
if let Event::PaymentForwarded { .. } = events[1] {} else { panic!(); }
30653074

3066-
// The event processing should release the last RAA update.
3067-
check_added_monitors(&nodes[1], 1);
3075+
// The event processing should release the last RAA updates on both channels.
3076+
check_added_monitors(&nodes[1], 2);
30683077

30693078
// When we fetch the next update the message getter will generate the next update for nodes[2],
30703079
// generating a further monitor update.
@@ -3075,3 +3084,123 @@ fn test_blocked_chan_preimage_release() {
30753084
commitment_signed_dance!(nodes[2], nodes[1], bs_htlc_fulfill_updates.commitment_signed, false);
30763085
expect_payment_sent(&nodes[2], payment_preimage_2, None, true, true);
30773086
}
3087+
3088+
fn do_test_inverted_mon_completion_order(complete_bc_commitment_dance: bool) {
3089+
// When we forward a payment and receive an `update_fulfill_htlc` message from the downstream
3090+
// channel, we immediately claim the HTLC on the upstream channel, before even doing a
3091+
// `commitment_signed` dance on the downstream channel. This implies that our
3092+
// `ChannelMonitorUpdate`s "go out" in the right order - first we ensure we'll get our money,
3093+
// then we write the update that resolves giving money on the downstream node. This is safe as
3094+
// long as `ChannelMonitorUpdate`s complete in the order in which they are generated, but of
3095+
// course this may not be the case. For asynchronous update writes, we have to ensure monitor
3096+
// updates can block each other, preventing the inversion all together.
3097+
let chanmon_cfgs = create_chanmon_cfgs(3);
3098+
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3099+
3100+
let persister;
3101+
let new_chain_monitor;
3102+
let nodes_1_deserialized;
3103+
3104+
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3105+
let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3106+
3107+
let chan_id_ab = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3108+
let chan_id_bc = create_announced_chan_between_nodes(&nodes, 1, 2).2;
3109+
3110+
// Route a payment from A, through B, to C, then claim it on C. Once we pass B the
3111+
// `update_fulfill_htlc` we have a monitor update for both of B's channels. We complete the one
3112+
// on the B<->C channel but leave the A<->B monitor update pending, then reload B.
3113+
let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100_000);
3114+
3115+
let mon_ab = get_monitor!(nodes[1], chan_id_ab).encode();
3116+
3117+
nodes[2].node.claim_funds(payment_preimage);
3118+
check_added_monitors(&nodes[2], 1);
3119+
expect_payment_claimed!(nodes[2], payment_hash, 100_000);
3120+
3121+
chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
3122+
let cs_updates = get_htlc_update_msgs(&nodes[2], &nodes[1].node.get_our_node_id());
3123+
nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
3124+
3125+
// B generates a new monitor update for the A <-> B channel, but doesn't send the new messages
3126+
// for it since the monitor update is marked in-progress.
3127+
check_added_monitors(&nodes[1], 1);
3128+
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3129+
3130+
// Now step the Commitment Signed Dance between B and C forward a bit (or fully), ensuring we
3131+
// won't get the preimage when the nodes reconnect, at which point we have to ensure we get it
3132+
// from the ChannelMonitor.
3133+
nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &cs_updates.commitment_signed);
3134+
check_added_monitors(&nodes[1], 1);
3135+
if complete_bc_commitment_dance {
3136+
let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3137+
nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3138+
check_added_monitors(&nodes[2], 1);
3139+
nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3140+
check_added_monitors(&nodes[2], 1);
3141+
let cs_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3142+
3143+
// At this point node B still hasn't persisted the `ChannelMonitorUpdate` with the
3144+
// preimage in the A <-> B channel, which will prevent it from persisting the
3145+
// `ChannelMonitorUpdate` here to avoid "losing" the preimage.
3146+
nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &cs_raa);
3147+
check_added_monitors(&nodes[1], 0);
3148+
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3149+
}
3150+
3151+
// Now reload node B
3152+
let manager_b = nodes[1].node.encode();
3153+
3154+
let mon_bc = get_monitor!(nodes[1], chan_id_bc).encode();
3155+
reload_node!(nodes[1], &manager_b, &[&mon_ab, &mon_bc], persister, new_chain_monitor, nodes_1_deserialized);
3156+
3157+
nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3158+
nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3159+
3160+
// If we used the latest ChannelManager to reload from, we should have both channels still
3161+
// live. The B <-> C channel's final RAA ChannelMonitorUpdate must still be blocked as
3162+
// before - the ChannelMonitorUpdate for the A <-> B channel hasn't completed.
3163+
// When we call `timer_tick_occurred` we will get that monitor update back, which we'll
3164+
// complete after reconnecting to our peers.
3165+
persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
3166+
nodes[1].node.timer_tick_occurred();
3167+
check_added_monitors(&nodes[1], 1);
3168+
assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3169+
3170+
// Now reconnect B to both A and C. If the B <-> C commitment signed dance wasn't run to
3171+
// the end go ahead and do that, though the -2 in `reconnect_nodes` indicates that we
3172+
// expect to *not* receive the final RAA ChannelMonitorUpdate.
3173+
if complete_bc_commitment_dance {
3174+
reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3175+
} else {
3176+
reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, -2), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3177+
}
3178+
3179+
reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3180+
3181+
// (Finally) complete the A <-> B ChannelMonitorUpdate, ensuring the preimage is durably on
3182+
// disk in the proper ChannelMonitor, unblocking the B <-> C ChannelMonitor updating
3183+
// process.
3184+
let (outpoint, _, ab_update_id) = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap().get(&chan_id_ab).unwrap().clone();
3185+
nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(outpoint, ab_update_id).unwrap();
3186+
3187+
// When we fetch B's HTLC update messages here (now that the ChannelMonitorUpdate has
3188+
// completed), it will also release the final RAA ChannelMonitorUpdate on the B <-> C
3189+
// channel.
3190+
let bs_updates = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id());
3191+
check_added_monitors(&nodes[1], 1);
3192+
3193+
nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
3194+
do_commitment_signed_dance(&nodes[0], &nodes[1], &bs_updates.commitment_signed, false, false);
3195+
3196+
expect_payment_forwarded!(nodes[1], &nodes[0], &nodes[2], Some(1_000), false, false);
3197+
3198+
// Finally, check that the payment was, ultimately, seen as sent by node A.
3199+
expect_payment_sent(&nodes[0], payment_preimage, None, true, true);
3200+
}
3201+
3202+
#[test]
3203+
fn test_inverted_mon_completion_order() {
3204+
do_test_inverted_mon_completion_order(true);
3205+
do_test_inverted_mon_completion_order(false);
3206+
}

lightning/src/ln/channelmanager.rs

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -603,7 +603,6 @@ pub(crate) enum RAAMonitorUpdateBlockingAction {
603603
}
604604

605605
impl RAAMonitorUpdateBlockingAction {
606-
#[allow(unused)]
607606
fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
608607
Self::ForwardedPaymentInboundClaim {
609608
channel_id: prev_hop.outpoint.to_channel_id(),
@@ -4813,10 +4812,13 @@ where
48134812
self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
48144813
}
48154814

4816-
fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, next_channel_outpoint: OutPoint, during_init: bool) {
4815+
fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint, during_init: bool) {
48174816
match source {
48184817
HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
48194818
debug_assert!(!during_init);
4819+
if let Some(pubkey) = next_channel_counterparty_node_id {
4820+
debug_assert_eq!(pubkey, path.hops[0].pubkey);
4821+
}
48204822
let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
48214823
channel_funding_outpoint: next_channel_outpoint,
48224824
counterparty_node_id: path.hops[0].pubkey,
@@ -4827,6 +4829,7 @@ where
48274829
},
48284830
HTLCSource::PreviousHopData(hop_data) => {
48294831
let prev_outpoint = hop_data.outpoint;
4832+
let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
48304833
let res = self.claim_funds_from_hop(hop_data, payment_preimage,
48314834
|htlc_claim_value_msat| {
48324835
if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
@@ -4842,7 +4845,17 @@ where
48424845
next_channel_id: Some(next_channel_outpoint.to_channel_id()),
48434846
outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
48444847
},
4845-
downstream_counterparty_and_funding_outpoint: None,
4848+
downstream_counterparty_and_funding_outpoint:
4849+
if let Some(node_id) = next_channel_counterparty_node_id {
4850+
Some((node_id, next_channel_outpoint, completed_blocker))
4851+
} else {
4852+
// We can only get `None` here if we are processing a
4853+
// `ChannelMonitor`-originated event, in which case we
4854+
// don't care about ensuring we wake the downstream
4855+
// channel's monitor updating - the channel is already
4856+
// closed.
4857+
None
4858+
},
48464859
})
48474860
} else { None }
48484861
}, during_init);
@@ -5596,13 +5609,27 @@ where
55965609
match peer_state.channel_by_id.entry(msg.channel_id) {
55975610
hash_map::Entry::Occupied(mut chan) => {
55985611
let res = try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), chan);
5612+
if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
5613+
peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
5614+
.or_insert_with(Vec::new)
5615+
.push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
5616+
}
5617+
// Note that we do not need to push an `actions_blocking_raa_monitor_updates`
5618+
// entry here, even though we *do* need to block the next RAA coming in from
5619+
// generating a monitor update which we let fly. We do this instead in the
5620+
// `claim_funds_internal` by attaching a `ReleaseRAAChannelMonitorUpdate`
5621+
// action to the event generated when we "claim" the sent payment. This is
5622+
// guaranteed to all complete before we process the RAA even though there is no
5623+
// lock held through that point as we aren't allowed to see another P2P message
5624+
// from the counterparty until we return, but `claim_funds_internal` runs
5625+
// first.
55995626
funding_txo = chan.get().context.get_funding_txo().expect("We won't accept a fulfill until funded");
56005627
res
56015628
},
56025629
hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
56035630
}
56045631
};
5605-
self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, funding_txo, false);
5632+
self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, Some(*counterparty_node_id), funding_txo, false);
56065633
Ok(())
56075634
}
56085635

@@ -5783,6 +5810,23 @@ where
57835810
})
57845811
}
57855812

5813+
#[cfg(any(test, feature = "_test_utils"))]
5814+
pub(crate) fn test_raa_monitor_updates_held(&self, counterparty_node_id: PublicKey,
5815+
channel_id: [u8; 32])
5816+
-> bool {
5817+
let per_peer_state = self.per_peer_state.read().unwrap();
5818+
if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
5819+
let mut peer_state_lck = peer_state_mtx.lock().unwrap();
5820+
let peer_state = &mut *peer_state_lck;
5821+
5822+
if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
5823+
return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
5824+
chan.context.get_funding_txo().unwrap(), counterparty_node_id);
5825+
}
5826+
}
5827+
false
5828+
}
5829+
57865830
fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
57875831
let (htlcs_to_fail, res) = {
57885832
let per_peer_state = self.per_peer_state.read().unwrap();
@@ -5795,12 +5839,10 @@ where
57955839
match peer_state.channel_by_id.entry(msg.channel_id) {
57965840
hash_map::Entry::Occupied(mut chan) => {
57975841
let funding_txo = chan.get().context.get_funding_txo();
5798-
let mon_update_blocked = self.pending_events.lock().unwrap().iter().any(|(_, action)| {
5799-
action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5800-
channel_funding_outpoint: funding_txo.expect("We won't accept an RAA until funded"),
5801-
counterparty_node_id: *counterparty_node_id,
5802-
})
5803-
});
5842+
let mon_update_blocked = self.raa_monitor_updates_held(
5843+
&peer_state.actions_blocking_raa_monitor_updates,
5844+
chan.get().context.get_funding_txo().expect("We won't accept an RAA until funded"),
5845+
*counterparty_node_id);
58045846
let (htlcs_to_fail, monitor_update_opt) = try_chan_entry!(self,
58055847
chan.get_mut().revoke_and_ack(&msg, &self.logger, mon_update_blocked), chan);
58065848
let res = if let Some(monitor_update) = monitor_update_opt {
@@ -5979,7 +6021,7 @@ where
59796021
MonitorEvent::HTLCEvent(htlc_update) => {
59806022
if let Some(preimage) = htlc_update.payment_preimage {
59816023
log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
5982-
self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, funding_outpoint, false);
6024+
self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, counterparty_node_id, funding_outpoint, false);
59836025
} else {
59846026
log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
59856027
let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
@@ -8700,6 +8742,7 @@ where
87008742
if let Some(payment_preimage) = preimage_opt {
87018743
Some((htlc_source, payment_preimage, htlc.amount_msat,
87028744
counterparty_opt.is_none(), // i.e. the downstream chan is closed
8745+
counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
87038746
monitor.get_funding_txo().0))
87048747
} else { None }
87058748
} else {
@@ -8964,9 +9007,9 @@ where
89649007
channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
89659008
}
89669009

8967-
for (source, preimage, downstream_value, downstream_closed, downstream_funding) in pending_claims_to_replay {
9010+
for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
89689011
channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
8969-
downstream_closed, downstream_funding, true);
9012+
downstream_closed, downstream_node_id, downstream_funding, true);
89709013
}
89719014

89729015
//TODO: Broadcast channel update for closed channels, but only after we've made a

0 commit comments

Comments
 (0)