Skip to content

Commit 05bca3b

Browse files
committed
add combined scorer
1 parent 50dda5d commit 05bca3b

File tree

1 file changed

+233
-2
lines changed

1 file changed

+233
-2
lines changed

lightning/src/routing/scoring.rs

+233-2
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,7 @@ where L::Target: Logger {
477477
channel_liquidities: ChannelLiquidities,
478478
}
479479
/// ChannelLiquidities contains live and historical liquidity bounds for each channel.
480+
#[derive(Clone)]
480481
pub struct ChannelLiquidities(HashMap<u64, ChannelLiquidity>);
481482

482483
impl ChannelLiquidities {
@@ -885,6 +886,7 @@ impl ProbabilisticScoringDecayParameters {
885886
/// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
886887
/// offset fields gives the opposite direction.
887888
#[repr(C)] // Force the fields in memory to be in the order we specify
889+
#[derive(Clone)]
888890
pub struct ChannelLiquidity {
889891
/// Lower channel liquidity bound in terms of an offset from zero.
890892
min_liquidity_offset_msat: u64,
@@ -1155,6 +1157,15 @@ impl ChannelLiquidity {
11551157
}
11561158
}
11571159

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

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

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

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

@@ -2216,15 +2393,15 @@ impl Readable for ChannelLiquidity {
22162393

22172394
#[cfg(test)]
22182395
mod tests {
2219-
use super::{ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters, ProbabilisticScorer};
2396+
use super::{ChannelLiquidity, HistoricalLiquidityTracker, ProbabilisticScorer, ProbabilisticScoringDecayParameters, ProbabilisticScoringFeeParameters};
22202397
use crate::blinded_path::BlindedHop;
22212398
use crate::util::config::UserConfig;
22222399

22232400
use crate::ln::channelmanager;
22242401
use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
22252402
use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
22262403
use crate::routing::router::{BlindedTail, Path, RouteHop, CandidateRouteHop, PublicHopCandidate};
2227-
use crate::routing::scoring::{ChannelUsage, ScoreLookUp, ScoreUpdate};
2404+
use crate::routing::scoring::{ChannelLiquidities, ChannelUsage, CombinedScorer, ScoreLookUp, ScoreUpdate};
22282405
use crate::util::ser::{ReadableArgs, Writeable};
22292406
use crate::util::test_utils::{self, TestLogger};
22302407

@@ -2234,6 +2411,7 @@ mod tests {
22342411
use bitcoin::network::Network;
22352412
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
22362413
use core::time::Duration;
2414+
use std::rc::Rc;
22372415
use crate::io;
22382416

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

37303961
#[cfg(ldk_bench)]

0 commit comments

Comments
 (0)