Skip to content

Commit 590eae3

Browse files
Make process_pending_htlc_forwards more readable
Refactor `process_pending_htlc_forwards` to ensure that both branches that fails `pending_forwards` are placed next to eachother for improved readability.
1 parent 1e7dd6c commit 590eae3

File tree

1 file changed

+121
-118
lines changed

1 file changed

+121
-118
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 121 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -3177,134 +3177,137 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
31773177
continue;
31783178
}
31793179
};
3180-
if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
3181-
let mut add_htlc_msgs = Vec::new();
3182-
let mut fail_htlc_msgs = Vec::new();
3183-
for forward_info in pending_forwards.drain(..) {
3184-
match forward_info {
3185-
HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
3186-
routing: PendingHTLCRouting::Forward {
3187-
onion_packet, ..
3188-
}, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
3189-
prev_funding_outpoint } => {
3190-
log_trace!(self.logger, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", prev_short_channel_id, log_bytes!(payment_hash.0), short_chan_id);
3191-
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3192-
short_channel_id: prev_short_channel_id,
3193-
outpoint: prev_funding_outpoint,
3194-
htlc_id: prev_htlc_id,
3195-
incoming_packet_shared_secret: incoming_shared_secret,
3196-
// Phantom payments are only PendingHTLCRouting::Receive.
3197-
phantom_shared_secret: None,
3198-
});
3199-
match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet, &self.logger) {
3200-
Err(e) => {
3201-
if let ChannelError::Ignore(msg) = e {
3202-
log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
3203-
} else {
3204-
panic!("Stated return value requirements in send_htlc() were not met");
3205-
}
3206-
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
3207-
failed_forwards.push((htlc_source, payment_hash,
3208-
HTLCFailReason::Reason { failure_code, data },
3209-
HTLCDestination::NextHopChannel { node_id: Some(chan.get().get_counterparty_node_id()), channel_id: forward_chan_id }
3210-
));
3211-
continue;
3212-
},
3213-
Ok(update_add) => {
3214-
match update_add {
3215-
Some(msg) => { add_htlc_msgs.push(msg); },
3216-
None => {
3217-
// Nothing to do here...we're waiting on a remote
3218-
// revoke_and_ack before we can add anymore HTLCs. The Channel
3219-
// will automatically handle building the update_add_htlc and
3220-
// commitment_signed messages when we can.
3221-
// TODO: Do some kind of timer to set the channel as !is_live()
3222-
// as we don't really want others relying on us relaying through
3223-
// this channel currently :/.
3180+
match channel_state.by_id.entry(forward_chan_id) {
3181+
hash_map::Entry::Vacant(_) => {
3182+
forwarding_channel_not_found!();
3183+
continue;
3184+
},
3185+
hash_map::Entry::Occupied(mut chan) => {
3186+
let mut add_htlc_msgs = Vec::new();
3187+
let mut fail_htlc_msgs = Vec::new();
3188+
for forward_info in pending_forwards.drain(..) {
3189+
match forward_info {
3190+
HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
3191+
routing: PendingHTLCRouting::Forward {
3192+
onion_packet, ..
3193+
}, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
3194+
prev_funding_outpoint } => {
3195+
log_trace!(self.logger, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", prev_short_channel_id, log_bytes!(payment_hash.0), short_chan_id);
3196+
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3197+
short_channel_id: prev_short_channel_id,
3198+
outpoint: prev_funding_outpoint,
3199+
htlc_id: prev_htlc_id,
3200+
incoming_packet_shared_secret: incoming_shared_secret,
3201+
// Phantom payments are only PendingHTLCRouting::Receive.
3202+
phantom_shared_secret: None,
3203+
});
3204+
match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet, &self.logger) {
3205+
Err(e) => {
3206+
if let ChannelError::Ignore(msg) = e {
3207+
log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
3208+
} else {
3209+
panic!("Stated return value requirements in send_htlc() were not met");
3210+
}
3211+
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
3212+
failed_forwards.push((htlc_source, payment_hash,
3213+
HTLCFailReason::Reason { failure_code, data },
3214+
HTLCDestination::NextHopChannel { node_id: Some(chan.get().get_counterparty_node_id()), channel_id: forward_chan_id }
3215+
));
3216+
continue;
3217+
},
3218+
Ok(update_add) => {
3219+
match update_add {
3220+
Some(msg) => { add_htlc_msgs.push(msg); },
3221+
None => {
3222+
// Nothing to do here...we're waiting on a remote
3223+
// revoke_and_ack before we can add anymore HTLCs. The Channel
3224+
// will automatically handle building the update_add_htlc and
3225+
// commitment_signed messages when we can.
3226+
// TODO: Do some kind of timer to set the channel as !is_live()
3227+
// as we don't really want others relying on us relaying through
3228+
// this channel currently :/.
3229+
}
32243230
}
32253231
}
32263232
}
3227-
}
3228-
},
3229-
HTLCForwardInfo::AddHTLC { .. } => {
3230-
panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
3231-
},
3232-
HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
3233-
log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
3234-
match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet, &self.logger) {
3235-
Err(e) => {
3236-
if let ChannelError::Ignore(msg) = e {
3237-
log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
3238-
} else {
3239-
panic!("Stated return value requirements in get_update_fail_htlc() were not met");
3233+
},
3234+
HTLCForwardInfo::AddHTLC { .. } => {
3235+
panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
3236+
},
3237+
HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
3238+
log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
3239+
match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet, &self.logger) {
3240+
Err(e) => {
3241+
if let ChannelError::Ignore(msg) = e {
3242+
log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
3243+
} else {
3244+
panic!("Stated return value requirements in get_update_fail_htlc() were not met");
3245+
}
3246+
// fail-backs are best-effort, we probably already have one
3247+
// pending, and if not that's OK, if not, the channel is on
3248+
// the chain and sending the HTLC-Timeout is their problem.
3249+
continue;
3250+
},
3251+
Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
3252+
Ok(None) => {
3253+
// Nothing to do here...we're waiting on a remote
3254+
// revoke_and_ack before we can update the commitment
3255+
// transaction. The Channel will automatically handle
3256+
// building the update_fail_htlc and commitment_signed
3257+
// messages when we can.
3258+
// We don't need any kind of timer here as they should fail
3259+
// the channel onto the chain if they can't get our
3260+
// update_fail_htlc in time, it's not our problem.
32403261
}
3241-
// fail-backs are best-effort, we probably already have one
3242-
// pending, and if not that's OK, if not, the channel is on
3243-
// the chain and sending the HTLC-Timeout is their problem.
3244-
continue;
3245-
},
3246-
Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
3247-
Ok(None) => {
3248-
// Nothing to do here...we're waiting on a remote
3249-
// revoke_and_ack before we can update the commitment
3250-
// transaction. The Channel will automatically handle
3251-
// building the update_fail_htlc and commitment_signed
3252-
// messages when we can.
3253-
// We don't need any kind of timer here as they should fail
3254-
// the channel onto the chain if they can't get our
3255-
// update_fail_htlc in time, it's not our problem.
32563262
}
3257-
}
3258-
},
3263+
},
3264+
}
32593265
}
3260-
}
32613266

3262-
if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
3263-
let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
3264-
Ok(res) => res,
3265-
Err(e) => {
3266-
// We surely failed send_commitment due to bad keys, in that case
3267-
// close channel and then send error message to peer.
3268-
let counterparty_node_id = chan.get().get_counterparty_node_id();
3269-
let err: Result<(), _> = match e {
3270-
ChannelError::Ignore(_) | ChannelError::Warn(_) => {
3271-
panic!("Stated return value requirements in send_commitment() were not met");
3272-
}
3273-
ChannelError::Close(msg) => {
3274-
log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
3275-
let mut channel = remove_channel!(self, chan);
3276-
// ChannelClosed event is generated by handle_error for us.
3277-
Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel.channel_id(), channel.get_user_id(), channel.force_shutdown(true), self.get_channel_update_for_broadcast(&channel).ok()))
3278-
},
3279-
};
3280-
handle_errors.push((counterparty_node_id, err));
3281-
continue;
3282-
}
3283-
};
3284-
match self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3285-
ChannelMonitorUpdateStatus::Completed => {},
3286-
e => {
3287-
handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
3288-
continue;
3267+
if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
3268+
let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
3269+
Ok(res) => res,
3270+
Err(e) => {
3271+
// We surely failed send_commitment due to bad keys, in that case
3272+
// close channel and then send error message to peer.
3273+
let counterparty_node_id = chan.get().get_counterparty_node_id();
3274+
let err: Result<(), _> = match e {
3275+
ChannelError::Ignore(_) | ChannelError::Warn(_) => {
3276+
panic!("Stated return value requirements in send_commitment() were not met");
3277+
}
3278+
ChannelError::Close(msg) => {
3279+
log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
3280+
let mut channel = remove_channel!(self, chan);
3281+
// ChannelClosed event is generated by handle_error for us.
3282+
Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel.channel_id(), channel.get_user_id(), channel.force_shutdown(true), self.get_channel_update_for_broadcast(&channel).ok()))
3283+
},
3284+
};
3285+
handle_errors.push((counterparty_node_id, err));
3286+
continue;
3287+
}
3288+
};
3289+
match self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3290+
ChannelMonitorUpdateStatus::Completed => {},
3291+
e => {
3292+
handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
3293+
continue;
3294+
}
32893295
}
3296+
log_debug!(self.logger, "Forwarding HTLCs resulted in a commitment update with {} HTLCs added and {} HTLCs failed for channel {}",
3297+
add_htlc_msgs.len(), fail_htlc_msgs.len(), log_bytes!(chan.get().channel_id()));
3298+
channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3299+
node_id: chan.get().get_counterparty_node_id(),
3300+
updates: msgs::CommitmentUpdate {
3301+
update_add_htlcs: add_htlc_msgs,
3302+
update_fulfill_htlcs: Vec::new(),
3303+
update_fail_htlcs: fail_htlc_msgs,
3304+
update_fail_malformed_htlcs: Vec::new(),
3305+
update_fee: None,
3306+
commitment_signed: commitment_msg,
3307+
},
3308+
});
32903309
}
3291-
log_debug!(self.logger, "Forwarding HTLCs resulted in a commitment update with {} HTLCs added and {} HTLCs failed for channel {}",
3292-
add_htlc_msgs.len(), fail_htlc_msgs.len(), log_bytes!(chan.get().channel_id()));
3293-
channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3294-
node_id: chan.get().get_counterparty_node_id(),
3295-
updates: msgs::CommitmentUpdate {
3296-
update_add_htlcs: add_htlc_msgs,
3297-
update_fulfill_htlcs: Vec::new(),
3298-
update_fail_htlcs: fail_htlc_msgs,
3299-
update_fail_malformed_htlcs: Vec::new(),
3300-
update_fee: None,
3301-
commitment_signed: commitment_msg,
3302-
},
3303-
});
33043310
}
3305-
} else {
3306-
forwarding_channel_not_found!();
3307-
continue;
33083311
}
33093312
} else {
33103313
for forward_info in pending_forwards.drain(..) {

0 commit comments

Comments
 (0)