Skip to content

Commit d6caa86

Browse files
committed
add combined scorer
1 parent b3e7ab0 commit d6caa86

File tree

1 file changed

+232
-2
lines changed

1 file changed

+232
-2
lines changed

lightning/src/routing/scoring.rs

+232-2
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 {
@@ -886,6 +887,7 @@ impl ProbabilisticScoringDecayParameters {
886887
/// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
887888
/// offset fields gives the opposite direction.
888889
#[repr(C)] // Force the fields in memory to be in the order we specify
890+
#[derive(Clone)]
889891
pub struct ChannelLiquidity {
890892
/// Lower channel liquidity bound in terms of an offset from zero.
891893
min_liquidity_offset_msat: u64,
@@ -1156,6 +1158,15 @@ impl ChannelLiquidity {
11561158
}
11571159
}
11581160

1161+
fn merge(&mut self, other: &Self) {
1162+
// Take average for min/max liquidity offsets.
1163+
self.min_liquidity_offset_msat = (self.min_liquidity_offset_msat + other.min_liquidity_offset_msat) / 2;
1164+
self.max_liquidity_offset_msat = (self.max_liquidity_offset_msat + other.max_liquidity_offset_msat) / 2;
1165+
1166+
// Merge historical liquidity data.
1167+
self.liquidity_history.merge(&other.liquidity_history);
1168+
}
1169+
11591170
/// Returns a view of the channel liquidity directed from `source` to `target` assuming
11601171
/// `capacity_msat`.
11611172
fn as_directed(
@@ -1689,6 +1700,91 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> ScoreUpdate for Probabilistic
16891700
}
16901701
}
16911702

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

18731976
impl_writeable_tlv_based!(HistoricalBucketRangeTracker, { (0, buckets, required) });
@@ -1964,6 +2067,13 @@ mod bucketed_history {
19642067
-> DirectedHistoricalLiquidityTracker<&'a mut HistoricalLiquidityTracker> {
19652068
DirectedHistoricalLiquidityTracker { source_less_than_target, tracker: self }
19662069
}
2070+
2071+
/// Merges the historical liquidity data from another tracker into this one.
2072+
pub fn merge(&mut self, other: &Self) {
2073+
self.min_liquidity_offset_history.merge(&other.min_liquidity_offset_history);
2074+
self.max_liquidity_offset_history.merge(&other.max_liquidity_offset_history);
2075+
self.recalculate_valid_point_count();
2076+
}
19672077
}
19682078

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

21272303
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> Writeable for ProbabilisticScorer<G, L> where L::Target: Logger {
@@ -2215,15 +2391,15 @@ impl Readable for ChannelLiquidity {
22152391

22162392
#[cfg(test)]
22172393
mod tests {
2218-
use super::{ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters, ProbabilisticScorer};
2394+
use super::{ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScorer, ProbabilisticScoringDecayParameters, ProbabilisticScoringFeeParameters};
22192395
use crate::blinded_path::BlindedHop;
22202396
use crate::util::config::UserConfig;
22212397

22222398
use crate::ln::channelmanager;
22232399
use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
22242400
use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
22252401
use crate::routing::router::{BlindedTail, Path, RouteHop, CandidateRouteHop, PublicHopCandidate};
2226-
use crate::routing::scoring::{ChannelUsage, ScoreLookUp, ScoreUpdate};
2402+
use crate::routing::scoring::{ChannelLiquidities, ChannelUsage, CombinedScorer, ScoreLookUp, ScoreUpdate};
22272403
use crate::util::ser::{ReadableArgs, Writeable};
22282404
use crate::util::test_utils::{self, TestLogger};
22292405

@@ -2233,6 +2409,7 @@ mod tests {
22332409
use bitcoin::network::Network;
22342410
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
22352411
use core::time::Duration;
2412+
use std::rc::Rc;
22362413
use crate::io;
22372414

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

37293959
#[cfg(ldk_bench)]

0 commit comments

Comments
 (0)