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