Skip to content

Commit 87406fe

Browse files
committed
f various dedup fixes, enum helper, etc
1 parent df5e51e commit 87406fe

File tree

4 files changed

+71
-49
lines changed

4 files changed

+71
-49
lines changed

lightning/src/ln/channelmanager.rs

+44-47
Original file line numberDiff line numberDiff line change
@@ -2073,10 +2073,15 @@ macro_rules! handle_new_monitor_update {
20732073
($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan_entry: expr, INITIAL_MONITOR) => {
20742074
if let ChannelPhase::Funded(chan) = $chan_entry.get_mut() {
20752075
handle_new_monitor_update!($self, $update_res, $peer_state_lock, $peer_state, $per_peer_state_lock, chan, MANUALLY_REMOVING_INITIAL_MONITOR, {
2076-
if let ChannelPhase::Funded(chan) = $chan_entry.remove() { chan } else { unreachable!() }
2076+
unwrap_enum_value!($chan_entry.remove(), ChannelPhase::Funded(chan) => chan)
20772077
})
20782078
} else {
2079-
unreachable!();
2079+
// We're not supposed to handle monitor updates for unfunded channels (they have no monitors to
2080+
// update).
2081+
debug_assert!(true);
2082+
Err(MsgHandleErrInternal::send_err_msg_no_close(
2083+
"Cannot update monitor for unfunded channels as they don't have monitors yet".into(),
2084+
*$chan_entry.key()))
20802085
}
20812086
};
20822087
($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, MANUALLY_REMOVING, $remove: expr) => { {
@@ -2529,47 +2534,38 @@ where
25292534

25302535
match peer_state.channel_by_id.entry(channel_id.clone()) {
25312536
hash_map::Entry::Occupied(mut chan_phase_entry) => {
2532-
match chan_phase_entry.get_mut() {
2533-
ChannelPhase::Funded(chan) => {
2534-
let funding_txo_opt = chan.context.get_funding_txo();
2535-
let their_features = &peer_state.latest_features;
2536-
let (shutdown_msg, mut monitor_update_opt, htlcs) =
2537-
chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2538-
failed_htlcs = htlcs;
2539-
2540-
// We can send the `shutdown` message before updating the `ChannelMonitor`
2541-
// here as we don't need the monitor update to complete until we send a
2542-
// `shutdown_signed`, which we'll delay if we're pending a monitor update.
2543-
peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2544-
node_id: *counterparty_node_id,
2545-
msg: shutdown_msg,
2546-
});
2537+
if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2538+
let funding_txo_opt = chan.context.get_funding_txo();
2539+
let their_features = &peer_state.latest_features;
2540+
let (shutdown_msg, mut monitor_update_opt, htlcs) =
2541+
chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2542+
failed_htlcs = htlcs;
2543+
2544+
// We can send the `shutdown` message before updating the `ChannelMonitor`
2545+
// here as we don't need the monitor update to complete until we send a
2546+
// `shutdown_signed`, which we'll delay if we're pending a monitor update.
2547+
peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2548+
node_id: *counterparty_node_id,
2549+
msg: shutdown_msg,
2550+
});
25472551

2548-
// Update the monitor with the shutdown script if necessary.
2549-
if let Some(monitor_update) = monitor_update_opt.take() {
2550-
break handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2551-
peer_state_lock, peer_state, per_peer_state, chan_phase_entry).map(|_| ());
2552-
}
2552+
// Update the monitor with the shutdown script if necessary.
2553+
if let Some(monitor_update) = monitor_update_opt.take() {
2554+
break handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2555+
peer_state_lock, peer_state, per_peer_state, chan_phase_entry).map(|_| ());
2556+
}
25532557

2554-
if chan.is_shutdown() {
2555-
if let ChannelPhase::Funded(chan) = remove_channel_phase!(self, chan_phase_entry) {
2556-
if let Ok(channel_update) = self.get_channel_update_for_broadcast(&chan) {
2557-
peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2558-
msg: channel_update
2559-
});
2560-
}
2561-
self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
2558+
if chan.is_shutdown() {
2559+
if let ChannelPhase::Funded(chan) = remove_channel_phase!(self, chan_phase_entry) {
2560+
if let Ok(channel_update) = self.get_channel_update_for_broadcast(&chan) {
2561+
peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2562+
msg: channel_update
2563+
});
25622564
}
2565+
self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
25632566
}
2564-
break Ok(());
2565-
},
2566-
_ => {
2567-
// If we reach this point, it means that the channel_id either refers to an unfunded channel or
2568-
// it does not exist for this peer. Either way, we can attempt to force-close it.
2569-
//
2570-
// An appropriate error will be returned for non-existence of the channel if that's the case.
2571-
return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2572-
},
2567+
}
2568+
break Ok(());
25732569
}
25742570
},
25752571
hash_map::Entry::Vacant(_) => (),
@@ -2580,8 +2576,6 @@ where
25802576
//
25812577
// An appropriate error will be returned for non-existence of the channel if that's the case.
25822578
return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2583-
// TODO(dunxen): This is still not ideal as we're doing some extra lookups.
2584-
// Fix this with https://github.com/lightningdevkit/rust-lightning/issues/2422
25852579
};
25862580

25872581
for htlc_source in failed_htlcs.drain(..) {
@@ -3043,10 +3037,13 @@ where
30433037
}
30443038
let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
30453039
let peer_state = &mut *peer_state_lock;
3046-
let opt_chan_phase = peer_state.channel_by_id.get_mut(&forwarding_id);
3047-
let chan = match opt_chan_phase.iter().find_map(
3040+
let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
30483041
|chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3049-
) {
3042+
).flatten() {
3043+
// let opt_chan_phase = peer_state.channel_by_id.get_mut(&forwarding_id);
3044+
// let chan = match opt_chan_phase.iter().find_map(
3045+
// |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3046+
// ) {
30503047
None => {
30513048
// Channel was removed. The short_to_chan_info and channel_by_id maps
30523049
// have no consistency guarantees.
@@ -3857,7 +3854,7 @@ where
38573854
next_hop_channel_id, next_node_id)
38583855
}),
38593856
None => return Err(APIError::ChannelUnavailable {
3860-
err: format!("Funded channel with id {} not found for the passed counterparty node_id {}.",
3857+
err: format!("Channel with id {} not found for the passed counterparty node_id {}.",
38613858
next_hop_channel_id, next_node_id)
38623859
})
38633860
}
@@ -4417,10 +4414,10 @@ where
44174414
let mut peer_state_lock = peer_state_mutex.lock().unwrap();
44184415
let peer_state = &mut *peer_state_lock;
44194416
match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4420-
hash_map::Entry::Occupied(mut chan_phase_phase) => {
4417+
hash_map::Entry::Occupied(mut chan_phase) => {
44214418
updated_chan = true;
44224419
handle_new_monitor_update!(self, funding_txo, update.clone(),
4423-
peer_state_lock, peer_state, per_peer_state, chan_phase_phase).map(|_| ())
4420+
peer_state_lock, peer_state, per_peer_state, chan_phase).map(|_| ())
44244421
},
44254422
hash_map::Entry::Vacant(_) => Ok(()),
44264423
}

lightning/src/ln/payment_tests.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1705,7 +1705,7 @@ fn do_test_intercepted_payment(test: InterceptTest) {
17051705
// Check for unknown channel id error.
17061706
let unknown_chan_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &ChannelId::from_bytes([42; 32]), nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
17071707
assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1708-
err: format!("Funded channel with id {} not found for the passed counterparty node_id {}.",
1708+
err: format!("Channel with id {} not found for the passed counterparty node_id {}.",
17091709
log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
17101710

17111711
if test == InterceptTest::Fail {
@@ -1731,7 +1731,7 @@ fn do_test_intercepted_payment(test: InterceptTest) {
17311731
let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
17321732
let unusable_chan_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &temp_chan_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
17331733
assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1734-
err: format!("Funded channel with id {} not found for the passed counterparty node_id {}.",
1734+
err: format!("Channel with id {} not found for the passed counterparty node_id {}.",
17351735
temp_chan_id, nodes[2].node.get_our_node_id()) });
17361736
assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
17371737

lightning/src/util/enum_utils.rs

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// This file is Copyright its original authors, visible in version control
2+
// history.
3+
//
4+
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5+
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7+
// You may not use this file except in accordance with one or both of these
8+
// licenses.
9+
10+
//! Utilities for making working with enums, their variants, and inner values more convenient.
11+
12+
/// Returns an inner variant value from an enum with a pattern.
13+
/// Panics if the pattern does not match the actual enum value.
14+
#[macro_export]
15+
macro_rules! unwrap_enum_value {
16+
($enum:expr, $pattern:pat => $inner_value:expr) => {
17+
match $enum {
18+
$pattern => $inner_value,
19+
_ => panic!("Failed to unwrap enum value as variant was unexpected!"),
20+
}
21+
};
22+
}

lightning/src/util/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,6 @@ pub mod test_utils;
5858
#[cfg(any(test, feature = "_test_utils"))]
5959
pub mod enforcing_trait_impls;
6060

61+
/// Enum macro utilities.
62+
#[macro_use]
63+
pub(crate) mod enum_utils;

0 commit comments

Comments
 (0)