Skip to content

Commit b368941

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 ec9db02 commit b368941

File tree

1 file changed

+121
-118
lines changed

1 file changed

+121
-118
lines changed

lightning/src/ln/channelmanager.rs

+121-118
Original file line numberDiff line numberDiff line change
@@ -3242,134 +3242,137 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
32423242
continue;
32433243
}
32443244
};
3245-
if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
3246-
let mut add_htlc_msgs = Vec::new();
3247-
let mut fail_htlc_msgs = Vec::new();
3248-
for forward_info in pending_forwards.drain(..) {
3249-
match forward_info {
3250-
HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
3251-
routing: PendingHTLCRouting::Forward {
3252-
onion_packet, ..
3253-
}, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
3254-
prev_funding_outpoint } => {
3255-
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);
3256-
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3257-
short_channel_id: prev_short_channel_id,
3258-
outpoint: prev_funding_outpoint,
3259-
htlc_id: prev_htlc_id,
3260-
incoming_packet_shared_secret: incoming_shared_secret,
3261-
// Phantom payments are only PendingHTLCRouting::Receive.
3262-
phantom_shared_secret: None,
3263-
});
3264-
match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet, &self.logger) {
3265-
Err(e) => {
3266-
if let ChannelError::Ignore(msg) = e {
3267-
log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
3268-
} else {
3269-
panic!("Stated return value requirements in send_htlc() were not met");
3270-
}
3271-
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
3272-
failed_forwards.push((htlc_source, payment_hash,
3273-
HTLCFailReason::Reason { failure_code, data },
3274-
HTLCDestination::NextHopChannel { node_id: Some(chan.get().get_counterparty_node_id()), channel_id: forward_chan_id }
3275-
));
3276-
continue;
3277-
},
3278-
Ok(update_add) => {
3279-
match update_add {
3280-
Some(msg) => { add_htlc_msgs.push(msg); },
3281-
None => {
3282-
// Nothing to do here...we're waiting on a remote
3283-
// revoke_and_ack before we can add anymore HTLCs. The Channel
3284-
// will automatically handle building the update_add_htlc and
3285-
// commitment_signed messages when we can.
3286-
// TODO: Do some kind of timer to set the channel as !is_live()
3287-
// as we don't really want others relying on us relaying through
3288-
// this channel currently :/.
3245+
match channel_state.by_id.entry(forward_chan_id) {
3246+
hash_map::Entry::Vacant(_) => {
3247+
forwarding_channel_not_found!();
3248+
continue;
3249+
},
3250+
hash_map::Entry::Occupied(mut chan) => {
3251+
let mut add_htlc_msgs = Vec::new();
3252+
let mut fail_htlc_msgs = Vec::new();
3253+
for forward_info in pending_forwards.drain(..) {
3254+
match forward_info {
3255+
HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
3256+
routing: PendingHTLCRouting::Forward {
3257+
onion_packet, ..
3258+
}, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
3259+
prev_funding_outpoint } => {
3260+
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);
3261+
let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3262+
short_channel_id: prev_short_channel_id,
3263+
outpoint: prev_funding_outpoint,
3264+
htlc_id: prev_htlc_id,
3265+
incoming_packet_shared_secret: incoming_shared_secret,
3266+
// Phantom payments are only PendingHTLCRouting::Receive.
3267+
phantom_shared_secret: None,
3268+
});
3269+
match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet, &self.logger) {
3270+
Err(e) => {
3271+
if let ChannelError::Ignore(msg) = e {
3272+
log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
3273+
} else {
3274+
panic!("Stated return value requirements in send_htlc() were not met");
3275+
}
3276+
let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
3277+
failed_forwards.push((htlc_source, payment_hash,
3278+
HTLCFailReason::Reason { failure_code, data },
3279+
HTLCDestination::NextHopChannel { node_id: Some(chan.get().get_counterparty_node_id()), channel_id: forward_chan_id }
3280+
));
3281+
continue;
3282+
},
3283+
Ok(update_add) => {
3284+
match update_add {
3285+
Some(msg) => { add_htlc_msgs.push(msg); },
3286+
None => {
3287+
// Nothing to do here...we're waiting on a remote
3288+
// revoke_and_ack before we can add anymore HTLCs. The Channel
3289+
// will automatically handle building the update_add_htlc and
3290+
// commitment_signed messages when we can.
3291+
// TODO: Do some kind of timer to set the channel as !is_live()
3292+
// as we don't really want others relying on us relaying through
3293+
// this channel currently :/.
3294+
}
32893295
}
32903296
}
32913297
}
3292-
}
3293-
},
3294-
HTLCForwardInfo::AddHTLC { .. } => {
3295-
panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
3296-
},
3297-
HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
3298-
log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
3299-
match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet, &self.logger) {
3300-
Err(e) => {
3301-
if let ChannelError::Ignore(msg) = e {
3302-
log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
3303-
} else {
3304-
panic!("Stated return value requirements in get_update_fail_htlc() were not met");
3298+
},
3299+
HTLCForwardInfo::AddHTLC { .. } => {
3300+
panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
3301+
},
3302+
HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
3303+
log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
3304+
match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet, &self.logger) {
3305+
Err(e) => {
3306+
if let ChannelError::Ignore(msg) = e {
3307+
log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
3308+
} else {
3309+
panic!("Stated return value requirements in get_update_fail_htlc() were not met");
3310+
}
3311+
// fail-backs are best-effort, we probably already have one
3312+
// pending, and if not that's OK, if not, the channel is on
3313+
// the chain and sending the HTLC-Timeout is their problem.
3314+
continue;
3315+
},
3316+
Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
3317+
Ok(None) => {
3318+
// Nothing to do here...we're waiting on a remote
3319+
// revoke_and_ack before we can update the commitment
3320+
// transaction. The Channel will automatically handle
3321+
// building the update_fail_htlc and commitment_signed
3322+
// messages when we can.
3323+
// We don't need any kind of timer here as they should fail
3324+
// the channel onto the chain if they can't get our
3325+
// update_fail_htlc in time, it's not our problem.
33053326
}
3306-
// fail-backs are best-effort, we probably already have one
3307-
// pending, and if not that's OK, if not, the channel is on
3308-
// the chain and sending the HTLC-Timeout is their problem.
3309-
continue;
3310-
},
3311-
Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
3312-
Ok(None) => {
3313-
// Nothing to do here...we're waiting on a remote
3314-
// revoke_and_ack before we can update the commitment
3315-
// transaction. The Channel will automatically handle
3316-
// building the update_fail_htlc and commitment_signed
3317-
// messages when we can.
3318-
// We don't need any kind of timer here as they should fail
3319-
// the channel onto the chain if they can't get our
3320-
// update_fail_htlc in time, it's not our problem.
33213327
}
3322-
}
3323-
},
3328+
},
3329+
}
33243330
}
3325-
}
33263331

3327-
if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
3328-
let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
3329-
Ok(res) => res,
3330-
Err(e) => {
3331-
// We surely failed send_commitment due to bad keys, in that case
3332-
// close channel and then send error message to peer.
3333-
let counterparty_node_id = chan.get().get_counterparty_node_id();
3334-
let err: Result<(), _> = match e {
3335-
ChannelError::Ignore(_) | ChannelError::Warn(_) => {
3336-
panic!("Stated return value requirements in send_commitment() were not met");
3337-
}
3338-
ChannelError::Close(msg) => {
3339-
log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
3340-
let mut channel = remove_channel!(self, chan);
3341-
// ChannelClosed event is generated by handle_error for us.
3342-
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()))
3343-
},
3344-
};
3345-
handle_errors.push((counterparty_node_id, err));
3346-
continue;
3347-
}
3348-
};
3349-
match self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3350-
ChannelMonitorUpdateStatus::Completed => {},
3351-
e => {
3352-
handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
3353-
continue;
3332+
if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
3333+
let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
3334+
Ok(res) => res,
3335+
Err(e) => {
3336+
// We surely failed send_commitment due to bad keys, in that case
3337+
// close channel and then send error message to peer.
3338+
let counterparty_node_id = chan.get().get_counterparty_node_id();
3339+
let err: Result<(), _> = match e {
3340+
ChannelError::Ignore(_) | ChannelError::Warn(_) => {
3341+
panic!("Stated return value requirements in send_commitment() were not met");
3342+
}
3343+
ChannelError::Close(msg) => {
3344+
log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
3345+
let mut channel = remove_channel!(self, chan);
3346+
// ChannelClosed event is generated by handle_error for us.
3347+
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()))
3348+
},
3349+
};
3350+
handle_errors.push((counterparty_node_id, err));
3351+
continue;
3352+
}
3353+
};
3354+
match self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3355+
ChannelMonitorUpdateStatus::Completed => {},
3356+
e => {
3357+
handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
3358+
continue;
3359+
}
33543360
}
3361+
log_debug!(self.logger, "Forwarding HTLCs resulted in a commitment update with {} HTLCs added and {} HTLCs failed for channel {}",
3362+
add_htlc_msgs.len(), fail_htlc_msgs.len(), log_bytes!(chan.get().channel_id()));
3363+
channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3364+
node_id: chan.get().get_counterparty_node_id(),
3365+
updates: msgs::CommitmentUpdate {
3366+
update_add_htlcs: add_htlc_msgs,
3367+
update_fulfill_htlcs: Vec::new(),
3368+
update_fail_htlcs: fail_htlc_msgs,
3369+
update_fail_malformed_htlcs: Vec::new(),
3370+
update_fee: None,
3371+
commitment_signed: commitment_msg,
3372+
},
3373+
});
33553374
}
3356-
log_debug!(self.logger, "Forwarding HTLCs resulted in a commitment update with {} HTLCs added and {} HTLCs failed for channel {}",
3357-
add_htlc_msgs.len(), fail_htlc_msgs.len(), log_bytes!(chan.get().channel_id()));
3358-
channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3359-
node_id: chan.get().get_counterparty_node_id(),
3360-
updates: msgs::CommitmentUpdate {
3361-
update_add_htlcs: add_htlc_msgs,
3362-
update_fulfill_htlcs: Vec::new(),
3363-
update_fail_htlcs: fail_htlc_msgs,
3364-
update_fail_malformed_htlcs: Vec::new(),
3365-
update_fee: None,
3366-
commitment_signed: commitment_msg,
3367-
},
3368-
});
33693375
}
3370-
} else {
3371-
forwarding_channel_not_found!();
3372-
continue;
33733376
}
33743377
} else {
33753378
for forward_info in pending_forwards.drain(..) {

0 commit comments

Comments
 (0)