@@ -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 {
@@ -877,6 +878,7 @@ impl ProbabilisticScoringDecayParameters {
877
878
/// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
878
879
/// offset fields gives the opposite direction.
879
880
#[ repr( C ) ] // Force the fields in memory to be in the order we specify
881
+ #[ derive( Clone ) ]
880
882
pub struct ChannelLiquidity {
881
883
/// Lower channel liquidity bound in terms of an offset from zero.
882
884
min_liquidity_offset_msat : u64 ,
@@ -1147,6 +1149,15 @@ impl ChannelLiquidity {
1147
1149
}
1148
1150
}
1149
1151
1152
+ fn merge ( & mut self , other : & Self ) {
1153
+ // Take average for min/max liquidity offsets.
1154
+ self . min_liquidity_offset_msat = ( self . min_liquidity_offset_msat + other. min_liquidity_offset_msat ) / 2 ;
1155
+ self . max_liquidity_offset_msat = ( self . max_liquidity_offset_msat + other. max_liquidity_offset_msat ) / 2 ;
1156
+
1157
+ // Merge historical liquidity data.
1158
+ self . liquidity_history . merge ( & other. liquidity_history ) ;
1159
+ }
1160
+
1150
1161
/// Returns a view of the channel liquidity directed from `source` to `target` assuming
1151
1162
/// `capacity_msat`.
1152
1163
fn as_directed (
@@ -1680,6 +1691,96 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> ScoreUpdate for Probabilistic
1680
1691
}
1681
1692
}
1682
1693
1694
+ /// A probabilistic scorer that combines local and external information to score channels. This scorer is
1695
+ /// shadow-tracking local only scores, so that it becomes possible to cleanly merge external scores when they become
1696
+ /// available.
1697
+ ///
1698
+ /// This is useful for nodes that have a limited local view of the network and need to augment their view with scores
1699
+ /// from an external source to improve payment reliability. The external source may use something like background
1700
+ /// probing to gather a more complete view of the network. Merging reduces the likelihood of losing unique local data on
1701
+ /// particular channels.
1702
+ pub struct CombinedScorer < G : Deref < Target = NetworkGraph < L > > , L : Deref > where L :: Target : Logger {
1703
+ local_only_scorer : ProbabilisticScorer < G , L > ,
1704
+ scorer : ProbabilisticScorer < G , L > ,
1705
+ }
1706
+
1707
+ impl < G : Deref < Target = NetworkGraph < L > > + Clone , L : Deref + Clone > CombinedScorer < G , L > where L :: Target : Logger {
1708
+ /// Create a new combined scorer with the given local scorer.
1709
+ pub fn new ( local_scorer : ProbabilisticScorer < G , L > ) -> Self {
1710
+ let decay_params = local_scorer. decay_params ;
1711
+ let network_graph = local_scorer. network_graph . clone ( ) ;
1712
+ let logger = local_scorer. logger . clone ( ) ;
1713
+ let mut scorer = ProbabilisticScorer :: new ( decay_params, network_graph, logger) ;
1714
+
1715
+ scorer. channel_liquidities = local_scorer. channel_liquidities . clone ( ) ;
1716
+
1717
+ Self {
1718
+ local_only_scorer : local_scorer,
1719
+ scorer : scorer,
1720
+ }
1721
+ }
1722
+
1723
+ /// Merge external channel liquidity information into the scorer.
1724
+ pub fn merge ( & mut self , mut external_scores : ChannelLiquidities , duration_since_epoch : Duration ) {
1725
+ // Decay both sets of scores to make them comparable and mergeable.
1726
+ self . local_only_scorer . time_passed ( duration_since_epoch) ;
1727
+ external_scores. time_passed ( duration_since_epoch, self . local_only_scorer . decay_params ) ;
1728
+
1729
+ let local_scores = & self . local_only_scorer . channel_liquidities ;
1730
+
1731
+ // For each channel, merge the external liquidity information with the isolated local liquidity information.
1732
+ for ( scid, mut liquidity) in external_scores. 0 {
1733
+ if let Some ( local_liquidity) = local_scores. get ( & scid) {
1734
+ liquidity. merge ( local_liquidity) ;
1735
+ }
1736
+ self . scorer . channel_liquidities . insert ( scid, liquidity) ;
1737
+ }
1738
+ }
1739
+ }
1740
+
1741
+ impl < G : Deref < Target = NetworkGraph < L > > , L : Deref > ScoreLookUp for CombinedScorer < G , L > where L :: Target : Logger {
1742
+ type ScoreParams = ProbabilisticScoringFeeParameters ;
1743
+
1744
+ fn channel_penalty_msat (
1745
+ & self , candidate : & CandidateRouteHop , usage : ChannelUsage , score_params : & ProbabilisticScoringFeeParameters
1746
+ ) -> u64 {
1747
+ self . scorer . channel_penalty_msat ( candidate, usage, score_params)
1748
+ }
1749
+ }
1750
+
1751
+ impl < G : Deref < Target = NetworkGraph < L > > , L : Deref > ScoreUpdate for CombinedScorer < G , L > where L :: Target : Logger {
1752
+ fn payment_path_failed ( & mut self , path : & Path , short_channel_id : u64 , duration_since_epoch : Duration ) {
1753
+ self . local_only_scorer . payment_path_failed ( path, short_channel_id, duration_since_epoch) ;
1754
+ self . scorer . payment_path_failed ( path, short_channel_id, duration_since_epoch) ;
1755
+ }
1756
+
1757
+ fn payment_path_successful ( & mut self , path : & Path , duration_since_epoch : Duration ) {
1758
+ self . local_only_scorer . payment_path_successful ( path, duration_since_epoch) ;
1759
+ self . scorer . payment_path_successful ( path, duration_since_epoch) ;
1760
+ }
1761
+
1762
+ fn probe_failed ( & mut self , path : & Path , short_channel_id : u64 , duration_since_epoch : Duration ) {
1763
+ self . local_only_scorer . probe_failed ( path, short_channel_id, duration_since_epoch) ;
1764
+ self . scorer . probe_failed ( path, short_channel_id, duration_since_epoch) ;
1765
+ }
1766
+
1767
+ fn probe_successful ( & mut self , path : & Path , duration_since_epoch : Duration ) {
1768
+ self . local_only_scorer . probe_successful ( path, duration_since_epoch) ;
1769
+ self . scorer . probe_successful ( path, duration_since_epoch) ;
1770
+ }
1771
+
1772
+ fn time_passed ( & mut self , duration_since_epoch : Duration ) {
1773
+ self . local_only_scorer . time_passed ( duration_since_epoch) ;
1774
+ self . scorer . time_passed ( duration_since_epoch) ;
1775
+ }
1776
+ }
1777
+
1778
+ impl < G : Deref < Target = NetworkGraph < L > > , L : Deref > Writeable for CombinedScorer < G , L > where L :: Target : Logger {
1779
+ fn write < W : crate :: util:: ser:: Writer > ( & self , writer : & mut W ) -> Result < ( ) , crate :: io:: Error > {
1780
+ self . local_only_scorer . write ( writer)
1781
+ }
1782
+ }
1783
+
1683
1784
#[ cfg( c_bindings) ]
1684
1785
impl < G : Deref < Target = NetworkGraph < L > > , L : Deref > Score for ProbabilisticScorer < G , L >
1685
1786
where L :: Target : Logger { }
@@ -1859,6 +1960,13 @@ mod bucketed_history {
1859
1960
self . buckets [ bucket] = self . buckets [ bucket] . saturating_add ( BUCKET_FIXED_POINT_ONE ) ;
1860
1961
}
1861
1962
}
1963
+
1964
+ /// Returns the average of the buckets between the two trackers.
1965
+ pub ( crate ) fn merge ( & mut self , other : & Self ) -> ( ) {
1966
+ for ( index, bucket) in self . buckets . iter_mut ( ) . enumerate ( ) {
1967
+ * bucket = ( * bucket + other. buckets [ index] ) / 2 ;
1968
+ }
1969
+ }
1862
1970
}
1863
1971
1864
1972
impl_writeable_tlv_based ! ( HistoricalBucketRangeTracker , { ( 0 , buckets, required) } ) ;
@@ -1955,6 +2063,13 @@ mod bucketed_history {
1955
2063
-> DirectedHistoricalLiquidityTracker < & ' a mut HistoricalLiquidityTracker > {
1956
2064
DirectedHistoricalLiquidityTracker { source_less_than_target, tracker : self }
1957
2065
}
2066
+
2067
+ /// Merges the historical liquidity data from another tracker into this one.
2068
+ pub fn merge ( & mut self , other : & Self ) {
2069
+ self . min_liquidity_offset_history . merge ( & other. min_liquidity_offset_history ) ;
2070
+ self . max_liquidity_offset_history . merge ( & other. max_liquidity_offset_history ) ;
2071
+ self . recalculate_valid_point_count ( ) ;
2072
+ }
1958
2073
}
1959
2074
1960
2075
/// A set of buckets representing the history of where we've seen the minimum- and maximum-
@@ -2113,6 +2228,72 @@ mod bucketed_history {
2113
2228
Some ( ( cumulative_success_prob * ( 1024.0 * 1024.0 * 1024.0 ) ) as u64 )
2114
2229
}
2115
2230
}
2231
+
2232
+ #[ cfg( test) ]
2233
+ mod tests {
2234
+ use crate :: routing:: scoring:: ProbabilisticScoringFeeParameters ;
2235
+
2236
+ use super :: { HistoricalBucketRangeTracker , HistoricalLiquidityTracker } ;
2237
+ #[ test]
2238
+ fn historical_liquidity_bucket_merge ( ) {
2239
+ let mut bucket1 = HistoricalBucketRangeTracker :: new ( ) ;
2240
+ bucket1. track_datapoint ( 100 , 1000 ) ;
2241
+ assert_eq ! (
2242
+ bucket1. buckets,
2243
+ [
2244
+ 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 ,
2245
+ 0 , 0 , 0 , 0 , 0 , 0 , 0
2246
+ ]
2247
+ ) ;
2248
+
2249
+ let mut bucket2 = HistoricalBucketRangeTracker :: new ( ) ;
2250
+ bucket2. track_datapoint ( 0 , 1000 ) ;
2251
+ assert_eq ! (
2252
+ bucket2. buckets,
2253
+ [
2254
+ 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 ,
2255
+ 0 , 0 , 0 , 0 , 0 , 0 , 0
2256
+ ]
2257
+ ) ;
2258
+
2259
+ bucket1. merge ( & bucket2) ;
2260
+ assert_eq ! (
2261
+ bucket1. buckets,
2262
+ [
2263
+ 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 ,
2264
+ 0 , 0 , 0 , 0 , 0 , 0 , 0
2265
+ ]
2266
+ ) ;
2267
+ }
2268
+
2269
+ #[ test]
2270
+ fn historical_liquidity_tracker_merge ( ) {
2271
+ let params = ProbabilisticScoringFeeParameters :: default ( ) ;
2272
+
2273
+ let probability1: Option < u64 > ;
2274
+ let mut tracker1 = HistoricalLiquidityTracker :: new ( ) ;
2275
+ {
2276
+ let mut directed_tracker1 = tracker1. as_directed_mut ( true ) ;
2277
+ directed_tracker1. track_datapoint ( 100 , 200 , 1000 ) ;
2278
+ probability1 = directed_tracker1
2279
+ . calculate_success_probability_times_billion ( & params, 500 , 1000 ) ;
2280
+ }
2281
+
2282
+ let mut tracker2 = HistoricalLiquidityTracker :: new ( ) ;
2283
+ {
2284
+ let mut directed_tracker2 = tracker2. as_directed_mut ( true ) ;
2285
+ directed_tracker2. track_datapoint ( 200 , 300 , 1000 ) ;
2286
+ }
2287
+
2288
+ tracker1. merge ( & tracker2) ;
2289
+
2290
+ let directed_tracker1 = tracker1. as_directed ( true ) ;
2291
+ let probability =
2292
+ directed_tracker1. calculate_success_probability_times_billion ( & params, 500 , 1000 ) ;
2293
+
2294
+ assert_ne ! ( probability1, probability) ;
2295
+ }
2296
+ }
2116
2297
}
2117
2298
2118
2299
impl < G : Deref < Target = NetworkGraph < L > > , L : Deref > Writeable for ProbabilisticScorer < G , L > where L :: Target : Logger {
@@ -2206,15 +2387,15 @@ impl Readable for ChannelLiquidity {
2206
2387
2207
2388
#[ cfg( test) ]
2208
2389
mod tests {
2209
- use super :: { ChannelLiquidity , HistoricalLiquidityTracker , ProbabilisticScoringFeeParameters , ProbabilisticScoringDecayParameters , ProbabilisticScorer } ;
2390
+ use super :: { ChannelLiquidity , HistoricalLiquidityTracker , ProbabilisticScorer , ProbabilisticScoringDecayParameters , ProbabilisticScoringFeeParameters } ;
2210
2391
use crate :: blinded_path:: BlindedHop ;
2211
2392
use crate :: util:: config:: UserConfig ;
2212
2393
2213
2394
use crate :: ln:: channelmanager;
2214
2395
use crate :: ln:: msgs:: { ChannelAnnouncement , ChannelUpdate , UnsignedChannelAnnouncement , UnsignedChannelUpdate } ;
2215
2396
use crate :: routing:: gossip:: { EffectiveCapacity , NetworkGraph , NodeId } ;
2216
2397
use crate :: routing:: router:: { BlindedTail , Path , RouteHop , CandidateRouteHop , PublicHopCandidate } ;
2217
- use crate :: routing:: scoring:: { ChannelUsage , ScoreLookUp , ScoreUpdate } ;
2398
+ use crate :: routing:: scoring:: { ChannelLiquidities , ChannelUsage , CombinedScorer , ScoreLookUp , ScoreUpdate } ;
2218
2399
use crate :: util:: ser:: { ReadableArgs , Writeable } ;
2219
2400
use crate :: util:: test_utils:: { self , TestLogger } ;
2220
2401
@@ -2224,6 +2405,7 @@ mod tests {
2224
2405
use bitcoin:: network:: Network ;
2225
2406
use bitcoin:: secp256k1:: { PublicKey , Secp256k1 , SecretKey } ;
2226
2407
use core:: time:: Duration ;
2408
+ use std:: rc:: Rc ;
2227
2409
use crate :: io;
2228
2410
2229
2411
fn source_privkey ( ) -> SecretKey {
@@ -3715,6 +3897,68 @@ mod tests {
3715
3897
assert_eq ! ( scorer. historical_estimated_payment_success_probability( 42 , & target, amount_msat, & params, false ) ,
3716
3898
Some ( 0.0 ) ) ;
3717
3899
}
3900
+
3901
+ #[ test]
3902
+ fn combined_scorer ( ) {
3903
+ let logger = TestLogger :: new ( ) ;
3904
+ let network_graph = network_graph ( & logger) ;
3905
+ let params = ProbabilisticScoringFeeParameters :: default ( ) ;
3906
+ let mut scorer = ProbabilisticScorer :: new (
3907
+ ProbabilisticScoringDecayParameters :: default ( ) ,
3908
+ & network_graph,
3909
+ & logger,
3910
+ ) ;
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 =
3917
+ combined_scorer. scorer . estimated_channel_liquidity_range ( 42 , & target_node_id ( ) ) ;
3918
+ assert_eq ! ( liquidity_range. unwrap( ) , ( 0 , 600 ) ) ;
3919
+
3920
+ let source = source_node_id ( ) ;
3921
+ let usage = ChannelUsage {
3922
+ amount_msat : 750 ,
3923
+ inflight_htlc_msat : 0 ,
3924
+ effective_capacity : EffectiveCapacity :: Total {
3925
+ capacity_msat : 1_000 ,
3926
+ htlc_maximum_msat : 1_000 ,
3927
+ } ,
3928
+ } ;
3929
+
3930
+ {
3931
+ let network_graph = network_graph. read_only ( ) ;
3932
+ let channel = network_graph. channel ( 42 ) . unwrap ( ) ;
3933
+ let ( info, _) = channel. as_directed_from ( & source) . unwrap ( ) ;
3934
+ let candidate =
3935
+ CandidateRouteHop :: PublicHop ( PublicHopCandidate { info, short_channel_id : 42 } ) ;
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
3942
+ . as_directed_mut ( & source_node_id ( ) , & target_node_id ( ) , 1_000 )
3943
+ . successful ( 1000 , Duration :: ZERO , format_args ! ( "test channel" ) , logger_rc. as_ref ( ) ) ;
3944
+
3945
+ let mut external_scores = ChannelLiquidities :: new ( ) ;
3946
+
3947
+ external_scores. insert ( 42 , external_liquidity) ;
3948
+ combined_scorer. merge ( external_scores, Duration :: ZERO ) ;
3949
+
3950
+ let penalty_after_merge =
3951
+ combined_scorer. channel_penalty_msat ( & candidate, usage, & params) ;
3952
+
3953
+ // Since the external source observed a successful payment, the penalty should be lower after the merge.
3954
+ assert ! ( penalty_after_merge < penalty) ;
3955
+ }
3956
+
3957
+ // Verify that after the merge with a successful payment, the liquidity range is increased.
3958
+ let liquidity_range =
3959
+ combined_scorer. scorer . estimated_channel_liquidity_range ( 42 , & target_node_id ( ) ) ;
3960
+ assert_eq ! ( liquidity_range. unwrap( ) , ( 0 , 300 ) ) ;
3961
+ }
3718
3962
}
3719
3963
3720
3964
#[ cfg( ldk_bench) ]
0 commit comments