9f3b7806a991681259deb4ae8655cc060a730382
[rust-lightning] / lightning / src / routing / scoring.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Utilities for scoring payment channels.
11 //!
12 //! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path
13 //! finding when a custom [`Score`] implementation is not needed.
14 //!
15 //! # Example
16 //!
17 //! ```
18 //! # extern crate secp256k1;
19 //! #
20 //! # use lightning::routing::network_graph::NetworkGraph;
21 //! # use lightning::routing::router::{RouteParameters, find_route};
22 //! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters, Scorer, ScoringParameters};
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use secp256k1::key::PublicKey;
25 //! #
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! #     fn log(&self, record: &Record) { unimplemented!() }
29 //! # }
30 //! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph) {
31 //! # let logger = FakeLogger {};
32 //! #
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringParameters::default();
35 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
36 //!
37 //! // Or use custom channel penalties.
38 //! let params = ProbabilisticScoringParameters {
39 //!     liquidity_penalty_multiplier_msat: 2 * 1000,
40 //!     ..ProbabilisticScoringParameters::default()
41 //! };
42 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
43 //!
44 //! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer);
45 //! # }
46 //! ```
47 //!
48 //! # Note
49 //!
50 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
51 //! different types and thus is undefined.
52 //!
53 //! [`find_route`]: crate::routing::router::find_route
54
55 use ln::msgs::DecodeError;
56 use routing::network_graph::{NetworkGraph, NodeId};
57 use routing::router::RouteHop;
58 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
59
60 use prelude::*;
61 use core::cell::{RefCell, RefMut};
62 use core::ops::{Deref, DerefMut};
63 use core::time::Duration;
64 use io::{self, Read};
65 use sync::{Mutex, MutexGuard};
66
67 /// We define Score ever-so-slightly differently based on whether we are being built for C bindings
68 /// or not. For users, `LockableScore` must somehow be writeable to disk. For Rust users, this is
69 /// no problem - you move a `Score` that implements `Writeable` into a `Mutex`, lock it, and now
70 /// you have the original, concrete, `Score` type, which presumably implements `Writeable`.
71 ///
72 /// For C users, once you've moved the `Score` into a `LockableScore` all you have after locking it
73 /// is an opaque trait object with an opaque pointer with no type info. Users could take the unsafe
74 /// approach of blindly casting that opaque pointer to a concrete type and calling `Writeable` from
75 /// there, but other languages downstream of the C bindings (e.g. Java) can't even do that.
76 /// Instead, we really want `Score` and `LockableScore` to implement `Writeable` directly, which we
77 /// do here by defining `Score` differently for `cfg(c_bindings)`.
78 macro_rules! define_score { ($($supertrait: path)*) => {
79 /// An interface used to score payment channels for path finding.
80 ///
81 ///     Scoring is in terms of fees willing to be paid in order to avoid routing through a channel.
82 pub trait Score $(: $supertrait)* {
83         /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
84         /// given channel in the direction from `source` to `target`.
85         ///
86         /// The channel's capacity (less any other MPP parts that are also being considered for use in
87         /// the same payment) is given by `capacity_msat`. It may be determined from various sources
88         /// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near
89         /// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount.
90         /// Thus, implementations should be overflow-safe.
91         fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, source: &NodeId, target: &NodeId) -> u64;
92
93         /// Handles updating channel penalties after failing to route through a channel.
94         fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64);
95
96         /// Handles updating channel penalties after successfully routing along a path.
97         fn payment_path_successful(&mut self, path: &[&RouteHop]);
98 }
99
100 impl<S: Score, T: DerefMut<Target=S> $(+ $supertrait)*> Score for T {
101         fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, source: &NodeId, target: &NodeId) -> u64 {
102                 self.deref().channel_penalty_msat(short_channel_id, send_amt_msat, capacity_msat, source, target)
103         }
104
105         fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
106                 self.deref_mut().payment_path_failed(path, short_channel_id)
107         }
108
109         fn payment_path_successful(&mut self, path: &[&RouteHop]) {
110                 self.deref_mut().payment_path_successful(path)
111         }
112 }
113 } }
114
115 #[cfg(c_bindings)]
116 define_score!(Writeable);
117 #[cfg(not(c_bindings))]
118 define_score!();
119
120 /// A scorer that is accessed under a lock.
121 ///
122 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
123 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
124 /// implementations. Internal locking would be detrimental to route finding performance and could
125 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
126 ///
127 /// [`find_route`]: crate::routing::router::find_route
128 pub trait LockableScore<'a> {
129         /// The locked [`Score`] type.
130         type Locked: 'a + Score;
131
132         /// Returns the locked scorer.
133         fn lock(&'a self) -> Self::Locked;
134 }
135
136 /// (C-not exported)
137 impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
138         type Locked = MutexGuard<'a, T>;
139
140         fn lock(&'a self) -> MutexGuard<'a, T> {
141                 Mutex::lock(self).unwrap()
142         }
143 }
144
145 impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
146         type Locked = RefMut<'a, T>;
147
148         fn lock(&'a self) -> RefMut<'a, T> {
149                 self.borrow_mut()
150         }
151 }
152
153 #[cfg(c_bindings)]
154 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
155 pub struct MultiThreadedLockableScore<S: Score> {
156         score: Mutex<S>,
157 }
158 #[cfg(c_bindings)]
159 /// (C-not exported)
160 impl<'a, T: Score + 'a> LockableScore<'a> for MultiThreadedLockableScore<T> {
161         type Locked = MutexGuard<'a, T>;
162
163         fn lock(&'a self) -> MutexGuard<'a, T> {
164                 Mutex::lock(&self.score).unwrap()
165         }
166 }
167
168 #[cfg(c_bindings)]
169 impl<T: Score> MultiThreadedLockableScore<T> {
170         /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
171         pub fn new(score: T) -> Self {
172                 MultiThreadedLockableScore { score: Mutex::new(score) }
173         }
174 }
175
176 #[cfg(c_bindings)]
177 /// (C-not exported)
178 impl<'a, T: Writeable> Writeable for RefMut<'a, T> {
179         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
180                 T::write(&**self, writer)
181         }
182 }
183
184 #[cfg(c_bindings)]
185 /// (C-not exported)
186 impl<'a, S: Writeable> Writeable for MutexGuard<'a, S> {
187         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
188                 S::write(&**self, writer)
189         }
190 }
191
192 /// [`Score`] implementation that provides reasonable default behavior.
193 ///
194 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
195 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
196 ///
197 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
198 ///
199 /// # Note
200 ///
201 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
202 /// behavior.
203 ///
204 /// [module-level documentation]: crate::routing::scoring
205 pub type Scorer = ScorerUsingTime::<ConfiguredTime>;
206
207 #[cfg(not(feature = "no-std"))]
208 type ConfiguredTime = std::time::Instant;
209 #[cfg(feature = "no-std")]
210 type ConfiguredTime = time::Eternity;
211
212 // Note that ideally we'd hide ScorerUsingTime from public view by sealing it as well, but rustdoc
213 // doesn't handle this well - instead exposing a `Scorer` which has no trait implementation(s) or
214 // methods at all.
215
216 /// [`Score`] implementation.
217 ///
218 /// (C-not exported) generally all users should use the [`Scorer`] type alias.
219 #[doc(hidden)]
220 pub struct ScorerUsingTime<T: Time> {
221         params: ScoringParameters,
222         // TODO: Remove entries of closed channels.
223         channel_failures: HashMap<u64, ChannelFailure<T>>,
224 }
225
226 /// Parameters for configuring [`Scorer`].
227 pub struct ScoringParameters {
228         /// A fixed penalty in msats to apply to each channel.
229         ///
230         /// Default value: 500 msat
231         pub base_penalty_msat: u64,
232
233         /// A penalty in msats to apply to a channel upon failing to relay a payment.
234         ///
235         /// This accumulates for each failure but may be reduced over time based on
236         /// [`failure_penalty_half_life`] or when successfully routing through a channel.
237         ///
238         /// Default value: 1,024,000 msat
239         ///
240         /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
241         pub failure_penalty_msat: u64,
242
243         /// When the amount being sent over a channel is this many 1024ths of the total channel
244         /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
245         ///
246         /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
247         ///
248         /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
249         pub overuse_penalty_start_1024th: u16,
250
251         /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
252         /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
253         ///
254         /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
255         ///                to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
256         ///
257         /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
258         pub overuse_penalty_msat_per_1024th: u64,
259
260         /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
261         /// cut in half.
262         ///
263         /// Successfully routing through a channel will immediately cut the penalty in half as well.
264         ///
265         /// Default value: 1 hour
266         ///
267         /// # Note
268         ///
269         /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
270         /// never decay.
271         ///
272         /// [`failure_penalty_msat`]: Self::failure_penalty_msat
273         pub failure_penalty_half_life: Duration,
274 }
275
276 impl_writeable_tlv_based!(ScoringParameters, {
277         (0, base_penalty_msat, required),
278         (1, overuse_penalty_start_1024th, (default_value, 128)),
279         (2, failure_penalty_msat, required),
280         (3, overuse_penalty_msat_per_1024th, (default_value, 20)),
281         (4, failure_penalty_half_life, required),
282 });
283
284 /// Accounting for penalties against a channel for failing to relay any payments.
285 ///
286 /// Penalties decay over time, though accumulate as more failures occur.
287 struct ChannelFailure<T: Time> {
288         /// Accumulated penalty in msats for the channel as of `last_updated`.
289         undecayed_penalty_msat: u64,
290
291         /// Last time the channel either failed to route or successfully routed a payment. Used to decay
292         /// `undecayed_penalty_msat`.
293         last_updated: T,
294 }
295
296 impl<T: Time> ScorerUsingTime<T> {
297         /// Creates a new scorer using the given scoring parameters.
298         pub fn new(params: ScoringParameters) -> Self {
299                 Self {
300                         params,
301                         channel_failures: HashMap::new(),
302                 }
303         }
304
305         /// Creates a new scorer using `penalty_msat` as a fixed channel penalty.
306         #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
307         pub fn with_fixed_penalty(penalty_msat: u64) -> Self {
308                 Self::new(ScoringParameters {
309                         base_penalty_msat: penalty_msat,
310                         failure_penalty_msat: 0,
311                         failure_penalty_half_life: Duration::from_secs(0),
312                         overuse_penalty_start_1024th: 1024,
313                         overuse_penalty_msat_per_1024th: 0,
314                 })
315         }
316 }
317
318 impl<T: Time> ChannelFailure<T> {
319         fn new(failure_penalty_msat: u64) -> Self {
320                 Self {
321                         undecayed_penalty_msat: failure_penalty_msat,
322                         last_updated: T::now(),
323                 }
324         }
325
326         fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
327                 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
328                 self.last_updated = T::now();
329         }
330
331         fn reduce_penalty(&mut self, half_life: Duration) {
332                 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) >> 1;
333                 self.last_updated = T::now();
334         }
335
336         fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
337                 self.last_updated.elapsed().as_secs()
338                         .checked_div(half_life.as_secs())
339                         .and_then(|decays| self.undecayed_penalty_msat.checked_shr(decays as u32))
340                         .unwrap_or(0)
341         }
342 }
343
344 impl<T: Time> Default for ScorerUsingTime<T> {
345         fn default() -> Self {
346                 Self::new(ScoringParameters::default())
347         }
348 }
349
350 impl Default for ScoringParameters {
351         fn default() -> Self {
352                 Self {
353                         base_penalty_msat: 500,
354                         failure_penalty_msat: 1024 * 1000,
355                         failure_penalty_half_life: Duration::from_secs(3600),
356                         overuse_penalty_start_1024th: 1024 / 8,
357                         overuse_penalty_msat_per_1024th: 20,
358                 }
359         }
360 }
361
362 impl<T: Time> Score for ScorerUsingTime<T> {
363         fn channel_penalty_msat(
364                 &self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, _source: &NodeId, _target: &NodeId
365         ) -> u64 {
366                 let failure_penalty_msat = self.channel_failures
367                         .get(&short_channel_id)
368                         .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
369
370                 let mut penalty_msat = self.params.base_penalty_msat + failure_penalty_msat;
371                 let send_1024ths = send_amt_msat.checked_mul(1024).unwrap_or(u64::max_value()) / capacity_msat;
372                 if send_1024ths > self.params.overuse_penalty_start_1024th as u64 {
373                         penalty_msat = penalty_msat.checked_add(
374                                         (send_1024ths - self.params.overuse_penalty_start_1024th as u64)
375                                         .checked_mul(self.params.overuse_penalty_msat_per_1024th).unwrap_or(u64::max_value()))
376                                 .unwrap_or(u64::max_value());
377                 }
378
379                 penalty_msat
380         }
381
382         fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
383                 let failure_penalty_msat = self.params.failure_penalty_msat;
384                 let half_life = self.params.failure_penalty_half_life;
385                 self.channel_failures
386                         .entry(short_channel_id)
387                         .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
388                         .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
389         }
390
391         fn payment_path_successful(&mut self, path: &[&RouteHop]) {
392                 let half_life = self.params.failure_penalty_half_life;
393                 for hop in path.iter() {
394                         self.channel_failures
395                                 .entry(hop.short_channel_id)
396                                 .and_modify(|failure| failure.reduce_penalty(half_life));
397                 }
398         }
399 }
400
401 impl<T: Time> Writeable for ScorerUsingTime<T> {
402         #[inline]
403         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
404                 self.params.write(w)?;
405                 self.channel_failures.write(w)?;
406                 write_tlv_fields!(w, {});
407                 Ok(())
408         }
409 }
410
411 impl<T: Time> Readable for ScorerUsingTime<T> {
412         #[inline]
413         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
414                 let res = Ok(Self {
415                         params: Readable::read(r)?,
416                         channel_failures: Readable::read(r)?,
417                 });
418                 read_tlv_fields!(r, {});
419                 res
420         }
421 }
422
423 impl<T: Time> Writeable for ChannelFailure<T> {
424         #[inline]
425         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
426                 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
427                 write_tlv_fields!(w, {
428                         (0, self.undecayed_penalty_msat, required),
429                         (2, duration_since_epoch, required),
430                 });
431                 Ok(())
432         }
433 }
434
435 impl<T: Time> Readable for ChannelFailure<T> {
436         #[inline]
437         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
438                 let mut undecayed_penalty_msat = 0;
439                 let mut duration_since_epoch = Duration::from_secs(0);
440                 read_tlv_fields!(r, {
441                         (0, undecayed_penalty_msat, required),
442                         (2, duration_since_epoch, required),
443                 });
444                 Ok(Self {
445                         undecayed_penalty_msat,
446                         last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
447                 })
448         }
449 }
450
451 /// [`Score`] implementation using channel success probability distributions.
452 ///
453 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
454 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
455 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
456 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
457 /// specific HTLC amount through a channel.
458 ///
459 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
460 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
461 /// [`ProbabilisticScoringParameters`] for details.
462 ///
463 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
464 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
465 /// volume are more likely to experience failed payment paths, which would need to be retried.
466 ///
467 /// # Note
468 ///
469 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
470 /// behavior.
471 ///
472 /// [1]: https://arxiv.org/abs/2107.05322
473 pub type ProbabilisticScorer<G> = ProbabilisticScorerUsingTime::<G, ConfiguredTime>;
474
475 /// Probabilistic [`Score`] implementation.
476 ///
477 /// (C-not exported) generally all users should use the [`ProbabilisticScorer`] type alias.
478 #[doc(hidden)]
479 pub struct ProbabilisticScorerUsingTime<G: Deref<Target = NetworkGraph>, T: Time> {
480         params: ProbabilisticScoringParameters,
481         network_graph: G,
482         // TODO: Remove entries of closed channels.
483         channel_liquidities: HashMap<u64, ChannelLiquidity<T>>,
484 }
485
486 /// Parameters for configuring [`ProbabilisticScorer`].
487 #[derive(Clone, Copy)]
488 pub struct ProbabilisticScoringParameters {
489         /// A multiplier used to determine the amount in msats willing to be paid to avoid routing
490         /// through a channel, as per multiplying by the negative `log10` of the channel's success
491         /// probability for a payment.
492         ///
493         /// The success probability is determined by the effective channel capacity, the payment amount,
494         /// and knowledge learned from prior successful and unsuccessful payments. The lower bound of
495         /// the success probability is 0.01, effectively limiting the penalty to the range
496         /// `0..=2*liquidity_penalty_multiplier_msat`. The knowledge learned is decayed over time based
497         /// on [`liquidity_offset_half_life`].
498         ///
499         /// Default value: 10,000 msat
500         ///
501         /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
502         pub liquidity_penalty_multiplier_msat: u64,
503
504         /// The time required to elapse before any knowledge learned about channel liquidity balances is
505         /// cut in half.
506         ///
507         /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
508         /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
509         /// the certainty of the channel liquidity balance.
510         ///
511         /// Default value: 1 hour
512         ///
513         /// # Note
514         ///
515         /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
516         /// liquidity knowledge will never decay except when the bounds cross.
517         pub liquidity_offset_half_life: Duration,
518 }
519
520 impl_writeable_tlv_based!(ProbabilisticScoringParameters, {
521         (0, liquidity_penalty_multiplier_msat, required),
522         (2, liquidity_offset_half_life, required),
523 });
524
525 /// Accounting for channel liquidity balance uncertainty.
526 ///
527 /// Direction is defined in terms of [`NodeId`] partial ordering, where the source node is the
528 /// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
529 /// offset fields gives the opposite direction.
530 struct ChannelLiquidity<T: Time> {
531         /// Lower channel liquidity bound in terms of an offset from zero.
532         min_liquidity_offset_msat: u64,
533
534         /// Upper channel liquidity bound in terms of an offset from the effective capacity.
535         max_liquidity_offset_msat: u64,
536
537         /// Time when the liquidity bounds were last modified.
538         last_updated: T,
539 }
540
541 /// A snapshot of [`ChannelLiquidity`] in one direction assuming a certain channel capacity and
542 /// decayed with a given half life.
543 struct DirectedChannelLiquidity<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> {
544         min_liquidity_offset_msat: L,
545         max_liquidity_offset_msat: L,
546         capacity_msat: u64,
547         last_updated: U,
548         now: T,
549         half_life: Duration,
550 }
551
552 impl<G: Deref<Target = NetworkGraph>, T: Time> ProbabilisticScorerUsingTime<G, T> {
553         /// Creates a new scorer using the given scoring parameters for sending payments from a node
554         /// through a network graph.
555         pub fn new(params: ProbabilisticScoringParameters, network_graph: G) -> Self {
556                 Self {
557                         params,
558                         network_graph,
559                         channel_liquidities: HashMap::new(),
560                 }
561         }
562
563         #[cfg(test)]
564         fn with_channel(mut self, short_channel_id: u64, liquidity: ChannelLiquidity<T>) -> Self {
565                 assert!(self.channel_liquidities.insert(short_channel_id, liquidity).is_none());
566                 self
567         }
568 }
569
570 impl Default for ProbabilisticScoringParameters {
571         fn default() -> Self {
572                 Self {
573                         liquidity_penalty_multiplier_msat: 10_000,
574                         liquidity_offset_half_life: Duration::from_secs(3600),
575                 }
576         }
577 }
578
579 impl<T: Time> ChannelLiquidity<T> {
580         #[inline]
581         fn new() -> Self {
582                 Self {
583                         min_liquidity_offset_msat: 0,
584                         max_liquidity_offset_msat: 0,
585                         last_updated: T::now(),
586                 }
587         }
588
589         /// Returns a view of the channel liquidity directed from `source` to `target` assuming
590         /// `capacity_msat`.
591         fn as_directed(
592                 &self, source: &NodeId, target: &NodeId, capacity_msat: u64, half_life: Duration
593         ) -> DirectedChannelLiquidity<&u64, T, &T> {
594                 let (min_liquidity_offset_msat, max_liquidity_offset_msat) = if source < target {
595                         (&self.min_liquidity_offset_msat, &self.max_liquidity_offset_msat)
596                 } else {
597                         (&self.max_liquidity_offset_msat, &self.min_liquidity_offset_msat)
598                 };
599
600                 DirectedChannelLiquidity {
601                         min_liquidity_offset_msat,
602                         max_liquidity_offset_msat,
603                         capacity_msat,
604                         last_updated: &self.last_updated,
605                         now: T::now(),
606                         half_life,
607                 }
608         }
609
610         /// Returns a mutable view of the channel liquidity directed from `source` to `target` assuming
611         /// `capacity_msat`.
612         fn as_directed_mut(
613                 &mut self, source: &NodeId, target: &NodeId, capacity_msat: u64, half_life: Duration
614         ) -> DirectedChannelLiquidity<&mut u64, T, &mut T> {
615                 let (min_liquidity_offset_msat, max_liquidity_offset_msat) = if source < target {
616                         (&mut self.min_liquidity_offset_msat, &mut self.max_liquidity_offset_msat)
617                 } else {
618                         (&mut self.max_liquidity_offset_msat, &mut self.min_liquidity_offset_msat)
619                 };
620
621                 DirectedChannelLiquidity {
622                         min_liquidity_offset_msat,
623                         max_liquidity_offset_msat,
624                         capacity_msat,
625                         last_updated: &mut self.last_updated,
626                         now: T::now(),
627                         half_life,
628                 }
629         }
630 }
631
632 impl<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> DirectedChannelLiquidity<L, T, U> {
633         /// Returns the success probability of routing the given HTLC `amount_msat` through the channel
634         /// in this direction.
635         fn success_probability(&self, amount_msat: u64) -> f64 {
636                 let max_liquidity_msat = self.max_liquidity_msat();
637                 let min_liquidity_msat = core::cmp::min(self.min_liquidity_msat(), max_liquidity_msat);
638                 if amount_msat > max_liquidity_msat {
639                         0.0
640                 } else if amount_msat <= min_liquidity_msat {
641                         1.0
642                 } else {
643                         let numerator = max_liquidity_msat + 1 - amount_msat;
644                         let denominator = max_liquidity_msat + 1 - min_liquidity_msat;
645                         numerator as f64 / denominator as f64
646                 }.max(0.01) // Lower bound the success probability to ensure some channel is selected.
647         }
648
649         /// Returns the lower bound of the channel liquidity balance in this direction.
650         fn min_liquidity_msat(&self) -> u64 {
651                 self.decayed_offset_msat(*self.min_liquidity_offset_msat)
652         }
653
654         /// Returns the upper bound of the channel liquidity balance in this direction.
655         fn max_liquidity_msat(&self) -> u64 {
656                 self.capacity_msat
657                         .checked_sub(self.decayed_offset_msat(*self.max_liquidity_offset_msat))
658                         .unwrap_or(0)
659         }
660
661         fn decayed_offset_msat(&self, offset_msat: u64) -> u64 {
662                 self.now.duration_since(*self.last_updated).as_secs()
663                         .checked_div(self.half_life.as_secs())
664                         .and_then(|decays| offset_msat.checked_shr(decays as u32))
665                         .unwrap_or(0)
666         }
667 }
668
669 impl<L: DerefMut<Target = u64>, T: Time, U: DerefMut<Target = T>> DirectedChannelLiquidity<L, T, U> {
670         /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat`.
671         fn failed_at_channel(&mut self, amount_msat: u64) {
672                 if amount_msat < self.max_liquidity_msat() {
673                         self.set_max_liquidity_msat(amount_msat);
674                 }
675         }
676
677         /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat` downstream.
678         fn failed_downstream(&mut self, amount_msat: u64) {
679                 if amount_msat > self.min_liquidity_msat() {
680                         self.set_min_liquidity_msat(amount_msat);
681                 }
682         }
683
684         /// Adjusts the channel liquidity balance bounds when successfully routing `amount_msat`.
685         fn successful(&mut self, amount_msat: u64) {
686                 let max_liquidity_msat = self.max_liquidity_msat().checked_sub(amount_msat).unwrap_or(0);
687                 self.set_max_liquidity_msat(max_liquidity_msat);
688         }
689
690         /// Adjusts the lower bound of the channel liquidity balance in this direction.
691         fn set_min_liquidity_msat(&mut self, amount_msat: u64) {
692                 *self.min_liquidity_offset_msat = amount_msat;
693                 *self.max_liquidity_offset_msat = if amount_msat > self.max_liquidity_msat() {
694                         0
695                 } else {
696                         self.decayed_offset_msat(*self.max_liquidity_offset_msat)
697                 };
698                 *self.last_updated = self.now;
699         }
700
701         /// Adjusts the upper bound of the channel liquidity balance in this direction.
702         fn set_max_liquidity_msat(&mut self, amount_msat: u64) {
703                 *self.max_liquidity_offset_msat = self.capacity_msat.checked_sub(amount_msat).unwrap_or(0);
704                 *self.min_liquidity_offset_msat = if amount_msat < self.min_liquidity_msat() {
705                         0
706                 } else {
707                         self.decayed_offset_msat(*self.min_liquidity_offset_msat)
708                 };
709                 *self.last_updated = self.now;
710         }
711 }
712
713 impl<G: Deref<Target = NetworkGraph>, T: Time> Score for ProbabilisticScorerUsingTime<G, T> {
714         fn channel_penalty_msat(
715                 &self, short_channel_id: u64, amount_msat: u64, capacity_msat: u64, source: &NodeId,
716                 target: &NodeId
717         ) -> u64 {
718                 let liquidity_penalty_multiplier_msat = self.params.liquidity_penalty_multiplier_msat;
719                 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
720                 let success_probability = self.channel_liquidities
721                         .get(&short_channel_id)
722                         .unwrap_or(&ChannelLiquidity::new())
723                         .as_directed(source, target, capacity_msat, liquidity_offset_half_life)
724                         .success_probability(amount_msat);
725                 // NOTE: If success_probability is ever changed to return 0.0, log10 is undefined so return
726                 // u64::max_value instead.
727                 debug_assert!(success_probability > core::f64::EPSILON);
728                 (-(success_probability.log10()) * liquidity_penalty_multiplier_msat as f64) as u64
729         }
730
731         fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
732                 let amount_msat = path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0);
733                 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
734                 let network_graph = self.network_graph.read_only();
735                 for hop in path {
736                         let target = NodeId::from_pubkey(&hop.pubkey);
737                         let channel_directed_from_source = network_graph.channels()
738                                 .get(&hop.short_channel_id)
739                                 .and_then(|channel| channel.as_directed_to(&target));
740
741                         // Only score announced channels.
742                         if let Some((channel, source)) = channel_directed_from_source {
743                                 let capacity_msat = channel.effective_capacity().as_msat();
744                                 if hop.short_channel_id == short_channel_id {
745                                         self.channel_liquidities
746                                                 .entry(hop.short_channel_id)
747                                                 .or_insert_with(ChannelLiquidity::new)
748                                                 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
749                                                 .failed_at_channel(amount_msat);
750                                         break;
751                                 }
752
753                                 self.channel_liquidities
754                                         .entry(hop.short_channel_id)
755                                         .or_insert_with(ChannelLiquidity::new)
756                                         .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
757                                         .failed_downstream(amount_msat);
758                         }
759                 }
760         }
761
762         fn payment_path_successful(&mut self, path: &[&RouteHop]) {
763                 let amount_msat = path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0);
764                 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
765                 let network_graph = self.network_graph.read_only();
766                 for hop in path {
767                         let target = NodeId::from_pubkey(&hop.pubkey);
768                         let channel_directed_from_source = network_graph.channels()
769                                 .get(&hop.short_channel_id)
770                                 .and_then(|channel| channel.as_directed_to(&target));
771
772                         // Only score announced channels.
773                         if let Some((channel, source)) = channel_directed_from_source {
774                                 let capacity_msat = channel.effective_capacity().as_msat();
775                                 self.channel_liquidities
776                                         .entry(hop.short_channel_id)
777                                         .or_insert_with(ChannelLiquidity::new)
778                                         .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
779                                         .successful(amount_msat);
780                         }
781                 }
782         }
783 }
784
785 impl<G: Deref<Target = NetworkGraph>, T: Time> Writeable for ProbabilisticScorerUsingTime<G, T> {
786         #[inline]
787         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
788                 write_tlv_fields!(w, {
789                         (0, self.channel_liquidities, required)
790                 });
791                 Ok(())
792         }
793 }
794
795 impl<G, T> ReadableArgs<(ProbabilisticScoringParameters, G)> for ProbabilisticScorerUsingTime<G, T>
796 where
797         G: Deref<Target = NetworkGraph>,
798         T: Time,
799 {
800         #[inline]
801         fn read<R: Read>(
802                 r: &mut R, args: (ProbabilisticScoringParameters, G)
803         ) -> Result<Self, DecodeError> {
804                 let (params, network_graph) = args;
805                 let mut channel_liquidities = HashMap::new();
806                 read_tlv_fields!(r, {
807                         (0, channel_liquidities, required)
808                 });
809                 Ok(Self {
810                         params,
811                         network_graph,
812                         channel_liquidities,
813                 })
814         }
815 }
816
817 impl<T: Time> Writeable for ChannelLiquidity<T> {
818         #[inline]
819         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
820                 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
821                 write_tlv_fields!(w, {
822                         (0, self.min_liquidity_offset_msat, required),
823                         (2, self.max_liquidity_offset_msat, required),
824                         (4, duration_since_epoch, required),
825                 });
826                 Ok(())
827         }
828 }
829
830 impl<T: Time> Readable for ChannelLiquidity<T> {
831         #[inline]
832         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
833                 let mut min_liquidity_offset_msat = 0;
834                 let mut max_liquidity_offset_msat = 0;
835                 let mut duration_since_epoch = Duration::from_secs(0);
836                 read_tlv_fields!(r, {
837                         (0, min_liquidity_offset_msat, required),
838                         (2, max_liquidity_offset_msat, required),
839                         (4, duration_since_epoch, required),
840                 });
841                 Ok(Self {
842                         min_liquidity_offset_msat,
843                         max_liquidity_offset_msat,
844                         last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
845                 })
846         }
847 }
848
849 pub(crate) mod time {
850         use core::ops::Sub;
851         use core::time::Duration;
852         /// A measurement of time.
853         pub trait Time: Copy + Sub<Duration, Output = Self> where Self: Sized {
854                 /// Returns an instance corresponding to the current moment.
855                 fn now() -> Self;
856
857                 /// Returns the amount of time elapsed since `self` was created.
858                 fn elapsed(&self) -> Duration;
859
860                 /// Returns the amount of time passed between `earlier` and `self`.
861                 fn duration_since(&self, earlier: Self) -> Duration;
862
863                 /// Returns the amount of time passed since the beginning of [`Time`].
864                 ///
865                 /// Used during (de-)serialization.
866                 fn duration_since_epoch() -> Duration;
867         }
868
869         /// A state in which time has no meaning.
870         #[derive(Clone, Copy, Debug, PartialEq, Eq)]
871         pub struct Eternity;
872
873         #[cfg(not(feature = "no-std"))]
874         impl Time for std::time::Instant {
875                 fn now() -> Self {
876                         std::time::Instant::now()
877                 }
878
879                 fn duration_since(&self, earlier: Self) -> Duration {
880                         self.duration_since(earlier)
881                 }
882
883                 fn duration_since_epoch() -> Duration {
884                         use std::time::SystemTime;
885                         SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
886                 }
887
888                 fn elapsed(&self) -> Duration {
889                         std::time::Instant::elapsed(self)
890                 }
891         }
892
893         impl Time for Eternity {
894                 fn now() -> Self {
895                         Self
896                 }
897
898                 fn duration_since(&self, _earlier: Self) -> Duration {
899                         Duration::from_secs(0)
900                 }
901
902                 fn duration_since_epoch() -> Duration {
903                         Duration::from_secs(0)
904                 }
905
906                 fn elapsed(&self) -> Duration {
907                         Duration::from_secs(0)
908                 }
909         }
910
911         impl Sub<Duration> for Eternity {
912                 type Output = Self;
913
914                 fn sub(self, _other: Duration) -> Self {
915                         self
916                 }
917         }
918 }
919
920 pub(crate) use self::time::Time;
921
922 #[cfg(test)]
923 mod tests {
924         use super::{ChannelLiquidity, ProbabilisticScoringParameters, ProbabilisticScorerUsingTime, ScoringParameters, ScorerUsingTime, Time};
925         use super::time::Eternity;
926
927         use ln::features::{ChannelFeatures, NodeFeatures};
928         use ln::msgs::{ChannelAnnouncement, ChannelUpdate, OptionalField, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
929         use routing::scoring::Score;
930         use routing::network_graph::{NetworkGraph, NodeId};
931         use routing::router::RouteHop;
932         use util::ser::{Readable, ReadableArgs, Writeable};
933
934         use bitcoin::blockdata::constants::genesis_block;
935         use bitcoin::hashes::Hash;
936         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
937         use bitcoin::network::constants::Network;
938         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
939         use core::cell::Cell;
940         use core::ops::Sub;
941         use core::time::Duration;
942         use io;
943
944         // `Time` tests
945
946         /// Time that can be advanced manually in tests.
947         #[derive(Clone, Copy, Debug, PartialEq, Eq)]
948         struct SinceEpoch(Duration);
949
950         impl SinceEpoch {
951                 thread_local! {
952                         static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
953                 }
954
955                 fn advance(duration: Duration) {
956                         Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
957                 }
958         }
959
960         impl Time for SinceEpoch {
961                 fn now() -> Self {
962                         Self(Self::duration_since_epoch())
963                 }
964
965                 fn duration_since(&self, earlier: Self) -> Duration {
966                         self.0 - earlier.0
967                 }
968
969                 fn duration_since_epoch() -> Duration {
970                         Self::ELAPSED.with(|elapsed| elapsed.get())
971                 }
972
973                 fn elapsed(&self) -> Duration {
974                         Self::duration_since_epoch() - self.0
975                 }
976         }
977
978         impl Sub<Duration> for SinceEpoch {
979                 type Output = Self;
980
981                 fn sub(self, other: Duration) -> Self {
982                         Self(self.0 - other)
983                 }
984         }
985
986         #[test]
987         fn time_passes_when_advanced() {
988                 let now = SinceEpoch::now();
989                 assert_eq!(now.elapsed(), Duration::from_secs(0));
990
991                 SinceEpoch::advance(Duration::from_secs(1));
992                 SinceEpoch::advance(Duration::from_secs(1));
993
994                 let elapsed = now.elapsed();
995                 let later = SinceEpoch::now();
996
997                 assert_eq!(elapsed, Duration::from_secs(2));
998                 assert_eq!(later - elapsed, now);
999         }
1000
1001         #[test]
1002         fn time_never_passes_in_an_eternity() {
1003                 let now = Eternity::now();
1004                 let elapsed = now.elapsed();
1005                 let later = Eternity::now();
1006
1007                 assert_eq!(now.elapsed(), Duration::from_secs(0));
1008                 assert_eq!(later - elapsed, now);
1009         }
1010
1011         // `Scorer` tests
1012
1013         /// A scorer for testing with time that can be manually advanced.
1014         type Scorer = ScorerUsingTime::<SinceEpoch>;
1015
1016         fn source_privkey() -> SecretKey {
1017                 SecretKey::from_slice(&[42; 32]).unwrap()
1018         }
1019
1020         fn target_privkey() -> SecretKey {
1021                 SecretKey::from_slice(&[43; 32]).unwrap()
1022         }
1023
1024         fn source_pubkey() -> PublicKey {
1025                 let secp_ctx = Secp256k1::new();
1026                 PublicKey::from_secret_key(&secp_ctx, &source_privkey())
1027         }
1028
1029         fn target_pubkey() -> PublicKey {
1030                 let secp_ctx = Secp256k1::new();
1031                 PublicKey::from_secret_key(&secp_ctx, &target_privkey())
1032         }
1033
1034         fn source_node_id() -> NodeId {
1035                 NodeId::from_pubkey(&source_pubkey())
1036         }
1037
1038         fn target_node_id() -> NodeId {
1039                 NodeId::from_pubkey(&target_pubkey())
1040         }
1041
1042         #[test]
1043         fn penalizes_without_channel_failures() {
1044                 let scorer = Scorer::new(ScoringParameters {
1045                         base_penalty_msat: 1_000,
1046                         failure_penalty_msat: 512,
1047                         failure_penalty_half_life: Duration::from_secs(1),
1048                         overuse_penalty_start_1024th: 1024,
1049                         overuse_penalty_msat_per_1024th: 0,
1050                 });
1051                 let source = source_node_id();
1052                 let target = target_node_id();
1053                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1054
1055                 SinceEpoch::advance(Duration::from_secs(1));
1056                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1057         }
1058
1059         #[test]
1060         fn accumulates_channel_failure_penalties() {
1061                 let mut scorer = Scorer::new(ScoringParameters {
1062                         base_penalty_msat: 1_000,
1063                         failure_penalty_msat: 64,
1064                         failure_penalty_half_life: Duration::from_secs(10),
1065                         overuse_penalty_start_1024th: 1024,
1066                         overuse_penalty_msat_per_1024th: 0,
1067                 });
1068                 let source = source_node_id();
1069                 let target = target_node_id();
1070                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1071
1072                 scorer.payment_path_failed(&[], 42);
1073                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1074
1075                 scorer.payment_path_failed(&[], 42);
1076                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1077
1078                 scorer.payment_path_failed(&[], 42);
1079                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_192);
1080         }
1081
1082         #[test]
1083         fn decays_channel_failure_penalties_over_time() {
1084                 let mut scorer = Scorer::new(ScoringParameters {
1085                         base_penalty_msat: 1_000,
1086                         failure_penalty_msat: 512,
1087                         failure_penalty_half_life: Duration::from_secs(10),
1088                         overuse_penalty_start_1024th: 1024,
1089                         overuse_penalty_msat_per_1024th: 0,
1090                 });
1091                 let source = source_node_id();
1092                 let target = target_node_id();
1093                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1094
1095                 scorer.payment_path_failed(&[], 42);
1096                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1097
1098                 SinceEpoch::advance(Duration::from_secs(9));
1099                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1100
1101                 SinceEpoch::advance(Duration::from_secs(1));
1102                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1103
1104                 SinceEpoch::advance(Duration::from_secs(10 * 8));
1105                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_001);
1106
1107                 SinceEpoch::advance(Duration::from_secs(10));
1108                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1109
1110                 SinceEpoch::advance(Duration::from_secs(10));
1111                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1112         }
1113
1114         #[test]
1115         fn decays_channel_failure_penalties_without_shift_overflow() {
1116                 let mut scorer = Scorer::new(ScoringParameters {
1117                         base_penalty_msat: 1_000,
1118                         failure_penalty_msat: 512,
1119                         failure_penalty_half_life: Duration::from_secs(10),
1120                         overuse_penalty_start_1024th: 1024,
1121                         overuse_penalty_msat_per_1024th: 0,
1122                 });
1123                 let source = source_node_id();
1124                 let target = target_node_id();
1125                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1126
1127                 scorer.payment_path_failed(&[], 42);
1128                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1129
1130                 // An unchecked right shift 64 bits or more in ChannelFailure::decayed_penalty_msat would
1131                 // cause an overflow.
1132                 SinceEpoch::advance(Duration::from_secs(10 * 64));
1133                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1134
1135                 SinceEpoch::advance(Duration::from_secs(10));
1136                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1137         }
1138
1139         #[test]
1140         fn accumulates_channel_failure_penalties_after_decay() {
1141                 let mut scorer = Scorer::new(ScoringParameters {
1142                         base_penalty_msat: 1_000,
1143                         failure_penalty_msat: 512,
1144                         failure_penalty_half_life: Duration::from_secs(10),
1145                         overuse_penalty_start_1024th: 1024,
1146                         overuse_penalty_msat_per_1024th: 0,
1147                 });
1148                 let source = source_node_id();
1149                 let target = target_node_id();
1150                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1151
1152                 scorer.payment_path_failed(&[], 42);
1153                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1154
1155                 SinceEpoch::advance(Duration::from_secs(10));
1156                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1157
1158                 scorer.payment_path_failed(&[], 42);
1159                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_768);
1160
1161                 SinceEpoch::advance(Duration::from_secs(10));
1162                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_384);
1163         }
1164
1165         #[test]
1166         fn reduces_channel_failure_penalties_after_success() {
1167                 let mut scorer = Scorer::new(ScoringParameters {
1168                         base_penalty_msat: 1_000,
1169                         failure_penalty_msat: 512,
1170                         failure_penalty_half_life: Duration::from_secs(10),
1171                         overuse_penalty_start_1024th: 1024,
1172                         overuse_penalty_msat_per_1024th: 0,
1173                 });
1174                 let source = source_node_id();
1175                 let target = target_node_id();
1176                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1177
1178                 scorer.payment_path_failed(&[], 42);
1179                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1180
1181                 SinceEpoch::advance(Duration::from_secs(10));
1182                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1183
1184                 let hop = RouteHop {
1185                         pubkey: PublicKey::from_slice(target.as_slice()).unwrap(),
1186                         node_features: NodeFeatures::known(),
1187                         short_channel_id: 42,
1188                         channel_features: ChannelFeatures::known(),
1189                         fee_msat: 1,
1190                         cltv_expiry_delta: 18,
1191                 };
1192                 scorer.payment_path_successful(&[&hop]);
1193                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1194
1195                 SinceEpoch::advance(Duration::from_secs(10));
1196                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1197         }
1198
1199         #[test]
1200         fn restores_persisted_channel_failure_penalties() {
1201                 let mut scorer = Scorer::new(ScoringParameters {
1202                         base_penalty_msat: 1_000,
1203                         failure_penalty_msat: 512,
1204                         failure_penalty_half_life: Duration::from_secs(10),
1205                         overuse_penalty_start_1024th: 1024,
1206                         overuse_penalty_msat_per_1024th: 0,
1207                 });
1208                 let source = source_node_id();
1209                 let target = target_node_id();
1210
1211                 scorer.payment_path_failed(&[], 42);
1212                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1213
1214                 SinceEpoch::advance(Duration::from_secs(10));
1215                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1216
1217                 scorer.payment_path_failed(&[], 43);
1218                 assert_eq!(scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
1219
1220                 let mut serialized_scorer = Vec::new();
1221                 scorer.write(&mut serialized_scorer).unwrap();
1222
1223                 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
1224                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1225                 assert_eq!(deserialized_scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
1226         }
1227
1228         #[test]
1229         fn decays_persisted_channel_failure_penalties() {
1230                 let mut scorer = Scorer::new(ScoringParameters {
1231                         base_penalty_msat: 1_000,
1232                         failure_penalty_msat: 512,
1233                         failure_penalty_half_life: Duration::from_secs(10),
1234                         overuse_penalty_start_1024th: 1024,
1235                         overuse_penalty_msat_per_1024th: 0,
1236                 });
1237                 let source = source_node_id();
1238                 let target = target_node_id();
1239
1240                 scorer.payment_path_failed(&[], 42);
1241                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1242
1243                 let mut serialized_scorer = Vec::new();
1244                 scorer.write(&mut serialized_scorer).unwrap();
1245
1246                 SinceEpoch::advance(Duration::from_secs(10));
1247
1248                 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
1249                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1250
1251                 SinceEpoch::advance(Duration::from_secs(10));
1252                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1253         }
1254
1255         #[test]
1256         fn charges_per_1024th_penalty() {
1257                 let scorer = Scorer::new(ScoringParameters {
1258                         base_penalty_msat: 0,
1259                         failure_penalty_msat: 0,
1260                         failure_penalty_half_life: Duration::from_secs(0),
1261                         overuse_penalty_start_1024th: 256,
1262                         overuse_penalty_msat_per_1024th: 100,
1263                 });
1264                 let source = source_node_id();
1265                 let target = target_node_id();
1266
1267                 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 1_024_000, &source, &target), 0);
1268                 assert_eq!(scorer.channel_penalty_msat(42, 256_999, 1_024_000, &source, &target), 0);
1269                 assert_eq!(scorer.channel_penalty_msat(42, 257_000, 1_024_000, &source, &target), 100);
1270                 assert_eq!(scorer.channel_penalty_msat(42, 258_000, 1_024_000, &source, &target), 200);
1271                 assert_eq!(scorer.channel_penalty_msat(42, 512_000, 1_024_000, &source, &target), 256 * 100);
1272         }
1273
1274         // `ProbabilisticScorer` tests
1275
1276         /// A probabilistic scorer for testing with time that can be manually advanced.
1277         type ProbabilisticScorer<'a> = ProbabilisticScorerUsingTime::<&'a NetworkGraph, SinceEpoch>;
1278
1279         fn sender_privkey() -> SecretKey {
1280                 SecretKey::from_slice(&[41; 32]).unwrap()
1281         }
1282
1283         fn recipient_privkey() -> SecretKey {
1284                 SecretKey::from_slice(&[45; 32]).unwrap()
1285         }
1286
1287         fn sender_pubkey() -> PublicKey {
1288                 let secp_ctx = Secp256k1::new();
1289                 PublicKey::from_secret_key(&secp_ctx, &sender_privkey())
1290         }
1291
1292         fn recipient_pubkey() -> PublicKey {
1293                 let secp_ctx = Secp256k1::new();
1294                 PublicKey::from_secret_key(&secp_ctx, &recipient_privkey())
1295         }
1296
1297         fn sender_node_id() -> NodeId {
1298                 NodeId::from_pubkey(&sender_pubkey())
1299         }
1300
1301         fn recipient_node_id() -> NodeId {
1302                 NodeId::from_pubkey(&recipient_pubkey())
1303         }
1304
1305         fn network_graph() -> NetworkGraph {
1306                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1307                 let mut network_graph = NetworkGraph::new(genesis_hash);
1308                 add_channel(&mut network_graph, 42, source_privkey(), target_privkey());
1309                 add_channel(&mut network_graph, 43, target_privkey(), recipient_privkey());
1310
1311                 network_graph
1312         }
1313
1314         fn add_channel(
1315                 network_graph: &mut NetworkGraph, short_channel_id: u64, node_1_key: SecretKey,
1316                 node_2_key: SecretKey
1317         ) {
1318                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1319                 let node_1_secret = &SecretKey::from_slice(&[39; 32]).unwrap();
1320                 let node_2_secret = &SecretKey::from_slice(&[40; 32]).unwrap();
1321                 let secp_ctx = Secp256k1::new();
1322                 let unsigned_announcement = UnsignedChannelAnnouncement {
1323                         features: ChannelFeatures::known(),
1324                         chain_hash: genesis_hash,
1325                         short_channel_id,
1326                         node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_key),
1327                         node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_key),
1328                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_secret),
1329                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_secret),
1330                         excess_data: Vec::new(),
1331                 };
1332                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1333                 let signed_announcement = ChannelAnnouncement {
1334                         node_signature_1: secp_ctx.sign(&msghash, &node_1_key),
1335                         node_signature_2: secp_ctx.sign(&msghash, &node_2_key),
1336                         bitcoin_signature_1: secp_ctx.sign(&msghash, &node_1_secret),
1337                         bitcoin_signature_2: secp_ctx.sign(&msghash, &node_2_secret),
1338                         contents: unsigned_announcement,
1339                 };
1340                 let chain_source: Option<&::util::test_utils::TestChainSource> = None;
1341                 network_graph.update_channel_from_announcement(
1342                         &signed_announcement, &chain_source, &secp_ctx).unwrap();
1343                 update_channel(network_graph, short_channel_id, node_1_key, 0);
1344                 update_channel(network_graph, short_channel_id, node_2_key, 1);
1345         }
1346
1347         fn update_channel(
1348                 network_graph: &mut NetworkGraph, short_channel_id: u64, node_key: SecretKey, flags: u8
1349         ) {
1350                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1351                 let secp_ctx = Secp256k1::new();
1352                 let unsigned_update = UnsignedChannelUpdate {
1353                         chain_hash: genesis_hash,
1354                         short_channel_id,
1355                         timestamp: 100,
1356                         flags,
1357                         cltv_expiry_delta: 18,
1358                         htlc_minimum_msat: 0,
1359                         htlc_maximum_msat: OptionalField::Present(1_000),
1360                         fee_base_msat: 1,
1361                         fee_proportional_millionths: 0,
1362                         excess_data: Vec::new(),
1363                 };
1364                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_update.encode()[..])[..]);
1365                 let signed_update = ChannelUpdate {
1366                         signature: secp_ctx.sign(&msghash, &node_key),
1367                         contents: unsigned_update,
1368                 };
1369                 network_graph.update_channel(&signed_update, &secp_ctx).unwrap();
1370         }
1371
1372         fn payment_path_for_amount(amount_msat: u64) -> Vec<RouteHop> {
1373                 vec![
1374                         RouteHop {
1375                                 pubkey: source_pubkey(),
1376                                 node_features: NodeFeatures::known(),
1377                                 short_channel_id: 41,
1378                                 channel_features: ChannelFeatures::known(),
1379                                 fee_msat: 1,
1380                                 cltv_expiry_delta: 18,
1381                         },
1382                         RouteHop {
1383                                 pubkey: target_pubkey(),
1384                                 node_features: NodeFeatures::known(),
1385                                 short_channel_id: 42,
1386                                 channel_features: ChannelFeatures::known(),
1387                                 fee_msat: 2,
1388                                 cltv_expiry_delta: 18,
1389                         },
1390                         RouteHop {
1391                                 pubkey: recipient_pubkey(),
1392                                 node_features: NodeFeatures::known(),
1393                                 short_channel_id: 43,
1394                                 channel_features: ChannelFeatures::known(),
1395                                 fee_msat: amount_msat,
1396                                 cltv_expiry_delta: 18,
1397                         },
1398                 ]
1399         }
1400
1401         #[test]
1402         fn liquidity_bounds_directed_from_lowest_node_id() {
1403                 let last_updated = SinceEpoch::now();
1404                 let network_graph = network_graph();
1405                 let params = ProbabilisticScoringParameters::default();
1406                 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1407                         .with_channel(42,
1408                                 ChannelLiquidity {
1409                                         min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1410                                 })
1411                         .with_channel(43,
1412                                 ChannelLiquidity {
1413                                         min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1414                                 });
1415                 let source = source_node_id();
1416                 let target = target_node_id();
1417                 let recipient = recipient_node_id();
1418                 assert!(source > target);
1419                 assert!(target < recipient);
1420
1421                 // Update minimum liquidity.
1422
1423                 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1424                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1425                         .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1426                 assert_eq!(liquidity.min_liquidity_msat(), 100);
1427                 assert_eq!(liquidity.max_liquidity_msat(), 300);
1428
1429                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1430                         .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1431                 assert_eq!(liquidity.min_liquidity_msat(), 700);
1432                 assert_eq!(liquidity.max_liquidity_msat(), 900);
1433
1434                 scorer.channel_liquidities.get_mut(&42).unwrap()
1435                         .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1436                         .set_min_liquidity_msat(200);
1437
1438                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1439                         .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1440                 assert_eq!(liquidity.min_liquidity_msat(), 200);
1441                 assert_eq!(liquidity.max_liquidity_msat(), 300);
1442
1443                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1444                         .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1445                 assert_eq!(liquidity.min_liquidity_msat(), 700);
1446                 assert_eq!(liquidity.max_liquidity_msat(), 800);
1447
1448                 // Update maximum liquidity.
1449
1450                 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1451                         .as_directed(&target, &recipient, 1_000, liquidity_offset_half_life);
1452                 assert_eq!(liquidity.min_liquidity_msat(), 700);
1453                 assert_eq!(liquidity.max_liquidity_msat(), 900);
1454
1455                 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1456                         .as_directed(&recipient, &target, 1_000, liquidity_offset_half_life);
1457                 assert_eq!(liquidity.min_liquidity_msat(), 100);
1458                 assert_eq!(liquidity.max_liquidity_msat(), 300);
1459
1460                 scorer.channel_liquidities.get_mut(&43).unwrap()
1461                         .as_directed_mut(&target, &recipient, 1_000, liquidity_offset_half_life)
1462                         .set_max_liquidity_msat(200);
1463
1464                 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1465                         .as_directed(&target, &recipient, 1_000, liquidity_offset_half_life);
1466                 assert_eq!(liquidity.min_liquidity_msat(), 0);
1467                 assert_eq!(liquidity.max_liquidity_msat(), 200);
1468
1469                 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1470                         .as_directed(&recipient, &target, 1_000, liquidity_offset_half_life);
1471                 assert_eq!(liquidity.min_liquidity_msat(), 800);
1472                 assert_eq!(liquidity.max_liquidity_msat(), 1000);
1473         }
1474
1475         #[test]
1476         fn resets_liquidity_upper_bound_when_crossed_by_lower_bound() {
1477                 let last_updated = SinceEpoch::now();
1478                 let network_graph = network_graph();
1479                 let params = ProbabilisticScoringParameters::default();
1480                 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1481                         .with_channel(42,
1482                                 ChannelLiquidity {
1483                                         min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1484                                 });
1485                 let source = source_node_id();
1486                 let target = target_node_id();
1487                 assert!(source > target);
1488
1489                 // Check initial bounds.
1490                 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1491                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1492                         .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1493                 assert_eq!(liquidity.min_liquidity_msat(), 400);
1494                 assert_eq!(liquidity.max_liquidity_msat(), 800);
1495
1496                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1497                         .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1498                 assert_eq!(liquidity.min_liquidity_msat(), 200);
1499                 assert_eq!(liquidity.max_liquidity_msat(), 600);
1500
1501                 // Reset from source to target.
1502                 scorer.channel_liquidities.get_mut(&42).unwrap()
1503                         .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1504                         .set_min_liquidity_msat(900);
1505
1506                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1507                         .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1508                 assert_eq!(liquidity.min_liquidity_msat(), 900);
1509                 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1510
1511                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1512                         .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1513                 assert_eq!(liquidity.min_liquidity_msat(), 0);
1514                 assert_eq!(liquidity.max_liquidity_msat(), 100);
1515
1516                 // Reset from target to source.
1517                 scorer.channel_liquidities.get_mut(&42).unwrap()
1518                         .as_directed_mut(&target, &source, 1_000, liquidity_offset_half_life)
1519                         .set_min_liquidity_msat(400);
1520
1521                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1522                         .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1523                 assert_eq!(liquidity.min_liquidity_msat(), 0);
1524                 assert_eq!(liquidity.max_liquidity_msat(), 600);
1525
1526                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1527                         .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1528                 assert_eq!(liquidity.min_liquidity_msat(), 400);
1529                 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1530         }
1531
1532         #[test]
1533         fn resets_liquidity_lower_bound_when_crossed_by_upper_bound() {
1534                 let last_updated = SinceEpoch::now();
1535                 let network_graph = network_graph();
1536                 let params = ProbabilisticScoringParameters::default();
1537                 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1538                         .with_channel(42,
1539                                 ChannelLiquidity {
1540                                         min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1541                                 });
1542                 let source = source_node_id();
1543                 let target = target_node_id();
1544                 assert!(source > target);
1545
1546                 // Check initial bounds.
1547                 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1548                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1549                         .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1550                 assert_eq!(liquidity.min_liquidity_msat(), 400);
1551                 assert_eq!(liquidity.max_liquidity_msat(), 800);
1552
1553                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1554                         .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1555                 assert_eq!(liquidity.min_liquidity_msat(), 200);
1556                 assert_eq!(liquidity.max_liquidity_msat(), 600);
1557
1558                 // Reset from source to target.
1559                 scorer.channel_liquidities.get_mut(&42).unwrap()
1560                         .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1561                         .set_max_liquidity_msat(300);
1562
1563                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1564                         .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1565                 assert_eq!(liquidity.min_liquidity_msat(), 0);
1566                 assert_eq!(liquidity.max_liquidity_msat(), 300);
1567
1568                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1569                         .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1570                 assert_eq!(liquidity.min_liquidity_msat(), 700);
1571                 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1572
1573                 // Reset from target to source.
1574                 scorer.channel_liquidities.get_mut(&42).unwrap()
1575                         .as_directed_mut(&target, &source, 1_000, liquidity_offset_half_life)
1576                         .set_max_liquidity_msat(600);
1577
1578                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1579                         .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1580                 assert_eq!(liquidity.min_liquidity_msat(), 400);
1581                 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1582
1583                 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1584                         .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1585                 assert_eq!(liquidity.min_liquidity_msat(), 0);
1586                 assert_eq!(liquidity.max_liquidity_msat(), 600);
1587         }
1588
1589         #[test]
1590         fn increased_penalty_nearing_liquidity_upper_bound() {
1591                 let network_graph = network_graph();
1592                 let params = ProbabilisticScoringParameters {
1593                         liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1594                 };
1595                 let scorer = ProbabilisticScorer::new(params, &network_graph);
1596                 let source = source_node_id();
1597                 let target = target_node_id();
1598
1599                 assert_eq!(scorer.channel_penalty_msat(42, 100, 100_000, &source, &target), 0);
1600                 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 100_000, &source, &target), 4);
1601                 assert_eq!(scorer.channel_penalty_msat(42, 10_000, 100_000, &source, &target), 45);
1602                 assert_eq!(scorer.channel_penalty_msat(42, 100_000, 100_000, &source, &target), 2_000);
1603
1604                 assert_eq!(scorer.channel_penalty_msat(42, 125, 1_000, &source, &target), 57);
1605                 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1606                 assert_eq!(scorer.channel_penalty_msat(42, 375, 1_000, &source, &target), 203);
1607                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1608                 assert_eq!(scorer.channel_penalty_msat(42, 625, 1_000, &source, &target), 425);
1609                 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1610                 assert_eq!(scorer.channel_penalty_msat(42, 875, 1_000, &source, &target), 900);
1611         }
1612
1613         #[test]
1614         fn constant_penalty_outside_liquidity_bounds() {
1615                 let last_updated = SinceEpoch::now();
1616                 let network_graph = network_graph();
1617                 let params = ProbabilisticScoringParameters {
1618                         liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1619                 };
1620                 let scorer = ProbabilisticScorer::new(params, &network_graph)
1621                         .with_channel(42,
1622                                 ChannelLiquidity {
1623                                         min_liquidity_offset_msat: 40, max_liquidity_offset_msat: 40, last_updated
1624                                 });
1625                 let source = source_node_id();
1626                 let target = target_node_id();
1627
1628                 assert_eq!(scorer.channel_penalty_msat(42, 39, 100, &source, &target), 0);
1629                 assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 0);
1630                 assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 2_000);
1631                 assert_eq!(scorer.channel_penalty_msat(42, 61, 100, &source, &target), 2_000);
1632         }
1633
1634         #[test]
1635         fn does_not_further_penalize_own_channel() {
1636                 let network_graph = network_graph();
1637                 let params = ProbabilisticScoringParameters {
1638                         liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1639                 };
1640                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1641                 let sender = sender_node_id();
1642                 let source = source_node_id();
1643                 let failed_path = payment_path_for_amount(500);
1644                 let successful_path = payment_path_for_amount(200);
1645
1646                 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1647
1648                 scorer.payment_path_failed(&failed_path.iter().collect::<Vec<_>>(), 41);
1649                 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1650
1651                 scorer.payment_path_successful(&successful_path.iter().collect::<Vec<_>>());
1652                 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1653         }
1654
1655         #[test]
1656         fn sets_liquidity_lower_bound_on_downstream_failure() {
1657                 let network_graph = network_graph();
1658                 let params = ProbabilisticScoringParameters {
1659                         liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1660                 };
1661                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1662                 let source = source_node_id();
1663                 let target = target_node_id();
1664                 let path = payment_path_for_amount(500);
1665
1666                 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1667                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1668                 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1669
1670                 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 43);
1671
1672                 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 0);
1673                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 0);
1674                 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 300);
1675         }
1676
1677         #[test]
1678         fn sets_liquidity_upper_bound_on_failure() {
1679                 let network_graph = network_graph();
1680                 let params = ProbabilisticScoringParameters {
1681                         liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1682                 };
1683                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1684                 let source = source_node_id();
1685                 let target = target_node_id();
1686                 let path = payment_path_for_amount(500);
1687
1688                 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1689                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1690                 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1691
1692                 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 42);
1693
1694                 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 300);
1695                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1696                 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 2_000);
1697         }
1698
1699         #[test]
1700         fn reduces_liquidity_upper_bound_along_path_on_success() {
1701                 let network_graph = network_graph();
1702                 let params = ProbabilisticScoringParameters {
1703                         liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1704                 };
1705                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1706                 let sender = sender_node_id();
1707                 let source = source_node_id();
1708                 let target = target_node_id();
1709                 let recipient = recipient_node_id();
1710                 let path = payment_path_for_amount(500);
1711
1712                 assert_eq!(scorer.channel_penalty_msat(41, 250, 1_000, &sender, &source), 124);
1713                 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1714                 assert_eq!(scorer.channel_penalty_msat(43, 250, 1_000, &target, &recipient), 124);
1715
1716                 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
1717
1718                 assert_eq!(scorer.channel_penalty_msat(41, 250, 1_000, &sender, &source), 124);
1719                 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 300);
1720                 assert_eq!(scorer.channel_penalty_msat(43, 250, 1_000, &target, &recipient), 300);
1721         }
1722
1723         #[test]
1724         fn decays_liquidity_bounds_over_time() {
1725                 let network_graph = network_graph();
1726                 let params = ProbabilisticScoringParameters {
1727                         liquidity_penalty_multiplier_msat: 1_000,
1728                         liquidity_offset_half_life: Duration::from_secs(10),
1729                 };
1730                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1731                 let source = source_node_id();
1732                 let target = target_node_id();
1733
1734                 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1735                 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1736
1737                 scorer.payment_path_failed(&payment_path_for_amount(768).iter().collect::<Vec<_>>(), 42);
1738                 scorer.payment_path_failed(&payment_path_for_amount(128).iter().collect::<Vec<_>>(), 43);
1739
1740                 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
1741                 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 92);
1742                 assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_424);
1743                 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
1744
1745                 SinceEpoch::advance(Duration::from_secs(9));
1746                 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
1747                 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 92);
1748                 assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_424);
1749                 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
1750
1751                 SinceEpoch::advance(Duration::from_secs(1));
1752                 assert_eq!(scorer.channel_penalty_msat(42, 64, 1_024, &source, &target), 0);
1753                 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 34);
1754                 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 1_812);
1755                 assert_eq!(scorer.channel_penalty_msat(42, 960, 1_024, &source, &target), 2_000);
1756
1757                 // Fully decay liquidity lower bound.
1758                 SinceEpoch::advance(Duration::from_secs(10 * 7));
1759                 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1760                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1_024, &source, &target), 0);
1761                 assert_eq!(scorer.channel_penalty_msat(42, 1_023, 1_024, &source, &target), 2_000);
1762                 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1763
1764                 // Fully decay liquidity upper bound.
1765                 SinceEpoch::advance(Duration::from_secs(10));
1766                 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1767                 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1768
1769                 SinceEpoch::advance(Duration::from_secs(10));
1770                 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1771                 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1772         }
1773
1774         #[test]
1775         fn decays_liquidity_bounds_without_shift_overflow() {
1776                 let network_graph = network_graph();
1777                 let params = ProbabilisticScoringParameters {
1778                         liquidity_penalty_multiplier_msat: 1_000,
1779                         liquidity_offset_half_life: Duration::from_secs(10),
1780                 };
1781                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1782                 let source = source_node_id();
1783                 let target = target_node_id();
1784                 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1785
1786                 scorer.payment_path_failed(&payment_path_for_amount(512).iter().collect::<Vec<_>>(), 42);
1787                 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 281);
1788
1789                 // An unchecked right shift 64 bits or more in DirectedChannelLiquidity::decayed_offset_msat
1790                 // would cause an overflow.
1791                 SinceEpoch::advance(Duration::from_secs(10 * 64));
1792                 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1793
1794                 SinceEpoch::advance(Duration::from_secs(10));
1795                 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1796         }
1797
1798         #[test]
1799         fn restricts_liquidity_bounds_after_decay() {
1800                 let network_graph = network_graph();
1801                 let params = ProbabilisticScoringParameters {
1802                         liquidity_penalty_multiplier_msat: 1_000,
1803                         liquidity_offset_half_life: Duration::from_secs(10),
1804                 };
1805                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1806                 let source = source_node_id();
1807                 let target = target_node_id();
1808
1809                 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 300);
1810
1811                 // More knowledge gives higher confidence (256, 768), meaning a lower penalty.
1812                 scorer.payment_path_failed(&payment_path_for_amount(768).iter().collect::<Vec<_>>(), 42);
1813                 scorer.payment_path_failed(&payment_path_for_amount(256).iter().collect::<Vec<_>>(), 43);
1814                 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 281);
1815
1816                 // Decaying knowledge gives less confidence (128, 896), meaning a higher penalty.
1817                 SinceEpoch::advance(Duration::from_secs(10));
1818                 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 293);
1819
1820                 // Reducing the upper bound gives more confidence (128, 832) that the payment amount (512)
1821                 // is closer to the upper bound, meaning a higher penalty.
1822                 scorer.payment_path_successful(&payment_path_for_amount(64).iter().collect::<Vec<_>>());
1823                 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 333);
1824
1825                 // Increasing the lower bound gives more confidence (256, 832) that the payment amount (512)
1826                 // is closer to the lower bound, meaning a lower penalty.
1827                 scorer.payment_path_failed(&payment_path_for_amount(256).iter().collect::<Vec<_>>(), 43);
1828                 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 247);
1829
1830                 // Further decaying affects the lower bound more than the upper bound (128, 928).
1831                 SinceEpoch::advance(Duration::from_secs(10));
1832                 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 280);
1833         }
1834
1835         #[test]
1836         fn restores_persisted_liquidity_bounds() {
1837                 let network_graph = network_graph();
1838                 let params = ProbabilisticScoringParameters {
1839                         liquidity_penalty_multiplier_msat: 1_000,
1840                         liquidity_offset_half_life: Duration::from_secs(10),
1841                 };
1842                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1843                 let source = source_node_id();
1844                 let target = target_node_id();
1845
1846                 scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
1847                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1848
1849                 SinceEpoch::advance(Duration::from_secs(10));
1850                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 475);
1851
1852                 scorer.payment_path_failed(&payment_path_for_amount(250).iter().collect::<Vec<_>>(), 43);
1853                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1854
1855                 let mut serialized_scorer = Vec::new();
1856                 scorer.write(&mut serialized_scorer).unwrap();
1857
1858                 let mut serialized_scorer = io::Cursor::new(&serialized_scorer);
1859                 let deserialized_scorer =
1860                         <ProbabilisticScorer>::read(&mut serialized_scorer, (params, &network_graph)).unwrap();
1861                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1862         }
1863
1864         #[test]
1865         fn decays_persisted_liquidity_bounds() {
1866                 let network_graph = network_graph();
1867                 let params = ProbabilisticScoringParameters {
1868                         liquidity_penalty_multiplier_msat: 1_000,
1869                         liquidity_offset_half_life: Duration::from_secs(10),
1870                 };
1871                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1872                 let source = source_node_id();
1873                 let target = target_node_id();
1874
1875                 scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
1876                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1877
1878                 let mut serialized_scorer = Vec::new();
1879                 scorer.write(&mut serialized_scorer).unwrap();
1880
1881                 SinceEpoch::advance(Duration::from_secs(10));
1882
1883                 let mut serialized_scorer = io::Cursor::new(&serialized_scorer);
1884                 let deserialized_scorer =
1885                         <ProbabilisticScorer>::read(&mut serialized_scorer, (params, &network_graph)).unwrap();
1886                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 475);
1887
1888                 scorer.payment_path_failed(&payment_path_for_amount(250).iter().collect::<Vec<_>>(), 43);
1889                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1890
1891                 SinceEpoch::advance(Duration::from_secs(10));
1892                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 367);
1893         }
1894 }