Skip to content

Commit ced0adc

Browse files
committed
add combined scorer
1 parent 7478d76 commit ced0adc

File tree

1 file changed

+232
-2
lines changed

1 file changed

+232
-2
lines changed

lightning/src/routing/scoring.rs

Lines changed: 232 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,7 @@ where L::Target: Logger {
478478
channel_liquidities: ChannelLiquidities,
479479
}
480480
/// Container for live and historical liquidity bounds for each channel.
481+
#[derive(Clone)]
481482
pub struct ChannelLiquidities(HashMap<u64, ChannelLiquidity>);
482483

483484
impl ChannelLiquidities {
@@ -882,6 +883,7 @@ impl ProbabilisticScoringDecayParameters {
882883
/// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
883884
/// offset fields gives the opposite direction.
884885
#[repr(C)] // Force the fields in memory to be in the order we specify
886+
#[derive(Clone)]
885887
pub struct ChannelLiquidity {
886888
/// Lower channel liquidity bound in terms of an offset from zero.
887889
min_liquidity_offset_msat: u64,
@@ -1152,6 +1154,15 @@ impl ChannelLiquidity {
11521154
}
11531155
}
11541156

1157+
fn merge(&mut self, other: &Self) {
1158+
// Take average for min/max liquidity offsets.
1159+
self.min_liquidity_offset_msat = (self.min_liquidity_offset_msat + other.min_liquidity_offset_msat) / 2;
1160+
self.max_liquidity_offset_msat = (self.max_liquidity_offset_msat + other.max_liquidity_offset_msat) / 2;
1161+
1162+
// Merge historical liquidity data.
1163+
self.liquidity_history.merge(&other.liquidity_history);
1164+
}
1165+
11551166
/// Returns a view of the channel liquidity directed from `source` to `target` assuming
11561167
/// `capacity_msat`.
11571168
fn as_directed(
@@ -1685,6 +1696,91 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> ScoreUpdate for Probabilistic
16851696
}
16861697
}
16871698

1699+
/// A probabilistic scorer that combines local and external information to score channels. This scorer is
1700+
/// shadow-tracking local only scores, so that it becomes possible to cleanly merge external scores when they become
1701+
/// available.
1702+
pub struct CombinedScorer<G: Deref<Target = NetworkGraph<L>>, L: Deref> where L::Target: Logger {
1703+
local_only_scorer: ProbabilisticScorer<G, L>,
1704+
scorer: ProbabilisticScorer<G, L>,
1705+
}
1706+
1707+
impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref + Clone> CombinedScorer<G, L> where L::Target: Logger {
1708+
/// Create a new combined scorer with the given local scorer.
1709+
pub fn new(local_scorer: ProbabilisticScorer<G, L>) -> Self {
1710+
let decay_params = local_scorer.decay_params;
1711+
let network_graph = local_scorer.network_graph.clone();
1712+
let logger = local_scorer.logger.clone();
1713+
let mut scorer = ProbabilisticScorer::new(decay_params, network_graph, logger);
1714+
1715+
scorer.channel_liquidities = local_scorer.channel_liquidities.clone();
1716+
1717+
Self {
1718+
local_only_scorer: local_scorer,
1719+
scorer: scorer,
1720+
}
1721+
}
1722+
1723+
/// Merge external channel liquidity information into the scorer.
1724+
pub fn merge(&mut self, mut external_scores: ChannelLiquidities, duration_since_epoch: Duration) {
1725+
// Decay both sets of scores to make them comparable and mergeable.
1726+
self.local_only_scorer.time_passed(duration_since_epoch);
1727+
external_scores.time_passed(duration_since_epoch, self.local_only_scorer.decay_params);
1728+
1729+
let local_scores = &self.local_only_scorer.channel_liquidities;
1730+
1731+
// For each channel, merge the external liquidity information with the isolated local liquidity information.
1732+
for (scid, mut liquidity) in external_scores.0 {
1733+
if let Some(local_liquidity) = local_scores.get(&scid) {
1734+
liquidity.merge(local_liquidity);
1735+
}
1736+
self.scorer.channel_liquidities.insert(scid, liquidity);
1737+
}
1738+
}
1739+
}
1740+
1741+
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> ScoreLookUp for CombinedScorer<G, L> where L::Target: Logger {
1742+
type ScoreParams = ProbabilisticScoringFeeParameters;
1743+
1744+
fn channel_penalty_msat(
1745+
&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &ProbabilisticScoringFeeParameters
1746+
) -> u64 {
1747+
self.scorer.channel_penalty_msat(candidate, usage, score_params)
1748+
}
1749+
}
1750+
1751+
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> ScoreUpdate for CombinedScorer<G, L> where L::Target: Logger {
1752+
fn payment_path_failed(&mut self,path: &Path,short_channel_id:u64,duration_since_epoch:Duration) {
1753+
self.local_only_scorer.payment_path_failed(path, short_channel_id, duration_since_epoch);
1754+
self.scorer.payment_path_failed(path, short_channel_id, duration_since_epoch);
1755+
}
1756+
1757+
fn payment_path_successful(&mut self,path: &Path,duration_since_epoch:Duration) {
1758+
self.local_only_scorer.payment_path_successful(path, duration_since_epoch);
1759+
self.scorer.payment_path_successful(path, duration_since_epoch);
1760+
}
1761+
1762+
fn probe_failed(&mut self,path: &Path,short_channel_id:u64,duration_since_epoch:Duration) {
1763+
self.local_only_scorer.probe_failed(path, short_channel_id, duration_since_epoch);
1764+
self.scorer.probe_failed(path, short_channel_id, duration_since_epoch);
1765+
}
1766+
1767+
fn probe_successful(&mut self,path: &Path,duration_since_epoch:Duration) {
1768+
self.local_only_scorer.probe_successful(path, duration_since_epoch);
1769+
self.scorer.probe_successful(path, duration_since_epoch);
1770+
}
1771+
1772+
fn time_passed(&mut self,duration_since_epoch:Duration) {
1773+
self.local_only_scorer.time_passed(duration_since_epoch);
1774+
self.scorer.time_passed(duration_since_epoch);
1775+
}
1776+
}
1777+
1778+
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> Writeable for CombinedScorer<G, L> where L::Target: Logger {
1779+
fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
1780+
self.local_only_scorer.write(writer)
1781+
}
1782+
}
1783+
16881784
#[cfg(c_bindings)]
16891785
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> Score for ProbabilisticScorer<G, L>
16901786
where L::Target: Logger {}
@@ -1864,6 +1960,13 @@ mod bucketed_history {
18641960
self.buckets[bucket] = self.buckets[bucket].saturating_add(BUCKET_FIXED_POINT_ONE);
18651961
}
18661962
}
1963+
1964+
/// Returns the average of the buckets between the two trackers.
1965+
pub(crate) fn merge(&mut self, other: &Self) -> () {
1966+
for (index, bucket) in self.buckets.iter_mut().enumerate() {
1967+
*bucket = (*bucket + other.buckets[index]) / 2;
1968+
}
1969+
}
18671970
}
18681971

18691972
impl_writeable_tlv_based!(HistoricalBucketRangeTracker, { (0, buckets, required) });
@@ -1960,6 +2063,13 @@ mod bucketed_history {
19602063
-> DirectedHistoricalLiquidityTracker<&'a mut HistoricalLiquidityTracker> {
19612064
DirectedHistoricalLiquidityTracker { source_less_than_target, tracker: self }
19622065
}
2066+
2067+
/// Merges the historical liquidity data from another tracker into this one.
2068+
pub fn merge(&mut self, other: &Self) {
2069+
self.min_liquidity_offset_history.merge(&other.min_liquidity_offset_history);
2070+
self.max_liquidity_offset_history.merge(&other.max_liquidity_offset_history);
2071+
self.recalculate_valid_point_count();
2072+
}
19632073
}
19642074

19652075
/// A set of buckets representing the history of where we've seen the minimum- and maximum-
@@ -2118,6 +2228,72 @@ mod bucketed_history {
21182228
Some((cumulative_success_prob * (1024.0 * 1024.0 * 1024.0)) as u64)
21192229
}
21202230
}
2231+
2232+
#[cfg(test)]
2233+
mod tests {
2234+
use crate::routing::scoring::ProbabilisticScoringFeeParameters;
2235+
2236+
use super::{HistoricalBucketRangeTracker, HistoricalLiquidityTracker};
2237+
#[test]
2238+
fn historical_liquidity_bucket_merge() {
2239+
let mut bucket1 = HistoricalBucketRangeTracker::new();
2240+
bucket1.track_datapoint(100, 1000);
2241+
assert_eq!(
2242+
bucket1.buckets,
2243+
[
2244+
0u16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2245+
0, 0, 0, 0, 0, 0, 0
2246+
]
2247+
);
2248+
2249+
let mut bucket2 = HistoricalBucketRangeTracker::new();
2250+
bucket2.track_datapoint(0, 1000);
2251+
assert_eq!(
2252+
bucket2.buckets,
2253+
[
2254+
32u16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2255+
0, 0, 0, 0, 0, 0, 0
2256+
]
2257+
);
2258+
2259+
bucket1.merge(&bucket2);
2260+
assert_eq!(
2261+
bucket1.buckets,
2262+
[
2263+
16u16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2264+
0, 0, 0, 0, 0, 0, 0
2265+
]
2266+
);
2267+
}
2268+
2269+
#[test]
2270+
fn historical_liquidity_tracker_merge() {
2271+
let params = ProbabilisticScoringFeeParameters::default();
2272+
2273+
let probability1: Option<u64>;
2274+
let mut tracker1 = HistoricalLiquidityTracker::new();
2275+
{
2276+
let mut directed_tracker1 = tracker1.as_directed_mut(true);
2277+
directed_tracker1.track_datapoint(100, 200, 1000);
2278+
probability1 = directed_tracker1
2279+
.calculate_success_probability_times_billion(&params, 500, 1000);
2280+
}
2281+
2282+
let mut tracker2 = HistoricalLiquidityTracker::new();
2283+
{
2284+
let mut directed_tracker2 = tracker2.as_directed_mut(true);
2285+
directed_tracker2.track_datapoint(200, 300, 1000);
2286+
}
2287+
2288+
tracker1.merge(&tracker2);
2289+
2290+
let directed_tracker1 = tracker1.as_directed(true);
2291+
let probability =
2292+
directed_tracker1.calculate_success_probability_times_billion(&params, 500, 1000);
2293+
2294+
assert_ne!(probability1, probability);
2295+
}
2296+
}
21212297
}
21222298

21232299
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> Writeable for ProbabilisticScorer<G, L> where L::Target: Logger {
@@ -2211,15 +2387,15 @@ impl Readable for ChannelLiquidity {
22112387

22122388
#[cfg(test)]
22132389
mod tests {
2214-
use super::{ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters, ProbabilisticScorer};
2390+
use super::{ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScorer, ProbabilisticScoringDecayParameters, ProbabilisticScoringFeeParameters};
22152391
use crate::blinded_path::BlindedHop;
22162392
use crate::util::config::UserConfig;
22172393

22182394
use crate::ln::channelmanager;
22192395
use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
22202396
use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
22212397
use crate::routing::router::{BlindedTail, Path, RouteHop, CandidateRouteHop, PublicHopCandidate};
2222-
use crate::routing::scoring::{ChannelUsage, ScoreLookUp, ScoreUpdate};
2398+
use crate::routing::scoring::{ChannelLiquidities, ChannelUsage, CombinedScorer, ScoreLookUp, ScoreUpdate};
22232399
use crate::util::ser::{ReadableArgs, Writeable};
22242400
use crate::util::test_utils::{self, TestLogger};
22252401

@@ -2229,6 +2405,7 @@ mod tests {
22292405
use bitcoin::network::Network;
22302406
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
22312407
use core::time::Duration;
2408+
use std::rc::Rc;
22322409
use crate::io;
22332410

22342411
fn source_privkey() -> SecretKey {
@@ -3720,6 +3897,59 @@ mod tests {
37203897
assert_eq!(scorer.historical_estimated_payment_success_probability(42, &target, amount_msat, &params, false),
37213898
Some(0.0));
37223899
}
3900+
3901+
#[test]
3902+
fn combined_scorer() {
3903+
let logger = TestLogger::new();
3904+
let network_graph = network_graph(&logger);
3905+
let params = ProbabilisticScoringFeeParameters::default();
3906+
let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
3907+
scorer.payment_path_failed(&payment_path_for_amount(600), 42, Duration::ZERO);
3908+
3909+
let mut combined_scorer = CombinedScorer::new(scorer);
3910+
3911+
// Verify that the combined_scorer has the correct liquidity range after a failed 600 msat payment.
3912+
let liquidity_range = combined_scorer.scorer.estimated_channel_liquidity_range(42, &target_node_id());
3913+
assert_eq!(liquidity_range.unwrap(), (0, 600));
3914+
3915+
let source = source_node_id();
3916+
let usage = ChannelUsage {
3917+
amount_msat: 750,
3918+
inflight_htlc_msat: 0,
3919+
effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_000, htlc_maximum_msat: 1_000 },
3920+
};
3921+
3922+
{
3923+
let network_graph = network_graph.read_only();
3924+
let channel = network_graph.channel(42).unwrap();
3925+
let (info, _) = channel.as_directed_from(&source).unwrap();
3926+
let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
3927+
info,
3928+
short_channel_id: 42,
3929+
});
3930+
3931+
let penalty = combined_scorer.channel_penalty_msat(&candidate, usage, &params);
3932+
3933+
let mut external_liquidity = ChannelLiquidity::new(Duration::ZERO);
3934+
let logger_rc = Rc::new(&logger); // Why necessary and not above for the network graph?
3935+
external_liquidity.as_directed_mut(&source_node_id(), &target_node_id(), 1_000).
3936+
successful(1000, Duration::ZERO, format_args!("test channel"), logger_rc.as_ref());
3937+
3938+
let mut external_scores = ChannelLiquidities::new();
3939+
3940+
external_scores.insert(42, external_liquidity);
3941+
combined_scorer.merge(external_scores, Duration::ZERO);
3942+
3943+
let penalty_after_merge = combined_scorer.channel_penalty_msat(&candidate, usage, &params);
3944+
3945+
// Since the external source observed a successful payment, the penalty should be lower after the merge.
3946+
assert!(penalty_after_merge < penalty);
3947+
}
3948+
3949+
// Verify that after the merge with a successful payment, the liquidity range is increased.
3950+
let liquidity_range = combined_scorer.scorer.estimated_channel_liquidity_range(42, &target_node_id());
3951+
assert_eq!(liquidity_range.unwrap(), (0, 300));
3952+
}
37233953
}
37243954

37253955
#[cfg(ldk_bench)]

0 commit comments

Comments
 (0)