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