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