@@ -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 {
@@ -886,6 +887,7 @@ impl ProbabilisticScoringDecayParameters {
886
887
/// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
887
888
/// offset fields gives the opposite direction.
888
889
#[ repr( C ) ] // Force the fields in memory to be in the order we specify
890
+ #[ derive( Clone ) ]
889
891
pub struct ChannelLiquidity {
890
892
/// Lower channel liquidity bound in terms of an offset from zero.
891
893
min_liquidity_offset_msat : u64 ,
@@ -1156,6 +1158,15 @@ impl ChannelLiquidity {
1156
1158
}
1157
1159
}
1158
1160
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
+
1159
1170
/// Returns a view of the channel liquidity directed from `source` to `target` assuming
1160
1171
/// `capacity_msat`.
1161
1172
fn as_directed (
@@ -1689,6 +1700,91 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> ScoreUpdate for Probabilistic
1689
1700
}
1690
1701
}
1691
1702
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
+
1692
1788
#[ cfg( c_bindings) ]
1693
1789
impl < G : Deref < Target = NetworkGraph < L > > , L : Deref > Score for ProbabilisticScorer < G , L >
1694
1790
where L :: Target : Logger { }
@@ -1868,6 +1964,13 @@ mod bucketed_history {
1868
1964
self . buckets [ bucket] = self . buckets [ bucket] . saturating_add ( BUCKET_FIXED_POINT_ONE ) ;
1869
1965
}
1870
1966
}
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
+ }
1871
1974
}
1872
1975
1873
1976
impl_writeable_tlv_based ! ( HistoricalBucketRangeTracker , { ( 0 , buckets, required) } ) ;
@@ -1964,6 +2067,13 @@ mod bucketed_history {
1964
2067
-> DirectedHistoricalLiquidityTracker < & ' a mut HistoricalLiquidityTracker > {
1965
2068
DirectedHistoricalLiquidityTracker { source_less_than_target, tracker : self }
1966
2069
}
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
+ }
1967
2077
}
1968
2078
1969
2079
/// A set of buckets representing the history of where we've seen the minimum- and maximum-
@@ -2122,6 +2232,72 @@ mod bucketed_history {
2122
2232
Some ( ( cumulative_success_prob * ( 1024.0 * 1024.0 * 1024.0 ) ) as u64 )
2123
2233
}
2124
2234
}
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
+ }
2125
2301
}
2126
2302
2127
2303
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 {
2215
2391
2216
2392
#[ cfg( test) ]
2217
2393
mod tests {
2218
- use super :: { ChannelLiquidity , HistoricalLiquidityTracker , ProbabilisticScoringFeeParameters , ProbabilisticScoringDecayParameters , ProbabilisticScorer } ;
2394
+ use super :: { ChannelLiquidity , HistoricalLiquidityTracker , ProbabilisticScorer , ProbabilisticScoringDecayParameters , ProbabilisticScoringFeeParameters } ;
2219
2395
use crate :: blinded_path:: BlindedHop ;
2220
2396
use crate :: util:: config:: UserConfig ;
2221
2397
2222
2398
use crate :: ln:: channelmanager;
2223
2399
use crate :: ln:: msgs:: { ChannelAnnouncement , ChannelUpdate , UnsignedChannelAnnouncement , UnsignedChannelUpdate } ;
2224
2400
use crate :: routing:: gossip:: { EffectiveCapacity , NetworkGraph , NodeId } ;
2225
2401
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 } ;
2227
2403
use crate :: util:: ser:: { ReadableArgs , Writeable } ;
2228
2404
use crate :: util:: test_utils:: { self , TestLogger } ;
2229
2405
@@ -2233,6 +2409,7 @@ mod tests {
2233
2409
use bitcoin:: network:: Network ;
2234
2410
use bitcoin:: secp256k1:: { PublicKey , Secp256k1 , SecretKey } ;
2235
2411
use core:: time:: Duration ;
2412
+ use std:: rc:: Rc ;
2236
2413
use crate :: io;
2237
2414
2238
2415
fn source_privkey ( ) -> SecretKey {
@@ -3724,6 +3901,59 @@ mod tests {
3724
3901
assert_eq ! ( scorer. historical_estimated_payment_success_probability( 42 , & target, amount_msat, & params, false ) ,
3725
3902
Some ( 0.0 ) ) ;
3726
3903
}
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
+ }
3727
3957
}
3728
3958
3729
3959
#[ cfg( ldk_bench) ]
0 commit comments