Merge pull request #1166 from TheBlueMatt/2021-11-chan-size-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 //! If persisting [`Scorer`], it must be restored using the same [`Time`] parameterization. Using a
50 //! different type results in undefined behavior. Specifically, persisting when built with feature
51 //! `no-std` and restoring without it, or vice versa, uses different types and thus is undefined.
52 //!
53 //! [`find_route`]: crate::routing::router::find_route
54
55 use ln::msgs::DecodeError;
56 use routing::network_graph::NodeId;
57 use routing::router::RouteHop;
58 use util::ser::{Readable, Writeable, Writer};
59
60 use prelude::*;
61 use core::cell::{RefCell, RefMut};
62 use core::ops::{DerefMut, Sub};
63 use core::time::Duration;
64 use io::{self, Read}; use sync::{Mutex, MutexGuard};
65
66 /// An interface used to score payment channels for path finding.
67 ///
68 ///     Scoring is in terms of fees willing to be paid in order to avoid routing through a channel.
69 pub trait Score {
70         /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
71         /// given channel in the direction from `source` to `target`.
72         ///
73         /// The channel's capacity (less any other MPP parts which are also being considered for use in
74         /// the same payment) is given by `channel_capacity_msat`. It may be guessed from various
75         /// sources or assumed from no data at all.
76         ///
77         /// For hints provided in the invoice, we assume the channel has sufficient capacity to accept
78         /// the invoice's full amount, and provide a `channel_capacity_msat` of `None`. In all other
79         /// cases it is set to `Some`, even if we're guessing at the channel value.
80         ///
81         /// Your code should be overflow-safe through a `channel_capacity_msat` of 21 million BTC.
82         fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, channel_capacity_msat: Option<u64>, source: &NodeId, target: &NodeId) -> u64;
83
84         /// Handles updating channel penalties after failing to route through a channel.
85         fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64);
86 }
87
88 /// A scorer that is accessed under a lock.
89 ///
90 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
91 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
92 /// implementations. Internal locking would be detrimental to route finding performance and could
93 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
94 ///
95 /// [`find_route`]: crate::routing::router::find_route
96 pub trait LockableScore<'a> {
97         /// The locked [`Score`] type.
98         type Locked: 'a + Score;
99
100         /// Returns the locked scorer.
101         fn lock(&'a self) -> Self::Locked;
102 }
103
104 impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
105         type Locked = MutexGuard<'a, T>;
106
107         fn lock(&'a self) -> MutexGuard<'a, T> {
108                 Mutex::lock(self).unwrap()
109         }
110 }
111
112 impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
113         type Locked = RefMut<'a, T>;
114
115         fn lock(&'a self) -> RefMut<'a, T> {
116                 self.borrow_mut()
117         }
118 }
119
120 impl<S: Score, T: DerefMut<Target=S>> Score for T {
121         fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, channel_capacity_msat: Option<u64>, source: &NodeId, target: &NodeId) -> u64 {
122                 self.deref().channel_penalty_msat(short_channel_id, send_amt_msat, channel_capacity_msat, source, target)
123         }
124
125         fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
126                 self.deref_mut().payment_path_failed(path, short_channel_id)
127         }
128 }
129
130 /// [`Score`] implementation that provides reasonable default behavior.
131 ///
132 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
133 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
134 ///
135 /// See [module-level documentation] for usage.
136 ///
137 /// [module-level documentation]: crate::routing::scoring
138 pub type Scorer = ScorerUsingTime::<DefaultTime>;
139
140 /// Time used by [`Scorer`].
141 #[cfg(not(feature = "no-std"))]
142 pub type DefaultTime = std::time::Instant;
143
144 /// Time used by [`Scorer`].
145 #[cfg(feature = "no-std")]
146 pub type DefaultTime = Eternity;
147
148 /// [`Score`] implementation parameterized by [`Time`].
149 ///
150 /// See [`Scorer`] for details.
151 ///
152 /// # Note
153 ///
154 /// Mixing [`Time`] types between serialization and deserialization results in undefined behavior.
155 pub struct ScorerUsingTime<T: Time> {
156         params: ScoringParameters,
157         // TODO: Remove entries of closed channels.
158         channel_failures: HashMap<u64, ChannelFailure<T>>,
159 }
160
161 /// Parameters for configuring [`Scorer`].
162 pub struct ScoringParameters {
163         /// A fixed penalty in msats to apply to each channel.
164         ///
165         /// Default value: 500 msat
166         pub base_penalty_msat: u64,
167
168         /// A penalty in msats to apply to a channel upon failing to relay a payment.
169         ///
170         /// This accumulates for each failure but may be reduced over time based on
171         /// [`failure_penalty_half_life`].
172         ///
173         /// Default value: 1,024,000 msat
174         ///
175         /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
176         pub failure_penalty_msat: u64,
177
178         /// When the amount being sent over a channel is this many 1024ths of the total channel
179         /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
180         ///
181         /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
182         ///
183         /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
184         pub overuse_penalty_start_1024th: u16,
185
186         /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
187         /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
188         ///
189         /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
190         ///                to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
191         ///
192         /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
193         pub overuse_penalty_msat_per_1024th: u64,
194
195         /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
196         /// cut in half.
197         ///
198         /// # Note
199         ///
200         /// When time is an [`Eternity`], as is default when enabling feature `no-std`, it will never
201         /// elapse. Therefore, this penalty will never decay.
202         ///
203         /// [`failure_penalty_msat`]: Self::failure_penalty_msat
204         pub failure_penalty_half_life: Duration,
205 }
206
207 impl_writeable_tlv_based!(ScoringParameters, {
208         (0, base_penalty_msat, required),
209         (1, overuse_penalty_start_1024th, (default_value, 128)),
210         (2, failure_penalty_msat, required),
211         (3, overuse_penalty_msat_per_1024th, (default_value, 20)),
212         (4, failure_penalty_half_life, required),
213 });
214
215 /// Accounting for penalties against a channel for failing to relay any payments.
216 ///
217 /// Penalties decay over time, though accumulate as more failures occur.
218 struct ChannelFailure<T: Time> {
219         /// Accumulated penalty in msats for the channel as of `last_failed`.
220         undecayed_penalty_msat: u64,
221
222         /// Last time the channel failed. Used to decay `undecayed_penalty_msat`.
223         last_failed: T,
224 }
225
226 /// A measurement of time.
227 pub trait Time: Sub<Duration, Output = Self> where Self: Sized {
228         /// Returns an instance corresponding to the current moment.
229         fn now() -> Self;
230
231         /// Returns the amount of time elapsed since `self` was created.
232         fn elapsed(&self) -> Duration;
233
234         /// Returns the amount of time passed since the beginning of [`Time`].
235         ///
236         /// Used during (de-)serialization.
237         fn duration_since_epoch() -> Duration;
238 }
239
240 impl<T: Time> ScorerUsingTime<T> {
241         /// Creates a new scorer using the given scoring parameters.
242         pub fn new(params: ScoringParameters) -> Self {
243                 Self {
244                         params,
245                         channel_failures: HashMap::new(),
246                 }
247         }
248
249         /// Creates a new scorer using `penalty_msat` as a fixed channel penalty.
250         #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
251         pub fn with_fixed_penalty(penalty_msat: u64) -> Self {
252                 Self::new(ScoringParameters {
253                         base_penalty_msat: penalty_msat,
254                         failure_penalty_msat: 0,
255                         failure_penalty_half_life: Duration::from_secs(0),
256                         overuse_penalty_start_1024th: 1024,
257                         overuse_penalty_msat_per_1024th: 0,
258                 })
259         }
260 }
261
262 impl<T: Time> ChannelFailure<T> {
263         fn new(failure_penalty_msat: u64) -> Self {
264                 Self {
265                         undecayed_penalty_msat: failure_penalty_msat,
266                         last_failed: T::now(),
267                 }
268         }
269
270         fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
271                 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
272                 self.last_failed = T::now();
273         }
274
275         fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
276                 let decays = self.last_failed.elapsed().as_secs().checked_div(half_life.as_secs());
277                 match decays {
278                         Some(decays) => self.undecayed_penalty_msat >> decays,
279                         None => 0,
280                 }
281         }
282 }
283
284 impl<T: Time> Default for ScorerUsingTime<T> {
285         fn default() -> Self {
286                 Self::new(ScoringParameters::default())
287         }
288 }
289
290 impl Default for ScoringParameters {
291         fn default() -> Self {
292                 Self {
293                         base_penalty_msat: 500,
294                         failure_penalty_msat: 1024 * 1000,
295                         failure_penalty_half_life: Duration::from_secs(3600),
296                         overuse_penalty_start_1024th: 1024 / 8,
297                         overuse_penalty_msat_per_1024th: 20,
298                 }
299         }
300 }
301
302 impl<T: Time> Score for ScorerUsingTime<T> {
303         fn channel_penalty_msat(
304                 &self, short_channel_id: u64, send_amt_msat: u64, chan_capacity_opt: Option<u64>, _source: &NodeId, _target: &NodeId
305         ) -> u64 {
306                 let failure_penalty_msat = self.channel_failures
307                         .get(&short_channel_id)
308                         .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
309
310                 let mut penalty_msat = self.params.base_penalty_msat + failure_penalty_msat;
311
312                 if let Some(chan_capacity_msat) = chan_capacity_opt {
313                         let send_1024ths = send_amt_msat.checked_mul(1024).unwrap_or(u64::max_value()) / chan_capacity_msat;
314
315                         if send_1024ths > self.params.overuse_penalty_start_1024th as u64 {
316                                 penalty_msat = penalty_msat.checked_add(
317                                                 (send_1024ths - self.params.overuse_penalty_start_1024th as u64)
318                                                 .checked_mul(self.params.overuse_penalty_msat_per_1024th).unwrap_or(u64::max_value()))
319                                         .unwrap_or(u64::max_value());
320                         }
321                 }
322
323                 penalty_msat
324         }
325
326         fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
327                 let failure_penalty_msat = self.params.failure_penalty_msat;
328                 let half_life = self.params.failure_penalty_half_life;
329                 self.channel_failures
330                         .entry(short_channel_id)
331                         .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
332                         .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
333         }
334 }
335
336 #[cfg(not(feature = "no-std"))]
337 impl Time for std::time::Instant {
338         fn now() -> Self {
339                 std::time::Instant::now()
340         }
341
342         fn duration_since_epoch() -> Duration {
343                 use std::time::SystemTime;
344                 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
345         }
346
347         fn elapsed(&self) -> Duration {
348                 std::time::Instant::elapsed(self)
349         }
350 }
351
352 /// A state in which time has no meaning.
353 #[derive(Debug, PartialEq, Eq)]
354 pub struct Eternity;
355
356 impl Time for Eternity {
357         fn now() -> Self {
358                 Self
359         }
360
361         fn duration_since_epoch() -> Duration {
362                 Duration::from_secs(0)
363         }
364
365         fn elapsed(&self) -> Duration {
366                 Duration::from_secs(0)
367         }
368 }
369
370 impl Sub<Duration> for Eternity {
371         type Output = Self;
372
373         fn sub(self, _other: Duration) -> Self {
374                 self
375         }
376 }
377
378 impl<T: Time> Writeable for ScorerUsingTime<T> {
379         #[inline]
380         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
381                 self.params.write(w)?;
382                 self.channel_failures.write(w)?;
383                 write_tlv_fields!(w, {});
384                 Ok(())
385         }
386 }
387
388 impl<T: Time> Readable for ScorerUsingTime<T> {
389         #[inline]
390         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
391                 let res = Ok(Self {
392                         params: Readable::read(r)?,
393                         channel_failures: Readable::read(r)?,
394                 });
395                 read_tlv_fields!(r, {});
396                 res
397         }
398 }
399
400 impl<T: Time> Writeable for ChannelFailure<T> {
401         #[inline]
402         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
403                 let duration_since_epoch = T::duration_since_epoch() - self.last_failed.elapsed();
404                 write_tlv_fields!(w, {
405                         (0, self.undecayed_penalty_msat, required),
406                         (2, duration_since_epoch, required),
407                 });
408                 Ok(())
409         }
410 }
411
412 impl<T: Time> Readable for ChannelFailure<T> {
413         #[inline]
414         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
415                 let mut undecayed_penalty_msat = 0;
416                 let mut duration_since_epoch = Duration::from_secs(0);
417                 read_tlv_fields!(r, {
418                         (0, undecayed_penalty_msat, required),
419                         (2, duration_since_epoch, required),
420                 });
421                 Ok(Self {
422                         undecayed_penalty_msat,
423                         last_failed: T::now() - (T::duration_since_epoch() - duration_since_epoch),
424                 })
425         }
426 }
427
428 #[cfg(test)]
429 mod tests {
430         use super::{Eternity, ScoringParameters, ScorerUsingTime, Time};
431
432         use routing::scoring::Score;
433         use routing::network_graph::NodeId;
434         use util::ser::{Readable, Writeable};
435
436         use bitcoin::secp256k1::PublicKey;
437         use core::cell::Cell;
438         use core::ops::Sub;
439         use core::time::Duration;
440         use io;
441
442         /// Time that can be advanced manually in tests.
443         #[derive(Debug, PartialEq, Eq)]
444         struct SinceEpoch(Duration);
445
446         impl SinceEpoch {
447                 thread_local! {
448                         static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
449                 }
450
451                 fn advance(duration: Duration) {
452                         Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
453                 }
454         }
455
456         impl Time for SinceEpoch {
457                 fn now() -> Self {
458                         Self(Self::duration_since_epoch())
459                 }
460
461                 fn duration_since_epoch() -> Duration {
462                         Self::ELAPSED.with(|elapsed| elapsed.get())
463                 }
464
465                 fn elapsed(&self) -> Duration {
466                         Self::duration_since_epoch() - self.0
467                 }
468         }
469
470         impl Sub<Duration> for SinceEpoch {
471                 type Output = Self;
472
473                 fn sub(self, other: Duration) -> Self {
474                         Self(self.0 - other)
475                 }
476         }
477
478         #[test]
479         fn time_passes_when_advanced() {
480                 let now = SinceEpoch::now();
481                 assert_eq!(now.elapsed(), Duration::from_secs(0));
482
483                 SinceEpoch::advance(Duration::from_secs(1));
484                 SinceEpoch::advance(Duration::from_secs(1));
485
486                 let elapsed = now.elapsed();
487                 let later = SinceEpoch::now();
488
489                 assert_eq!(elapsed, Duration::from_secs(2));
490                 assert_eq!(later - elapsed, now);
491         }
492
493         #[test]
494         fn time_never_passes_in_an_eternity() {
495                 let now = Eternity::now();
496                 let elapsed = now.elapsed();
497                 let later = Eternity::now();
498
499                 assert_eq!(now.elapsed(), Duration::from_secs(0));
500                 assert_eq!(later - elapsed, now);
501         }
502
503         /// A scorer for testing with time that can be manually advanced.
504         type Scorer = ScorerUsingTime::<SinceEpoch>;
505
506         fn source_node_id() -> NodeId {
507                 NodeId::from_pubkey(&PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap())
508         }
509
510         fn target_node_id() -> NodeId {
511                 NodeId::from_pubkey(&PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap())
512         }
513
514         #[test]
515         fn penalizes_without_channel_failures() {
516                 let scorer = Scorer::new(ScoringParameters {
517                         base_penalty_msat: 1_000,
518                         failure_penalty_msat: 512,
519                         failure_penalty_half_life: Duration::from_secs(1),
520                         overuse_penalty_start_1024th: 1024,
521                         overuse_penalty_msat_per_1024th: 0,
522                 });
523                 let source = source_node_id();
524                 let target = target_node_id();
525                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
526
527                 SinceEpoch::advance(Duration::from_secs(1));
528                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
529         }
530
531         #[test]
532         fn accumulates_channel_failure_penalties() {
533                 let mut scorer = Scorer::new(ScoringParameters {
534                         base_penalty_msat: 1_000,
535                         failure_penalty_msat: 64,
536                         failure_penalty_half_life: Duration::from_secs(10),
537                         overuse_penalty_start_1024th: 1024,
538                         overuse_penalty_msat_per_1024th: 0,
539                 });
540                 let source = source_node_id();
541                 let target = target_node_id();
542                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
543
544                 scorer.payment_path_failed(&[], 42);
545                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_064);
546
547                 scorer.payment_path_failed(&[], 42);
548                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_128);
549
550                 scorer.payment_path_failed(&[], 42);
551                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_192);
552         }
553
554         #[test]
555         fn decays_channel_failure_penalties_over_time() {
556                 let mut scorer = Scorer::new(ScoringParameters {
557                         base_penalty_msat: 1_000,
558                         failure_penalty_msat: 512,
559                         failure_penalty_half_life: Duration::from_secs(10),
560                         overuse_penalty_start_1024th: 1024,
561                         overuse_penalty_msat_per_1024th: 0,
562                 });
563                 let source = source_node_id();
564                 let target = target_node_id();
565                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
566
567                 scorer.payment_path_failed(&[], 42);
568                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
569
570                 SinceEpoch::advance(Duration::from_secs(9));
571                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
572
573                 SinceEpoch::advance(Duration::from_secs(1));
574                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
575
576                 SinceEpoch::advance(Duration::from_secs(10 * 8));
577                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_001);
578
579                 SinceEpoch::advance(Duration::from_secs(10));
580                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
581
582                 SinceEpoch::advance(Duration::from_secs(10));
583                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
584         }
585
586         #[test]
587         fn accumulates_channel_failure_penalties_after_decay() {
588                 let mut scorer = Scorer::new(ScoringParameters {
589                         base_penalty_msat: 1_000,
590                         failure_penalty_msat: 512,
591                         failure_penalty_half_life: Duration::from_secs(10),
592                         overuse_penalty_start_1024th: 1024,
593                         overuse_penalty_msat_per_1024th: 0,
594                 });
595                 let source = source_node_id();
596                 let target = target_node_id();
597                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
598
599                 scorer.payment_path_failed(&[], 42);
600                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
601
602                 SinceEpoch::advance(Duration::from_secs(10));
603                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
604
605                 scorer.payment_path_failed(&[], 42);
606                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_768);
607
608                 SinceEpoch::advance(Duration::from_secs(10));
609                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_384);
610         }
611
612         #[test]
613         fn restores_persisted_channel_failure_penalties() {
614                 let mut scorer = Scorer::new(ScoringParameters {
615                         base_penalty_msat: 1_000,
616                         failure_penalty_msat: 512,
617                         failure_penalty_half_life: Duration::from_secs(10),
618                         overuse_penalty_start_1024th: 1024,
619                         overuse_penalty_msat_per_1024th: 0,
620                 });
621                 let source = source_node_id();
622                 let target = target_node_id();
623
624                 scorer.payment_path_failed(&[], 42);
625                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
626
627                 SinceEpoch::advance(Duration::from_secs(10));
628                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
629
630                 scorer.payment_path_failed(&[], 43);
631                 assert_eq!(scorer.channel_penalty_msat(43, 1, Some(1), &source, &target), 1_512);
632
633                 let mut serialized_scorer = Vec::new();
634                 scorer.write(&mut serialized_scorer).unwrap();
635
636                 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
637                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
638                 assert_eq!(deserialized_scorer.channel_penalty_msat(43, 1, Some(1), &source, &target), 1_512);
639         }
640
641         #[test]
642         fn decays_persisted_channel_failure_penalties() {
643                 let mut scorer = Scorer::new(ScoringParameters {
644                         base_penalty_msat: 1_000,
645                         failure_penalty_msat: 512,
646                         failure_penalty_half_life: Duration::from_secs(10),
647                         overuse_penalty_start_1024th: 1024,
648                         overuse_penalty_msat_per_1024th: 0,
649                 });
650                 let source = source_node_id();
651                 let target = target_node_id();
652
653                 scorer.payment_path_failed(&[], 42);
654                 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
655
656                 let mut serialized_scorer = Vec::new();
657                 scorer.write(&mut serialized_scorer).unwrap();
658
659                 SinceEpoch::advance(Duration::from_secs(10));
660
661                 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
662                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
663
664                 SinceEpoch::advance(Duration::from_secs(10));
665                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_128);
666         }
667
668         #[test]
669         fn charges_per_1024th_penalty() {
670                 let scorer = Scorer::new(ScoringParameters {
671                         base_penalty_msat: 0,
672                         failure_penalty_msat: 0,
673                         failure_penalty_half_life: Duration::from_secs(0),
674                         overuse_penalty_start_1024th: 256,
675                         overuse_penalty_msat_per_1024th: 100,
676                 });
677                 let source = source_node_id();
678                 let target = target_node_id();
679
680                 assert_eq!(scorer.channel_penalty_msat(42, 1_000, None, &source, &target), 0);
681                 assert_eq!(scorer.channel_penalty_msat(42, 1_000, Some(1_024_000), &source, &target), 0);
682                 assert_eq!(scorer.channel_penalty_msat(42, 256_999, Some(1_024_000), &source, &target), 0);
683                 assert_eq!(scorer.channel_penalty_msat(42, 257_000, Some(1_024_000), &source, &target), 100);
684                 assert_eq!(scorer.channel_penalty_msat(42, 258_000, Some(1_024_000), &source, &target), 200);
685                 assert_eq!(scorer.channel_penalty_msat(42, 512_000, Some(1_024_000), &source, &target), 256 * 100);
686         }
687 }