@@ -478,6 +478,7 @@ where L::Target: Logger {
478
478
channel_liquidities : ChannelLiquidities ,
479
479
}
480
480
/// Container for live and historical liquidity bounds for each channel.
481
+ #[ derive( Clone ) ]
481
482
pub struct ChannelLiquidities ( HashMap < u64 , ChannelLiquidity > ) ;
482
483
483
484
impl ChannelLiquidities {
@@ -878,6 +879,7 @@ impl ProbabilisticScoringDecayParameters {
878
879
/// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
879
880
/// offset fields gives the opposite direction.
880
881
#[ repr( C ) ] // Force the fields in memory to be in the order we specify
882
+ #[ derive( Clone ) ]
881
883
pub struct ChannelLiquidity {
882
884
/// Lower channel liquidity bound in terms of an offset from zero.
883
885
min_liquidity_offset_msat : u64 ,
@@ -1148,6 +1150,15 @@ impl ChannelLiquidity {
1148
1150
}
1149
1151
}
1150
1152
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
+
1151
1162
/// Returns a view of the channel liquidity directed from `source` to `target` assuming
1152
1163
/// `capacity_msat`.
1153
1164
fn as_directed (
@@ -1681,6 +1692,91 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> ScoreUpdate for Probabilistic
1681
1692
}
1682
1693
}
1683
1694
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
+
1684
1780
#[ cfg( c_bindings) ]
1685
1781
impl < G : Deref < Target = NetworkGraph < L > > , L : Deref > Score for ProbabilisticScorer < G , L >
1686
1782
where L :: Target : Logger { }
@@ -1860,6 +1956,13 @@ mod bucketed_history {
1860
1956
self . buckets [ bucket] = self . buckets [ bucket] . saturating_add ( BUCKET_FIXED_POINT_ONE ) ;
1861
1957
}
1862
1958
}
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
+ }
1863
1966
}
1864
1967
1865
1968
impl_writeable_tlv_based ! ( HistoricalBucketRangeTracker , { ( 0 , buckets, required) } ) ;
@@ -1956,6 +2059,13 @@ mod bucketed_history {
1956
2059
-> DirectedHistoricalLiquidityTracker < & ' a mut HistoricalLiquidityTracker > {
1957
2060
DirectedHistoricalLiquidityTracker { source_less_than_target, tracker : self }
1958
2061
}
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
+ }
1959
2069
}
1960
2070
1961
2071
/// A set of buckets representing the history of where we've seen the minimum- and maximum-
@@ -2114,6 +2224,72 @@ mod bucketed_history {
2114
2224
Some ( ( cumulative_success_prob * ( 1024.0 * 1024.0 * 1024.0 ) ) as u64 )
2115
2225
}
2116
2226
}
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
+ }
2117
2293
}
2118
2294
2119
2295
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 {
2207
2383
2208
2384
#[ cfg( test) ]
2209
2385
mod tests {
2210
- use super :: { ChannelLiquidity , HistoricalLiquidityTracker , ProbabilisticScoringFeeParameters , ProbabilisticScoringDecayParameters , ProbabilisticScorer } ;
2386
+ use super :: { ChannelLiquidity , HistoricalLiquidityTracker , ProbabilisticScorer , ProbabilisticScoringDecayParameters , ProbabilisticScoringFeeParameters } ;
2211
2387
use crate :: blinded_path:: BlindedHop ;
2212
2388
use crate :: util:: config:: UserConfig ;
2213
2389
2214
2390
use crate :: ln:: channelmanager;
2215
2391
use crate :: ln:: msgs:: { ChannelAnnouncement , ChannelUpdate , UnsignedChannelAnnouncement , UnsignedChannelUpdate } ;
2216
2392
use crate :: routing:: gossip:: { EffectiveCapacity , NetworkGraph , NodeId } ;
2217
2393
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 } ;
2219
2395
use crate :: util:: ser:: { ReadableArgs , Writeable } ;
2220
2396
use crate :: util:: test_utils:: { self , TestLogger } ;
2221
2397
@@ -2225,6 +2401,7 @@ mod tests {
2225
2401
use bitcoin:: network:: Network ;
2226
2402
use bitcoin:: secp256k1:: { PublicKey , Secp256k1 , SecretKey } ;
2227
2403
use core:: time:: Duration ;
2404
+ use std:: rc:: Rc ;
2228
2405
use crate :: io;
2229
2406
2230
2407
fn source_privkey ( ) -> SecretKey {
@@ -3716,6 +3893,59 @@ mod tests {
3716
3893
assert_eq ! ( scorer. historical_estimated_payment_success_probability( 42 , & target, amount_msat, & params, false ) ,
3717
3894
Some ( 0.0 ) ) ;
3718
3895
}
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
+ }
3719
3949
}
3720
3950
3721
3951
#[ cfg( ldk_bench) ]
0 commit comments