Skip to content

Commit b4324c0

Browse files
committed
Fix overflow in ProbabilisticScorer
When a routing hint is given in an invoice, the effective capacity of the channel is assumed to be infinite (i.e., u64::max_value) if the hop is private. Adding 1 to this in the success probability calculation will cause an overflow and ultimately an `index out of bounds panic` in log10_times_1024. This was not an issue with using log10 because the use of f64 would give infinite which casts to 0 for u64.
1 parent 9d8ba85 commit b4324c0

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

lightning/src/routing/scoring.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -708,8 +708,8 @@ impl<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> DirectedChannelLiqui
708708
} else if amount_msat <= min_liquidity_msat {
709709
0
710710
} else {
711-
let numerator = max_liquidity_msat + 1 - amount_msat;
712-
let denominator = max_liquidity_msat + 1 - min_liquidity_msat;
711+
let numerator = (max_liquidity_msat - amount_msat).saturating_add(1);
712+
let denominator = (max_liquidity_msat - min_liquidity_msat).saturating_add(1);
713713
match params.cost_function {
714714
ProbabilisticScoringCostFunction::NegativeLogSuccessProbability => {
715715
let penalty_msat = approx::negative_log10_times_1024(numerator, denominator)
@@ -2136,4 +2136,20 @@ mod tests {
21362136
let scorer = ProbabilisticScorer::new(params, &network_graph);
21372137
assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 1085);
21382138
}
2139+
2140+
#[test]
2141+
fn calculates_log10_without_overflowing_u64_max_value() {
2142+
let network_graph = network_graph();
2143+
let source = source_node_id();
2144+
let target = target_node_id();
2145+
2146+
let params = ProbabilisticScoringParameters {
2147+
base_penalty_msat: 0, ..Default::default()
2148+
};
2149+
let scorer = ProbabilisticScorer::new(params, &network_graph);
2150+
assert_eq!(
2151+
scorer.channel_penalty_msat(42, u64::max_value(), u64::max_value(), &source, &target),
2152+
20_000,
2153+
);
2154+
}
21392155
}

0 commit comments

Comments
 (0)