Effective channel capacity for router and scoring
[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 //! [`Scorer`] may be given to [`find_route`] to score payment channels during path finding when a
13 //! 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::{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, params: RouteParameters, network_graph: NetworkGraph) {
31 //! # let logger = FakeLogger {};
32 //! #
33 //! // Use the default channel penalties.
34 //! let scorer = Scorer::default();
35 //!
36 //! // Or use custom channel penalties.
37 //! let scorer = Scorer::new(ScoringParameters {
38 //!     base_penalty_msat: 1000,
39 //!     failure_penalty_msat: 2 * 1024 * 1000,
40 //!     ..ScoringParameters::default()
41 //! });
42 //!
43 //! let route = find_route(&payer, &params, &network_graph, None, &logger, &scorer);
44 //! # }
45 //! ```
46 //!
47 //! # Note
48 //!
49 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
50 //! different types and thus is undefined.
51 //!
52 //! [`find_route`]: crate::routing::router::find_route
53
54 use ln::msgs::DecodeError;
55 use routing::network_graph::NodeId;
56 use routing::router::RouteHop;
57 use util::ser::{Readable, Writeable, Writer};
58
59 use prelude::*;
60 use core::cell::{RefCell, RefMut};
61 use core::ops::DerefMut;
62 use core::time::Duration;
63 use io::{self, Read};
64 use sync::{Mutex, MutexGuard};
65
66 /// We define Score ever-so-slightly differently based on whether we are being built for C bindings
67 /// or not. For users, `LockableScore` must somehow be writeable to disk. For Rust users, this is
68 /// no problem - you move a `Score` that implements `Writeable` into a `Mutex`, lock it, and now
69 /// you have the original, concrete, `Score` type, which presumably implements `Writeable`.
70 ///
71 /// For C users, once you've moved the `Score` into a `LockableScore` all you have after locking it
72 /// is an opaque trait object with an opaque pointer with no type info. Users could take the unsafe
73 /// approach of blindly casting that opaque pointer to a concrete type and calling `Writeable` from
74 /// there, but other languages downstream of the C bindings (e.g. Java) can't even do that.
75 /// Instead, we really want `Score` and `LockableScore` to implement `Writeable` directly, which we
76 /// do here by defining `Score` differently for `cfg(c_bindings)`.
77 macro_rules! define_score { ($($supertrait: path)*) => {
78 /// An interface used to score payment channels for path finding.
79 ///
80 ///     Scoring is in terms of fees willing to be paid in order to avoid routing through a channel.
81 pub trait Score $(: $supertrait)* {
82         /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
83         /// given channel in the direction from `source` to `target`.
84         ///
85         /// The channel's capacity (less any other MPP parts that are also being considered for use in
86         /// the same payment) is given by `capacity_msat`. It may be determined from various sources
87         /// such as a chain data, network gossip, or invoice hints, the latter indicating sufficient
88         /// capacity (i.e., near [`u64::max_value`]). Thus, implementations should be overflow-safe.
89         fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, source: &NodeId, target: &NodeId) -> u64;
90
91         /// Handles updating channel penalties after failing to route through a channel.
92         fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64);
93
94         /// Handles updating channel penalties after successfully routing along a path.
95         fn payment_path_successful(&mut self, path: &[&RouteHop]);
96 }
97
98 impl<S: Score, T: DerefMut<Target=S> $(+ $supertrait)*> Score for T {
99         fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, source: &NodeId, target: &NodeId) -> u64 {
100                 self.deref().channel_penalty_msat(short_channel_id, send_amt_msat, capacity_msat, source, target)
101         }
102
103         fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
104                 self.deref_mut().payment_path_failed(path, short_channel_id)
105         }
106
107         fn payment_path_successful(&mut self, path: &[&RouteHop]) {
108                 self.deref_mut().payment_path_successful(path)
109         }
110 }
111 } }
112
113 #[cfg(c_bindings)]
114 define_score!(Writeable);
115 #[cfg(not(c_bindings))]
116 define_score!();
117
118 /// A scorer that is accessed under a lock.
119 ///
120 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
121 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
122 /// implementations. Internal locking would be detrimental to route finding performance and could
123 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
124 ///
125 /// [`find_route`]: crate::routing::router::find_route
126 pub trait LockableScore<'a> {
127         /// The locked [`Score`] type.
128         type Locked: 'a + Score;
129
130         /// Returns the locked scorer.
131         fn lock(&'a self) -> Self::Locked;
132 }
133
134 /// (C-not exported)
135 impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
136         type Locked = MutexGuard<'a, T>;
137
138         fn lock(&'a self) -> MutexGuard<'a, T> {
139                 Mutex::lock(self).unwrap()
140         }
141 }
142
143 impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
144         type Locked = RefMut<'a, T>;
145
146         fn lock(&'a self) -> RefMut<'a, T> {
147                 self.borrow_mut()
148         }
149 }
150
151 #[cfg(c_bindings)]
152 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
153 pub struct MultiThreadedLockableScore<S: Score> {
154         score: Mutex<S>,
155 }
156 #[cfg(c_bindings)]
157 /// (C-not exported)
158 impl<'a, T: Score + 'a> LockableScore<'a> for MultiThreadedLockableScore<T> {
159         type Locked = MutexGuard<'a, T>;
160
161         fn lock(&'a self) -> MutexGuard<'a, T> {
162                 Mutex::lock(&self.score).unwrap()
163         }
164 }
165
166 #[cfg(c_bindings)]
167 impl<T: Score> MultiThreadedLockableScore<T> {
168         /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
169         pub fn new(score: T) -> Self {
170                 MultiThreadedLockableScore { score: Mutex::new(score) }
171         }
172 }
173
174 #[cfg(c_bindings)]
175 /// (C-not exported)
176 impl<'a, T: Writeable> Writeable for RefMut<'a, T> {
177         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
178                 T::write(&**self, writer)
179         }
180 }
181
182 #[cfg(c_bindings)]
183 /// (C-not exported)
184 impl<'a, S: Writeable> Writeable for MutexGuard<'a, S> {
185         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
186                 S::write(&**self, writer)
187         }
188 }
189
190 /// [`Score`] implementation that provides reasonable default behavior.
191 ///
192 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
193 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
194 ///
195 /// See [module-level documentation] for usage.
196 ///
197 /// [module-level documentation]: crate::routing::scoring
198 #[cfg(not(feature = "no-std"))]
199 pub type Scorer = ScorerUsingTime::<std::time::Instant>;
200 /// [`Score`] implementation that provides reasonable default behavior.
201 ///
202 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
203 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
204 ///
205 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
206 ///
207 /// [module-level documentation]: crate::routing::scoring
208 #[cfg(feature = "no-std")]
209 pub type Scorer = ScorerUsingTime::<time::Eternity>;
210
211 // Note that ideally we'd hide ScorerUsingTime from public view by sealing it as well, but rustdoc
212 // doesn't handle this well - instead exposing a `Scorer` which has no trait implementation(s) or
213 // methods at all.
214
215 /// [`Score`] implementation.
216 ///
217 /// See [`Scorer`] for details.
218 ///
219 /// # Note
220 ///
221 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
222 /// behavior.
223 ///
224 /// (C-not exported) generally all users should use the [`Scorer`] type alias.
225 pub struct ScorerUsingTime<T: Time> {
226         params: ScoringParameters,
227         // TODO: Remove entries of closed channels.
228         channel_failures: HashMap<u64, ChannelFailure<T>>,
229 }
230
231 /// Parameters for configuring [`Scorer`].
232 pub struct ScoringParameters {
233         /// A fixed penalty in msats to apply to each channel.
234         ///
235         /// Default value: 500 msat
236         pub base_penalty_msat: u64,
237
238         /// A penalty in msats to apply to a channel upon failing to relay a payment.
239         ///
240         /// This accumulates for each failure but may be reduced over time based on
241         /// [`failure_penalty_half_life`] or when successfully routing through a channel.
242         ///
243         /// Default value: 1,024,000 msat
244         ///
245         /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
246         pub failure_penalty_msat: u64,
247
248         /// When the amount being sent over a channel is this many 1024ths of the total channel
249         /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
250         ///
251         /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
252         ///
253         /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
254         pub overuse_penalty_start_1024th: u16,
255
256         /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
257         /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
258         ///
259         /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
260         ///                to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
261         ///
262         /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
263         pub overuse_penalty_msat_per_1024th: u64,
264
265         /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
266         /// cut in half.
267         ///
268         /// Successfully routing through a channel will immediately cut the penalty in half as well.
269         ///
270         /// # Note
271         ///
272         /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
273         /// never decay.
274         ///
275         /// [`failure_penalty_msat`]: Self::failure_penalty_msat
276         pub failure_penalty_half_life: Duration,
277 }
278
279 impl_writeable_tlv_based!(ScoringParameters, {
280         (0, base_penalty_msat, required),
281         (1, overuse_penalty_start_1024th, (default_value, 128)),
282         (2, failure_penalty_msat, required),
283         (3, overuse_penalty_msat_per_1024th, (default_value, 20)),
284         (4, failure_penalty_half_life, required),
285 });
286
287 /// Accounting for penalties against a channel for failing to relay any payments.
288 ///
289 /// Penalties decay over time, though accumulate as more failures occur.
290 struct ChannelFailure<T: Time> {
291         /// Accumulated penalty in msats for the channel as of `last_updated`.
292         undecayed_penalty_msat: u64,
293
294         /// Last time the channel either failed to route or successfully routed a payment. Used to decay
295         /// `undecayed_penalty_msat`.
296         last_updated: T,
297 }
298
299 impl<T: Time> ScorerUsingTime<T> {
300         /// Creates a new scorer using the given scoring parameters.
301         pub fn new(params: ScoringParameters) -> Self {
302                 Self {
303                         params,
304                         channel_failures: HashMap::new(),
305                 }
306         }
307
308         /// Creates a new scorer using `penalty_msat` as a fixed channel penalty.
309         #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
310         pub fn with_fixed_penalty(penalty_msat: u64) -> Self {
311                 Self::new(ScoringParameters {
312                         base_penalty_msat: penalty_msat,
313                         failure_penalty_msat: 0,
314                         failure_penalty_half_life: Duration::from_secs(0),
315                         overuse_penalty_start_1024th: 1024,
316                         overuse_penalty_msat_per_1024th: 0,
317                 })
318         }
319 }
320
321 impl<T: Time> ChannelFailure<T> {
322         fn new(failure_penalty_msat: u64) -> Self {
323                 Self {
324                         undecayed_penalty_msat: failure_penalty_msat,
325                         last_updated: T::now(),
326                 }
327         }
328
329         fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
330                 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
331                 self.last_updated = T::now();
332         }
333
334         fn reduce_penalty(&mut self, half_life: Duration) {
335                 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) >> 1;
336                 self.last_updated = T::now();
337         }
338
339         fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
340                 self.last_updated.elapsed().as_secs()
341                         .checked_div(half_life.as_secs())
342                         .and_then(|decays| self.undecayed_penalty_msat.checked_shr(decays as u32))
343                         .unwrap_or(0)
344         }
345 }
346
347 impl<T: Time> Default for ScorerUsingTime<T> {
348         fn default() -> Self {
349                 Self::new(ScoringParameters::default())
350         }
351 }
352
353 impl Default for ScoringParameters {
354         fn default() -> Self {
355                 Self {
356                         base_penalty_msat: 500,
357                         failure_penalty_msat: 1024 * 1000,
358                         failure_penalty_half_life: Duration::from_secs(3600),
359                         overuse_penalty_start_1024th: 1024 / 8,
360                         overuse_penalty_msat_per_1024th: 20,
361                 }
362         }
363 }
364
365 impl<T: Time> Score for ScorerUsingTime<T> {
366         fn channel_penalty_msat(
367                 &self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, _source: &NodeId, _target: &NodeId
368         ) -> u64 {
369                 let failure_penalty_msat = self.channel_failures
370                         .get(&short_channel_id)
371                         .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
372
373                 let mut penalty_msat = self.params.base_penalty_msat + failure_penalty_msat;
374                 let send_1024ths = send_amt_msat.checked_mul(1024).unwrap_or(u64::max_value()) / capacity_msat;
375                 if send_1024ths > self.params.overuse_penalty_start_1024th as u64 {
376                         penalty_msat = penalty_msat.checked_add(
377                                         (send_1024ths - self.params.overuse_penalty_start_1024th as u64)
378                                         .checked_mul(self.params.overuse_penalty_msat_per_1024th).unwrap_or(u64::max_value()))
379                                 .unwrap_or(u64::max_value());
380                 }
381
382                 penalty_msat
383         }
384
385         fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
386                 let failure_penalty_msat = self.params.failure_penalty_msat;
387                 let half_life = self.params.failure_penalty_half_life;
388                 self.channel_failures
389                         .entry(short_channel_id)
390                         .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
391                         .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
392         }
393
394         fn payment_path_successful(&mut self, path: &[&RouteHop]) {
395                 let half_life = self.params.failure_penalty_half_life;
396                 for hop in path.iter() {
397                         self.channel_failures
398                                 .entry(hop.short_channel_id)
399                                 .and_modify(|failure| failure.reduce_penalty(half_life));
400                 }
401         }
402 }
403
404 impl<T: Time> Writeable for ScorerUsingTime<T> {
405         #[inline]
406         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
407                 self.params.write(w)?;
408                 self.channel_failures.write(w)?;
409                 write_tlv_fields!(w, {});
410                 Ok(())
411         }
412 }
413
414 impl<T: Time> Readable for ScorerUsingTime<T> {
415         #[inline]
416         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
417                 let res = Ok(Self {
418                         params: Readable::read(r)?,
419                         channel_failures: Readable::read(r)?,
420                 });
421                 read_tlv_fields!(r, {});
422                 res
423         }
424 }
425
426 impl<T: Time> Writeable for ChannelFailure<T> {
427         #[inline]
428         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
429                 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
430                 write_tlv_fields!(w, {
431                         (0, self.undecayed_penalty_msat, required),
432                         (2, duration_since_epoch, required),
433                 });
434                 Ok(())
435         }
436 }
437
438 impl<T: Time> Readable for ChannelFailure<T> {
439         #[inline]
440         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
441                 let mut undecayed_penalty_msat = 0;
442                 let mut duration_since_epoch = Duration::from_secs(0);
443                 read_tlv_fields!(r, {
444                         (0, undecayed_penalty_msat, required),
445                         (2, duration_since_epoch, required),
446                 });
447                 Ok(Self {
448                         undecayed_penalty_msat,
449                         last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
450                 })
451         }
452 }
453
454 pub(crate) mod time {
455         use core::ops::Sub;
456         use core::time::Duration;
457         /// A measurement of time.
458         pub trait Time: Sub<Duration, Output = Self> where Self: Sized {
459                 /// Returns an instance corresponding to the current moment.
460                 fn now() -> Self;
461
462                 /// Returns the amount of time elapsed since `self` was created.
463                 fn elapsed(&self) -> Duration;
464
465                 /// Returns the amount of time passed since the beginning of [`Time`].
466                 ///
467                 /// Used during (de-)serialization.
468                 fn duration_since_epoch() -> Duration;
469         }
470
471         /// A state in which time has no meaning.
472         #[derive(Debug, PartialEq, Eq)]
473         pub struct Eternity;
474
475         #[cfg(not(feature = "no-std"))]
476         impl Time for std::time::Instant {
477                 fn now() -> Self {
478                         std::time::Instant::now()
479                 }
480
481                 fn duration_since_epoch() -> Duration {
482                         use std::time::SystemTime;
483                         SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
484                 }
485
486                 fn elapsed(&self) -> Duration {
487                         std::time::Instant::elapsed(self)
488                 }
489         }
490
491         impl Time for Eternity {
492                 fn now() -> Self {
493                         Self
494                 }
495
496                 fn duration_since_epoch() -> Duration {
497                         Duration::from_secs(0)
498                 }
499
500                 fn elapsed(&self) -> Duration {
501                         Duration::from_secs(0)
502                 }
503         }
504
505         impl Sub<Duration> for Eternity {
506                 type Output = Self;
507
508                 fn sub(self, _other: Duration) -> Self {
509                         self
510                 }
511         }
512 }
513
514 pub(crate) use self::time::Time;
515
516 #[cfg(test)]
517 mod tests {
518         use super::{ScoringParameters, ScorerUsingTime, Time};
519         use super::time::Eternity;
520
521         use ln::features::{ChannelFeatures, NodeFeatures};
522         use routing::scoring::Score;
523         use routing::network_graph::NodeId;
524         use routing::router::RouteHop;
525         use util::ser::{Readable, Writeable};
526
527         use bitcoin::secp256k1::PublicKey;
528         use core::cell::Cell;
529         use core::ops::Sub;
530         use core::time::Duration;
531         use io;
532
533         /// Time that can be advanced manually in tests.
534         #[derive(Debug, PartialEq, Eq)]
535         struct SinceEpoch(Duration);
536
537         impl SinceEpoch {
538                 thread_local! {
539                         static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
540                 }
541
542                 fn advance(duration: Duration) {
543                         Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
544                 }
545         }
546
547         impl Time for SinceEpoch {
548                 fn now() -> Self {
549                         Self(Self::duration_since_epoch())
550                 }
551
552                 fn duration_since_epoch() -> Duration {
553                         Self::ELAPSED.with(|elapsed| elapsed.get())
554                 }
555
556                 fn elapsed(&self) -> Duration {
557                         Self::duration_since_epoch() - self.0
558                 }
559         }
560
561         impl Sub<Duration> for SinceEpoch {
562                 type Output = Self;
563
564                 fn sub(self, other: Duration) -> Self {
565                         Self(self.0 - other)
566                 }
567         }
568
569         #[test]
570         fn time_passes_when_advanced() {
571                 let now = SinceEpoch::now();
572                 assert_eq!(now.elapsed(), Duration::from_secs(0));
573
574                 SinceEpoch::advance(Duration::from_secs(1));
575                 SinceEpoch::advance(Duration::from_secs(1));
576
577                 let elapsed = now.elapsed();
578                 let later = SinceEpoch::now();
579
580                 assert_eq!(elapsed, Duration::from_secs(2));
581                 assert_eq!(later - elapsed, now);
582         }
583
584         #[test]
585         fn time_never_passes_in_an_eternity() {
586                 let now = Eternity::now();
587                 let elapsed = now.elapsed();
588                 let later = Eternity::now();
589
590                 assert_eq!(now.elapsed(), Duration::from_secs(0));
591                 assert_eq!(later - elapsed, now);
592         }
593
594         /// A scorer for testing with time that can be manually advanced.
595         type Scorer = ScorerUsingTime::<SinceEpoch>;
596
597         fn source_node_id() -> NodeId {
598                 NodeId::from_pubkey(&PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap())
599         }
600
601         fn target_node_id() -> NodeId {
602                 NodeId::from_pubkey(&PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap())
603         }
604
605         #[test]
606         fn penalizes_without_channel_failures() {
607                 let scorer = Scorer::new(ScoringParameters {
608                         base_penalty_msat: 1_000,
609                         failure_penalty_msat: 512,
610                         failure_penalty_half_life: Duration::from_secs(1),
611                         overuse_penalty_start_1024th: 1024,
612                         overuse_penalty_msat_per_1024th: 0,
613                 });
614                 let source = source_node_id();
615                 let target = target_node_id();
616                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
617
618                 SinceEpoch::advance(Duration::from_secs(1));
619                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
620         }
621
622         #[test]
623         fn accumulates_channel_failure_penalties() {
624                 let mut scorer = Scorer::new(ScoringParameters {
625                         base_penalty_msat: 1_000,
626                         failure_penalty_msat: 64,
627                         failure_penalty_half_life: Duration::from_secs(10),
628                         overuse_penalty_start_1024th: 1024,
629                         overuse_penalty_msat_per_1024th: 0,
630                 });
631                 let source = source_node_id();
632                 let target = target_node_id();
633                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
634
635                 scorer.payment_path_failed(&[], 42);
636                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
637
638                 scorer.payment_path_failed(&[], 42);
639                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
640
641                 scorer.payment_path_failed(&[], 42);
642                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_192);
643         }
644
645         #[test]
646         fn decays_channel_failure_penalties_over_time() {
647                 let mut scorer = Scorer::new(ScoringParameters {
648                         base_penalty_msat: 1_000,
649                         failure_penalty_msat: 512,
650                         failure_penalty_half_life: Duration::from_secs(10),
651                         overuse_penalty_start_1024th: 1024,
652                         overuse_penalty_msat_per_1024th: 0,
653                 });
654                 let source = source_node_id();
655                 let target = target_node_id();
656                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
657
658                 scorer.payment_path_failed(&[], 42);
659                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
660
661                 SinceEpoch::advance(Duration::from_secs(9));
662                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
663
664                 SinceEpoch::advance(Duration::from_secs(1));
665                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
666
667                 SinceEpoch::advance(Duration::from_secs(10 * 8));
668                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_001);
669
670                 SinceEpoch::advance(Duration::from_secs(10));
671                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
672
673                 SinceEpoch::advance(Duration::from_secs(10));
674                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
675         }
676
677         #[test]
678         fn decays_channel_failure_penalties_without_shift_overflow() {
679                 let mut scorer = Scorer::new(ScoringParameters {
680                         base_penalty_msat: 1_000,
681                         failure_penalty_msat: 512,
682                         failure_penalty_half_life: Duration::from_secs(10),
683                         overuse_penalty_start_1024th: 1024,
684                         overuse_penalty_msat_per_1024th: 0,
685                 });
686                 let source = source_node_id();
687                 let target = target_node_id();
688                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
689
690                 scorer.payment_path_failed(&[], 42);
691                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
692
693                 // An unchecked right shift 64 bits or more in ChannelFailure::decayed_penalty_msat would
694                 // cause an overflow.
695                 SinceEpoch::advance(Duration::from_secs(10 * 64));
696                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
697
698                 SinceEpoch::advance(Duration::from_secs(10));
699                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
700         }
701
702         #[test]
703         fn accumulates_channel_failure_penalties_after_decay() {
704                 let mut scorer = Scorer::new(ScoringParameters {
705                         base_penalty_msat: 1_000,
706                         failure_penalty_msat: 512,
707                         failure_penalty_half_life: Duration::from_secs(10),
708                         overuse_penalty_start_1024th: 1024,
709                         overuse_penalty_msat_per_1024th: 0,
710                 });
711                 let source = source_node_id();
712                 let target = target_node_id();
713                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
714
715                 scorer.payment_path_failed(&[], 42);
716                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
717
718                 SinceEpoch::advance(Duration::from_secs(10));
719                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
720
721                 scorer.payment_path_failed(&[], 42);
722                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_768);
723
724                 SinceEpoch::advance(Duration::from_secs(10));
725                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_384);
726         }
727
728         #[test]
729         fn reduces_channel_failure_penalties_after_success() {
730                 let mut scorer = Scorer::new(ScoringParameters {
731                         base_penalty_msat: 1_000,
732                         failure_penalty_msat: 512,
733                         failure_penalty_half_life: Duration::from_secs(10),
734                         overuse_penalty_start_1024th: 1024,
735                         overuse_penalty_msat_per_1024th: 0,
736                 });
737                 let source = source_node_id();
738                 let target = target_node_id();
739                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
740
741                 scorer.payment_path_failed(&[], 42);
742                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
743
744                 SinceEpoch::advance(Duration::from_secs(10));
745                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
746
747                 let hop = RouteHop {
748                         pubkey: PublicKey::from_slice(target.as_slice()).unwrap(),
749                         node_features: NodeFeatures::known(),
750                         short_channel_id: 42,
751                         channel_features: ChannelFeatures::known(),
752                         fee_msat: 1,
753                         cltv_expiry_delta: 18,
754                 };
755                 scorer.payment_path_successful(&[&hop]);
756                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
757
758                 SinceEpoch::advance(Duration::from_secs(10));
759                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
760         }
761
762         #[test]
763         fn restores_persisted_channel_failure_penalties() {
764                 let mut scorer = Scorer::new(ScoringParameters {
765                         base_penalty_msat: 1_000,
766                         failure_penalty_msat: 512,
767                         failure_penalty_half_life: Duration::from_secs(10),
768                         overuse_penalty_start_1024th: 1024,
769                         overuse_penalty_msat_per_1024th: 0,
770                 });
771                 let source = source_node_id();
772                 let target = target_node_id();
773
774                 scorer.payment_path_failed(&[], 42);
775                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
776
777                 SinceEpoch::advance(Duration::from_secs(10));
778                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
779
780                 scorer.payment_path_failed(&[], 43);
781                 assert_eq!(scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
782
783                 let mut serialized_scorer = Vec::new();
784                 scorer.write(&mut serialized_scorer).unwrap();
785
786                 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
787                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
788                 assert_eq!(deserialized_scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
789         }
790
791         #[test]
792         fn decays_persisted_channel_failure_penalties() {
793                 let mut scorer = Scorer::new(ScoringParameters {
794                         base_penalty_msat: 1_000,
795                         failure_penalty_msat: 512,
796                         failure_penalty_half_life: Duration::from_secs(10),
797                         overuse_penalty_start_1024th: 1024,
798                         overuse_penalty_msat_per_1024th: 0,
799                 });
800                 let source = source_node_id();
801                 let target = target_node_id();
802
803                 scorer.payment_path_failed(&[], 42);
804                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
805
806                 let mut serialized_scorer = Vec::new();
807                 scorer.write(&mut serialized_scorer).unwrap();
808
809                 SinceEpoch::advance(Duration::from_secs(10));
810
811                 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
812                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
813
814                 SinceEpoch::advance(Duration::from_secs(10));
815                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
816         }
817
818         #[test]
819         fn charges_per_1024th_penalty() {
820                 let scorer = Scorer::new(ScoringParameters {
821                         base_penalty_msat: 0,
822                         failure_penalty_msat: 0,
823                         failure_penalty_half_life: Duration::from_secs(0),
824                         overuse_penalty_start_1024th: 256,
825                         overuse_penalty_msat_per_1024th: 100,
826                 });
827                 let source = source_node_id();
828                 let target = target_node_id();
829
830                 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 1_024_000, &source, &target), 0);
831                 assert_eq!(scorer.channel_penalty_msat(42, 256_999, 1_024_000, &source, &target), 0);
832                 assert_eq!(scorer.channel_penalty_msat(42, 257_000, 1_024_000, &source, &target), 100);
833                 assert_eq!(scorer.channel_penalty_msat(42, 258_000, 1_024_000, &source, &target), 200);
834                 assert_eq!(scorer.channel_penalty_msat(42, 512_000, 1_024_000, &source, &target), 256 * 100);
835         }
836 }