Skip to content

Commit 6ad185f

Browse files
committed
add combined scorer
1 parent 754cb70 commit 6ad185f

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 {
@@ -878,6 +879,7 @@ impl ProbabilisticScoringDecayParameters {
878879
/// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
879880
/// offset fields gives the opposite direction.
880881
#[repr(C)] // Force the fields in memory to be in the order we specify
882+
#[derive(Clone)]
881883
pub struct ChannelLiquidity {
882884
/// Lower channel liquidity bound in terms of an offset from zero.
883885
min_liquidity_offset_msat: u64,
@@ -1148,6 +1150,15 @@ impl ChannelLiquidity {
11481150
}
11491151
}
11501152

1153+
fn merge(&mut self, other: &Self) {
1154+
// Take average for min/max liquidity offsets.
1155+
self.min_liquidity_offset_msat = (self.min_liquidity_offset_msat + other.min_liquidity_offset_msat) / 2;
1156+
self.max_liquidity_offset_msat = (self.max_liquidity_offset_msat + other.max_liquidity_offset_msat) / 2;
1157+
1158+
// Merge historical liquidity data.
1159+
self.liquidity_history.merge(&other.liquidity_history);
1160+
}
1161+
11511162
/// Returns a view of the channel liquidity directed from `source` to `target` assuming
11521163
/// `capacity_msat`.
11531164
fn as_directed(
@@ -1681,6 +1692,91 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> ScoreUpdate for Probabilistic
16811692
}
16821693
}
16831694

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

18651968
impl_writeable_tlv_based!(HistoricalBucketRangeTracker, { (0, buckets, required) });
@@ -1956,6 +2059,13 @@ mod bucketed_history {
19562059
-> DirectedHistoricalLiquidityTracker<&'a mut HistoricalLiquidityTracker> {
19572060
DirectedHistoricalLiquidityTracker { source_less_than_target, tracker: self }
19582061
}
2062+
2063+
/// Merges the historical liquidity data from another tracker into this one.
2064+
pub fn merge(&mut self, other: &Self) {
2065+
self.min_liquidity_offset_history.merge(&other.min_liquidity_offset_history);
2066+
self.max_liquidity_offset_history.merge(&other.max_liquidity_offset_history);
2067+
self.recalculate_valid_point_count();
2068+
}
19592069
}
19602070

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

21192295
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> Writeable for ProbabilisticScorer<G, L> where L::Target: Logger {
@@ -2207,15 +2383,15 @@ impl Readable for ChannelLiquidity {
22072383

22082384
#[cfg(test)]
22092385
mod tests {
2210-
use super::{ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters, ProbabilisticScorer};
2386+
use super::{ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScorer, ProbabilisticScoringDecayParameters, ProbabilisticScoringFeeParameters};
22112387
use crate::blinded_path::BlindedHop;
22122388
use crate::util::config::UserConfig;
22132389

22142390
use crate::ln::channelmanager;
22152391
use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
22162392
use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
22172393
use crate::routing::router::{BlindedTail, Path, RouteHop, CandidateRouteHop, PublicHopCandidate};
2218-
use crate::routing::scoring::{ChannelUsage, ScoreLookUp, ScoreUpdate};
2394+
use crate::routing::scoring::{ChannelLiquidities, ChannelUsage, CombinedScorer, ScoreLookUp, ScoreUpdate};
22192395
use crate::util::ser::{ReadableArgs, Writeable};
22202396
use crate::util::test_utils::{self, TestLogger};
22212397

@@ -2225,6 +2401,7 @@ mod tests {
22252401
use bitcoin::network::Network;
22262402
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
22272403
use core::time::Duration;
2404+
use std::rc::Rc;
22282405
use crate::io;
22292406

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

37213951
#[cfg(ldk_bench)]

0 commit comments

Comments
 (0)