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