Skip to content
This repository was archived by the owner on Jan 6, 2025. It is now read-only.

Commit b94b2fe

Browse files
committed
Adapt calculate_amount_to_forward_per_htlc to avoid over/underflows
1 parent 2dea1a9 commit b94b2fe

File tree

1 file changed

+22
-15
lines changed

1 file changed

+22
-15
lines changed

src/lsps2/service.rs

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -779,31 +779,38 @@ where
779779
fn calculate_amount_to_forward_per_htlc(
780780
htlcs: &[InterceptedHTLC], total_amt_to_forward_msat: u64,
781781
) -> Vec<(InterceptId, u64)> {
782+
// TODO: we should eventually make sure the HTLCs are all above ChannelDetails::next_outbound_minimum_msat
782783
let total_received_msat: u64 =
783784
htlcs.iter().map(|htlc| htlc.expected_outbound_amount_msat).sum();
784785

785-
let mut fee_remaining_msat = total_received_msat - total_amt_to_forward_msat;
786-
let total_fee_msat = fee_remaining_msat;
786+
match total_received_msat.checked_sub(total_amt_to_forward_msat) {
787+
Some(total_fee_msat) => {
788+
let mut fee_remaining_msat = total_fee_msat;
787789

788-
let mut per_htlc_forwards = vec![];
790+
let mut per_htlc_forwards = vec![];
789791

790-
for (index, htlc) in htlcs.iter().enumerate() {
791-
let proportional_fee_amt_msat =
792-
total_fee_msat * htlc.expected_outbound_amount_msat / total_received_msat;
792+
for (index, htlc) in htlcs.iter().enumerate() {
793+
let proportional_fee_amt_msat =
794+
total_fee_msat * (htlc.expected_outbound_amount_msat / total_received_msat);
793795

794-
let mut actual_fee_amt_msat = core::cmp::min(fee_remaining_msat, proportional_fee_amt_msat);
795-
fee_remaining_msat -= actual_fee_amt_msat;
796+
let mut actual_fee_amt_msat =
797+
core::cmp::min(fee_remaining_msat, proportional_fee_amt_msat);
798+
fee_remaining_msat -= actual_fee_amt_msat;
796799

797-
if index == htlcs.len() - 1 {
798-
actual_fee_amt_msat += fee_remaining_msat;
799-
}
800+
if index == htlcs.len() - 1 {
801+
actual_fee_amt_msat += fee_remaining_msat;
802+
}
800803

801-
let amount_to_forward_msat = htlc.expected_outbound_amount_msat - actual_fee_amt_msat;
804+
let amount_to_forward_msat =
805+
htlc.expected_outbound_amount_msat.saturating_sub(actual_fee_amt_msat);
802806

803-
per_htlc_forwards.push((htlc.intercept_id, amount_to_forward_msat))
804-
}
807+
per_htlc_forwards.push((htlc.intercept_id, amount_to_forward_msat))
808+
}
805809

806-
per_htlc_forwards
810+
per_htlc_forwards
811+
}
812+
None => Vec::new(),
813+
}
807814
}
808815

809816
#[cfg(test)]

0 commit comments

Comments
 (0)