Skip to content

Commit a50ac4e

Browse files
committed
Use Duration based time info in scoring rather than Time
In the coming commits, the `T: Time` bound on `ProbabilisticScorer` will be removed. In order to enable that, we need to switch over to using the `ScoreUpdate`-provided current time (as a `Duration` since the unix epoch), making the `T` bound entirely unused.
1 parent d327c6c commit a50ac4e

File tree

1 file changed

+61
-83
lines changed

1 file changed

+61
-83
lines changed

lightning/src/routing/scoring.rs

Lines changed: 61 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,8 @@ where L::Target: Logger {
493493
decay_params: ProbabilisticScoringDecayParameters,
494494
network_graph: G,
495495
logger: L,
496-
channel_liquidities: HashMap<u64, ChannelLiquidity<T>>,
496+
channel_liquidities: HashMap<u64, ChannelLiquidity>,
497+
_unused_time: core::marker::PhantomData<T>,
497498
}
498499

499500
/// Parameters for configuring [`ProbabilisticScorer`].
@@ -797,7 +798,7 @@ impl ProbabilisticScoringDecayParameters {
797798
/// Direction is defined in terms of [`NodeId`] partial ordering, where the source node is the
798799
/// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
799800
/// offset fields gives the opposite direction.
800-
struct ChannelLiquidity<T: Time> {
801+
struct ChannelLiquidity {
801802
/// Lower channel liquidity bound in terms of an offset from zero.
802803
min_liquidity_offset_msat: u64,
803804

@@ -807,23 +808,23 @@ struct ChannelLiquidity<T: Time> {
807808
min_liquidity_offset_history: HistoricalBucketRangeTracker,
808809
max_liquidity_offset_history: HistoricalBucketRangeTracker,
809810

810-
/// Time when the liquidity bounds were last modified.
811-
last_updated: T,
811+
/// Time when the liquidity bounds were last modified as an offset since the unix epoch.
812+
last_updated: Duration,
812813

813-
/// Time when the historical liquidity bounds were last modified.
814-
offset_history_last_updated: T,
814+
/// Time when the historical liquidity bounds were last modified as an offset against the unix
815+
/// epoch.
816+
offset_history_last_updated: Duration,
815817
}
816818

817819
/// A snapshot of [`ChannelLiquidity`] in one direction assuming a certain channel capacity and
818820
/// decayed with a given half life.
819-
struct DirectedChannelLiquidity<L: Deref<Target = u64>, BRT: Deref<Target = HistoricalBucketRangeTracker>, T: Time, U: Deref<Target = T>> {
821+
struct DirectedChannelLiquidity<L: Deref<Target = u64>, BRT: Deref<Target = HistoricalBucketRangeTracker>, T: Deref<Target = Duration>> {
820822
min_liquidity_offset_msat: L,
821823
max_liquidity_offset_msat: L,
822824
liquidity_history: HistoricalMinMaxBuckets<BRT>,
823825
capacity_msat: u64,
824-
last_updated: U,
825-
offset_history_last_updated: U,
826-
now: T,
826+
last_updated: T,
827+
offset_history_last_updated: T,
827828
decay_params: ProbabilisticScoringDecayParameters,
828829
}
829830

@@ -836,11 +837,12 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, T: Time> ProbabilisticScorerU
836837
network_graph,
837838
logger,
838839
channel_liquidities: HashMap::new(),
840+
_unused_time: core::marker::PhantomData,
839841
}
840842
}
841843

842844
#[cfg(test)]
843-
fn with_channel(mut self, short_channel_id: u64, liquidity: ChannelLiquidity<T>) -> Self {
845+
fn with_channel(mut self, short_channel_id: u64, liquidity: ChannelLiquidity) -> Self {
844846
assert!(self.channel_liquidities.insert(short_channel_id, liquidity).is_none());
845847
self
846848
}
@@ -993,24 +995,23 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, T: Time> ProbabilisticScorerU
993995
}
994996
}
995997

996-
impl<T: Time> ChannelLiquidity<T> {
997-
#[inline]
998-
fn new() -> Self {
998+
impl ChannelLiquidity {
999+
fn new(last_updated: Duration) -> Self {
9991000
Self {
10001001
min_liquidity_offset_msat: 0,
10011002
max_liquidity_offset_msat: 0,
10021003
min_liquidity_offset_history: HistoricalBucketRangeTracker::new(),
10031004
max_liquidity_offset_history: HistoricalBucketRangeTracker::new(),
1004-
last_updated: T::now(),
1005-
offset_history_last_updated: T::now(),
1005+
last_updated,
1006+
offset_history_last_updated: last_updated,
10061007
}
10071008
}
10081009

10091010
/// Returns a view of the channel liquidity directed from `source` to `target` assuming
10101011
/// `capacity_msat`.
10111012
fn as_directed(
10121013
&self, source: &NodeId, target: &NodeId, capacity_msat: u64, decay_params: ProbabilisticScoringDecayParameters
1013-
) -> DirectedChannelLiquidity<&u64, &HistoricalBucketRangeTracker, T, &T> {
1014+
) -> DirectedChannelLiquidity<&u64, &HistoricalBucketRangeTracker, &Duration> {
10141015
let (min_liquidity_offset_msat, max_liquidity_offset_msat, min_liquidity_offset_history, max_liquidity_offset_history) =
10151016
if source < target {
10161017
(&self.min_liquidity_offset_msat, &self.max_liquidity_offset_msat,
@@ -1030,7 +1031,6 @@ impl<T: Time> ChannelLiquidity<T> {
10301031
capacity_msat,
10311032
last_updated: &self.last_updated,
10321033
offset_history_last_updated: &self.offset_history_last_updated,
1033-
now: T::now(),
10341034
decay_params: decay_params,
10351035
}
10361036
}
@@ -1039,7 +1039,7 @@ impl<T: Time> ChannelLiquidity<T> {
10391039
/// `capacity_msat`.
10401040
fn as_directed_mut(
10411041
&mut self, source: &NodeId, target: &NodeId, capacity_msat: u64, decay_params: ProbabilisticScoringDecayParameters
1042-
) -> DirectedChannelLiquidity<&mut u64, &mut HistoricalBucketRangeTracker, T, &mut T> {
1042+
) -> DirectedChannelLiquidity<&mut u64, &mut HistoricalBucketRangeTracker, &mut Duration> {
10431043
let (min_liquidity_offset_msat, max_liquidity_offset_msat, min_liquidity_offset_history, max_liquidity_offset_history) =
10441044
if source < target {
10451045
(&mut self.min_liquidity_offset_msat, &mut self.max_liquidity_offset_msat,
@@ -1059,7 +1059,6 @@ impl<T: Time> ChannelLiquidity<T> {
10591059
capacity_msat,
10601060
last_updated: &mut self.last_updated,
10611061
offset_history_last_updated: &mut self.offset_history_last_updated,
1062-
now: T::now(),
10631062
decay_params: decay_params,
10641063
}
10651064
}
@@ -1070,7 +1069,7 @@ impl<T: Time> ChannelLiquidity<T> {
10701069
) -> u64 {
10711070
let half_life = decay_params.liquidity_offset_half_life.as_secs_f64();
10721071
if half_life != 0.0 {
1073-
let elapsed_time = T::now().duration_since(self.last_updated).as_secs_f64();
1072+
let elapsed_time = duration_since_epoch.saturating_sub(self.last_updated).as_secs_f64();
10741073
((offset as f64) * powf64(0.5, elapsed_time / half_life)) as u64
10751074
} else {
10761075
0
@@ -1159,7 +1158,8 @@ fn success_probability(
11591158
(numerator, denominator)
11601159
}
11611160

1162-
impl<L: Deref<Target = u64>, BRT: Deref<Target = HistoricalBucketRangeTracker>, T: Time, U: Deref<Target = T>> DirectedChannelLiquidity< L, BRT, T, U> {
1161+
impl<L: Deref<Target = u64>, BRT: Deref<Target = HistoricalBucketRangeTracker>, T: Deref<Target = Duration>>
1162+
DirectedChannelLiquidity< L, BRT, T> {
11631163
/// Returns a liquidity penalty for routing the given HTLC `amount_msat` through the channel in
11641164
/// this direction.
11651165
fn penalty_msat(&self, amount_msat: u64, score_params: &ProbabilisticScoringFeeParameters) -> u64 {
@@ -1267,7 +1267,8 @@ impl<L: Deref<Target = u64>, BRT: Deref<Target = HistoricalBucketRangeTracker>,
12671267
}
12681268
}
12691269

1270-
impl<L: DerefMut<Target = u64>, BRT: DerefMut<Target = HistoricalBucketRangeTracker>, T: Time, U: DerefMut<Target = T>> DirectedChannelLiquidity<L, BRT, T, U> {
1270+
impl<L: DerefMut<Target = u64>, BRT: DerefMut<Target = HistoricalBucketRangeTracker>, T: DerefMut<Target = Duration>>
1271+
DirectedChannelLiquidity<L, BRT, T> {
12711272
/// Adjusts the channel liquidity balance bounds when failing to route `amount_msat`.
12721273
fn failed_at_channel<Log: Deref>(
12731274
&mut self, amount_msat: u64, duration_since_epoch: Duration, chan_descr: fmt::Arguments, logger: &Log
@@ -1313,7 +1314,9 @@ impl<L: DerefMut<Target = u64>, BRT: DerefMut<Target = HistoricalBucketRangeTrac
13131314
/// state"), we allow the caller to set an offset applied to our liquidity bounds which
13141315
/// represents the amount of the successful payment we just made.
13151316
fn update_history_buckets(&mut self, bucket_offset_msat: u64, duration_since_epoch: Duration) {
1316-
let half_lives = self.now.duration_since(*self.offset_history_last_updated).as_secs()
1317+
let half_lives =
1318+
duration_since_epoch.checked_sub(*self.offset_history_last_updated)
1319+
.unwrap_or(Duration::ZERO).as_secs()
13171320
.checked_div(self.decay_params.historical_no_updates_half_life.as_secs())
13181321
.map(|v| v.try_into().unwrap_or(u32::max_value())).unwrap_or(u32::max_value());
13191322
self.liquidity_history.min_liquidity_offset_history.time_decay_data(half_lives);
@@ -1327,29 +1330,25 @@ impl<L: DerefMut<Target = u64>, BRT: DerefMut<Target = HistoricalBucketRangeTrac
13271330
self.liquidity_history.max_liquidity_offset_history.track_datapoint(
13281331
max_liquidity_offset_msat.saturating_sub(bucket_offset_msat), self.capacity_msat
13291332
);
1330-
*self.offset_history_last_updated = self.now;
1333+
*self.offset_history_last_updated = duration_since_epoch;
13311334
}
13321335

13331336
/// Adjusts the lower bound of the channel liquidity balance in this direction.
13341337
fn set_min_liquidity_msat(&mut self, amount_msat: u64, duration_since_epoch: Duration) {
13351338
*self.min_liquidity_offset_msat = amount_msat;
1336-
*self.max_liquidity_offset_msat = if amount_msat > self.max_liquidity_msat() {
1337-
0
1338-
} else {
1339-
self.decayed_offset_msat(*self.max_liquidity_offset_msat)
1340-
};
1341-
*self.last_updated = self.now;
1339+
if amount_msat > self.max_liquidity_msat() {
1340+
*self.max_liquidity_offset_msat = 0;
1341+
}
1342+
*self.last_updated = duration_since_epoch;
13421343
}
13431344

13441345
/// Adjusts the upper bound of the channel liquidity balance in this direction.
13451346
fn set_max_liquidity_msat(&mut self, amount_msat: u64, duration_since_epoch: Duration) {
13461347
*self.max_liquidity_offset_msat = self.capacity_msat.checked_sub(amount_msat).unwrap_or(0);
1347-
*self.min_liquidity_offset_msat = if amount_msat < self.min_liquidity_msat() {
1348-
0
1349-
} else {
1350-
self.decayed_offset_msat(*self.min_liquidity_offset_msat)
1351-
};
1352-
*self.last_updated = self.now;
1348+
if amount_msat < *self.min_liquidity_offset_msat {
1349+
*self.min_liquidity_offset_msat = 0;
1350+
}
1351+
*self.last_updated = duration_since_epoch;
13531352
}
13541353
}
13551354

@@ -1396,7 +1395,7 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, T: Time> ScoreLookUp for Prob
13961395
let capacity_msat = usage.effective_capacity.as_msat();
13971396
self.channel_liquidities
13981397
.get(&scid)
1399-
.unwrap_or(&ChannelLiquidity::new())
1398+
.unwrap_or(&ChannelLiquidity::new(Duration::ZERO))
14001399
.as_directed(&source, &target, capacity_msat, self.decay_params)
14011400
.penalty_msat(amount_msat, score_params)
14021401
.saturating_add(anti_probing_penalty_msat)
@@ -1426,14 +1425,14 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, T: Time> ScoreUpdate for Prob
14261425
if at_failed_channel {
14271426
self.channel_liquidities
14281427
.entry(hop.short_channel_id)
1429-
.or_insert_with(ChannelLiquidity::new)
1428+
.or_insert_with(|| ChannelLiquidity::new(duration_since_epoch))
14301429
.as_directed_mut(source, &target, capacity_msat, self.decay_params)
14311430
.failed_at_channel(amount_msat, duration_since_epoch,
14321431
format_args!("SCID {}, towards {:?}", hop.short_channel_id, target), &self.logger);
14331432
} else {
14341433
self.channel_liquidities
14351434
.entry(hop.short_channel_id)
1436-
.or_insert_with(ChannelLiquidity::new)
1435+
.or_insert_with(|| ChannelLiquidity::new(duration_since_epoch))
14371436
.as_directed_mut(source, &target, capacity_msat, self.decay_params)
14381437
.failed_downstream(amount_msat, duration_since_epoch,
14391438
format_args!("SCID {}, towards {:?}", hop.short_channel_id, target), &self.logger);
@@ -1462,7 +1461,7 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, T: Time> ScoreUpdate for Prob
14621461
let capacity_msat = channel.effective_capacity().as_msat();
14631462
self.channel_liquidities
14641463
.entry(hop.short_channel_id)
1465-
.or_insert_with(ChannelLiquidity::new)
1464+
.or_insert_with(|| ChannelLiquidity::new(duration_since_epoch))
14661465
.as_directed_mut(source, &target, capacity_msat, self.decay_params)
14671466
.successful(amount_msat, duration_since_epoch,
14681467
format_args!("SCID {}, towards {:?}", hop.short_channel_id, target), &self.logger);
@@ -1488,10 +1487,10 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, T: Time> ScoreUpdate for Prob
14881487
liquidity.decayed_offset(liquidity.min_liquidity_offset_msat, duration_since_epoch, decay_params);
14891488
liquidity.max_liquidity_offset_msat =
14901489
liquidity.decayed_offset(liquidity.max_liquidity_offset_msat, duration_since_epoch, decay_params);
1491-
liquidity.last_updated = T::now();
1490+
liquidity.last_updated = duration_since_epoch;
14921491

14931492
let elapsed_time =
1494-
T::now().duration_since(liquidity.offset_history_last_updated);
1493+
duration_since_epoch.saturating_sub(liquidity.offset_history_last_updated);
14951494
if elapsed_time > decay_params.historical_no_updates_half_life {
14961495
let half_life = decay_params.historical_no_updates_half_life.as_secs_f64();
14971496
if half_life != 0.0 {
@@ -1502,7 +1501,7 @@ impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, T: Time> ScoreUpdate for Prob
15021501
for bucket in liquidity.max_liquidity_offset_history.buckets.iter_mut() {
15031502
*bucket = ((*bucket as u64) * 1024 / divisor) as u16;
15041503
}
1505-
liquidity.offset_history_last_updated = T::now();
1504+
liquidity.offset_history_last_updated = duration_since_epoch;
15061505
}
15071506
}
15081507
liquidity.min_liquidity_offset_msat != 0 || liquidity.max_liquidity_offset_msat != 0 ||
@@ -2125,31 +2124,29 @@ ReadableArgs<(ProbabilisticScoringDecayParameters, G, L)> for ProbabilisticScore
21252124
network_graph,
21262125
logger,
21272126
channel_liquidities,
2127+
_unused_time: core::marker::PhantomData,
21282128
})
21292129
}
21302130
}
21312131

2132-
impl<T: Time> Writeable for ChannelLiquidity<T> {
2132+
impl Writeable for ChannelLiquidity {
21332133
#[inline]
21342134
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
2135-
let offset_history_duration_since_epoch =
2136-
T::duration_since_epoch() - self.offset_history_last_updated.elapsed();
2137-
let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
21382135
write_tlv_fields!(w, {
21392136
(0, self.min_liquidity_offset_msat, required),
21402137
// 1 was the min_liquidity_offset_history in octile form
21412138
(2, self.max_liquidity_offset_msat, required),
21422139
// 3 was the max_liquidity_offset_history in octile form
2143-
(4, duration_since_epoch, required),
2140+
(4, self.last_updated, required),
21442141
(5, Some(self.min_liquidity_offset_history), option),
21452142
(7, Some(self.max_liquidity_offset_history), option),
2146-
(9, offset_history_duration_since_epoch, required),
2143+
(9, self.offset_history_last_updated, required),
21472144
});
21482145
Ok(())
21492146
}
21502147
}
21512148

2152-
impl<T: Time> Readable for ChannelLiquidity<T> {
2149+
impl Readable for ChannelLiquidity {
21532150
#[inline]
21542151
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
21552152
let mut min_liquidity_offset_msat = 0;
@@ -2158,36 +2155,18 @@ impl<T: Time> Readable for ChannelLiquidity<T> {
21582155
let mut legacy_max_liq_offset_history: Option<LegacyHistoricalBucketRangeTracker> = None;
21592156
let mut min_liquidity_offset_history: Option<HistoricalBucketRangeTracker> = None;
21602157
let mut max_liquidity_offset_history: Option<HistoricalBucketRangeTracker> = None;
2161-
let mut duration_since_epoch = Duration::from_secs(0);
2162-
let mut offset_history_duration_since_epoch = None;
2158+
let mut last_updated = Duration::from_secs(0);
2159+
let mut offset_history_last_updated = None;
21632160
read_tlv_fields!(r, {
21642161
(0, min_liquidity_offset_msat, required),
21652162
(1, legacy_min_liq_offset_history, option),
21662163
(2, max_liquidity_offset_msat, required),
21672164
(3, legacy_max_liq_offset_history, option),
2168-
(4, duration_since_epoch, required),
2165+
(4, last_updated, required),
21692166
(5, min_liquidity_offset_history, option),
21702167
(7, max_liquidity_offset_history, option),
2171-
(9, offset_history_duration_since_epoch, option),
2168+
(9, offset_history_last_updated, option),
21722169
});
2173-
// On rust prior to 1.60 `Instant::duration_since` will panic if time goes backwards.
2174-
// We write `last_updated` as wallclock time even though its ultimately an `Instant` (which
2175-
// is a time from a monotonic clock usually represented as an offset against boot time).
2176-
// Thus, we have to construct an `Instant` by subtracting the difference in wallclock time
2177-
// from the one that was written. However, because `Instant` can panic if we construct one
2178-
// in the future, we must handle wallclock time jumping backwards, which we do by simply
2179-
// using `Instant::now()` in that case.
2180-
let wall_clock_now = T::duration_since_epoch();
2181-
let now = T::now();
2182-
let last_updated = if wall_clock_now > duration_since_epoch {
2183-
now - (wall_clock_now - duration_since_epoch)
2184-
} else { now };
2185-
2186-
let offset_history_duration_since_epoch =
2187-
offset_history_duration_since_epoch.unwrap_or(duration_since_epoch);
2188-
let offset_history_last_updated = if wall_clock_now > offset_history_duration_since_epoch {
2189-
now - (wall_clock_now - offset_history_duration_since_epoch)
2190-
} else { now };
21912170

21922171
if min_liquidity_offset_history.is_none() {
21932172
if let Some(legacy_buckets) = legacy_min_liq_offset_history {
@@ -2209,7 +2188,7 @@ impl<T: Time> Readable for ChannelLiquidity<T> {
22092188
min_liquidity_offset_history: min_liquidity_offset_history.unwrap(),
22102189
max_liquidity_offset_history: max_liquidity_offset_history.unwrap(),
22112190
last_updated,
2212-
offset_history_last_updated,
2191+
offset_history_last_updated: offset_history_last_updated.unwrap_or(last_updated),
22132192
})
22142193
}
22152194
}
@@ -2219,7 +2198,6 @@ mod tests {
22192198
use super::{ChannelLiquidity, HistoricalBucketRangeTracker, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters, ProbabilisticScorerUsingTime};
22202199
use crate::blinded_path::{BlindedHop, BlindedPath};
22212200
use crate::util::config::UserConfig;
2222-
use crate::util::time::Time;
22232201
use crate::util::time::tests::SinceEpoch;
22242202

22252203
use crate::ln::channelmanager;
@@ -2384,8 +2362,8 @@ mod tests {
23842362
#[test]
23852363
fn liquidity_bounds_directed_from_lowest_node_id() {
23862364
let logger = TestLogger::new();
2387-
let last_updated = SinceEpoch::now();
2388-
let offset_history_last_updated = SinceEpoch::now();
2365+
let last_updated = Duration::ZERO;
2366+
let offset_history_last_updated = Duration::ZERO;
23892367
let network_graph = network_graph(&logger);
23902368
let decay_params = ProbabilisticScoringDecayParameters::default();
23912369
let mut scorer = ProbabilisticScorer::new(decay_params, &network_graph, &logger)
@@ -2465,8 +2443,8 @@ mod tests {
24652443
#[test]
24662444
fn resets_liquidity_upper_bound_when_crossed_by_lower_bound() {
24672445
let logger = TestLogger::new();
2468-
let last_updated = SinceEpoch::now();
2469-
let offset_history_last_updated = SinceEpoch::now();
2446+
let last_updated = Duration::ZERO;
2447+
let offset_history_last_updated = Duration::ZERO;
24702448
let network_graph = network_graph(&logger);
24712449
let decay_params = ProbabilisticScoringDecayParameters::default();
24722450
let mut scorer = ProbabilisticScorer::new(decay_params, &network_graph, &logger)
@@ -2526,8 +2504,8 @@ mod tests {
25262504
#[test]
25272505
fn resets_liquidity_lower_bound_when_crossed_by_upper_bound() {
25282506
let logger = TestLogger::new();
2529-
let last_updated = SinceEpoch::now();
2530-
let offset_history_last_updated = SinceEpoch::now();
2507+
let last_updated = Duration::ZERO;
2508+
let offset_history_last_updated = Duration::ZERO;
25312509
let network_graph = network_graph(&logger);
25322510
let decay_params = ProbabilisticScoringDecayParameters::default();
25332511
let mut scorer = ProbabilisticScorer::new(decay_params, &network_graph, &logger)
@@ -2639,8 +2617,8 @@ mod tests {
26392617
#[test]
26402618
fn constant_penalty_outside_liquidity_bounds() {
26412619
let logger = TestLogger::new();
2642-
let last_updated = SinceEpoch::now();
2643-
let offset_history_last_updated = SinceEpoch::now();
2620+
let last_updated = Duration::ZERO;
2621+
let offset_history_last_updated = Duration::ZERO;
26442622
let network_graph = network_graph(&logger);
26452623
let params = ProbabilisticScoringFeeParameters {
26462624
liquidity_penalty_multiplier_msat: 1_000,

0 commit comments

Comments
 (0)