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

Commit 175696c

Browse files
committed
Adapt calculate_amount_to_forward_per_htlc to avoid over/underflows
1 parent 5667dca commit 175696c

File tree

1 file changed

+22
-15
lines changed

1 file changed

+22
-15
lines changed

src/lsps2/channel_manager.rs

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1271,31 +1271,38 @@ where
12711271
fn calculate_amount_to_forward_per_htlc(
12721272
htlcs: &[InterceptedHTLC], total_amt_to_forward_msat: u64,
12731273
) -> Vec<(InterceptId, u64)> {
1274+
// TODO: we should eventually make sure the HTLCs are all above ChannelDetails::next_outbound_minimum_msat
12741275
let total_received_msat: u64 =
12751276
htlcs.iter().map(|htlc| htlc.expected_outbound_amount_msat).sum();
12761277

1277-
let mut fee_remaining_msat = total_received_msat - total_amt_to_forward_msat;
1278-
let total_fee_msat = fee_remaining_msat;
1278+
match total_received_msat.checked_sub(total_amt_to_forward_msat) {
1279+
Some(total_fee_msat) => {
1280+
let mut fee_remaining_msat = total_fee_msat;
12791281

1280-
let mut per_htlc_forwards = vec![];
1282+
let mut per_htlc_forwards = vec![];
12811283

1282-
for (index, htlc) in htlcs.iter().enumerate() {
1283-
let proportional_fee_amt_msat =
1284-
total_fee_msat * htlc.expected_outbound_amount_msat / total_received_msat;
1284+
for (index, htlc) in htlcs.iter().enumerate() {
1285+
let proportional_fee_amt_msat =
1286+
total_fee_msat * (htlc.expected_outbound_amount_msat / total_received_msat);
12851287

1286-
let mut actual_fee_amt_msat = core::cmp::min(fee_remaining_msat, proportional_fee_amt_msat);
1287-
fee_remaining_msat -= actual_fee_amt_msat;
1288+
let mut actual_fee_amt_msat =
1289+
core::cmp::min(fee_remaining_msat, proportional_fee_amt_msat);
1290+
fee_remaining_msat -= actual_fee_amt_msat;
12881291

1289-
if index == htlcs.len() - 1 {
1290-
actual_fee_amt_msat += fee_remaining_msat;
1291-
}
1292+
if index == htlcs.len() - 1 {
1293+
actual_fee_amt_msat += fee_remaining_msat;
1294+
}
12921295

1293-
let amount_to_forward_msat = htlc.expected_outbound_amount_msat - actual_fee_amt_msat;
1296+
let amount_to_forward_msat =
1297+
htlc.expected_outbound_amount_msat.saturating_sub(actual_fee_amt_msat);
12941298

1295-
per_htlc_forwards.push((htlc.intercept_id, amount_to_forward_msat))
1296-
}
1299+
per_htlc_forwards.push((htlc.intercept_id, amount_to_forward_msat))
1300+
}
12971301

1298-
per_htlc_forwards
1302+
per_htlc_forwards
1303+
}
1304+
None => Vec::new(),
1305+
}
12991306
}
13001307

13011308
#[cfg(test)]

0 commit comments

Comments
 (0)