1 // This file is Copyright its original authors, visible in version control
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
10 //! Utilities for scoring payment channels.
12 //! [`Scorer`] may be given to [`find_route`] to score payment channels during path finding when a
13 //! custom [`Score`] implementation is not needed.
18 //! # extern crate secp256k1;
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;
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! # fn log(&self, record: &Record) { unimplemented!() }
30 //! # fn find_scored_route(payer: PublicKey, params: RouteParameters, network_graph: NetworkGraph) {
31 //! # let logger = FakeLogger {};
33 //! // Use the default channel penalties.
34 //! let scorer = Scorer::default();
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()
43 //! let route = find_route(&payer, ¶ms, &network_graph, None, &logger, &scorer);
49 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
50 //! different types and thus is undefined.
52 //! [`find_route`]: crate::routing::router::find_route
54 use ln::msgs::DecodeError;
55 use routing::network_graph::NodeId;
56 use routing::router::RouteHop;
57 use util::ser::{Readable, Writeable, Writer};
60 use core::cell::{RefCell, RefMut};
61 use core::ops::DerefMut;
62 use core::time::Duration;
64 use sync::{Mutex, MutexGuard};
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`.
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.
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`.
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.
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.
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;
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);
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)
105 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
106 self.deref_mut().payment_path_failed(path, short_channel_id)
112 define_score!(Writeable);
113 #[cfg(not(c_bindings))]
116 /// A scorer that is accessed under a lock.
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.
123 /// [`find_route`]: crate::routing::router::find_route
124 pub trait LockableScore<'a> {
125 /// The locked [`Score`] type.
126 type Locked: 'a + Score;
128 /// Returns the locked scorer.
129 fn lock(&'a self) -> Self::Locked;
133 impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
134 type Locked = MutexGuard<'a, T>;
136 fn lock(&'a self) -> MutexGuard<'a, T> {
137 Mutex::lock(self).unwrap()
141 impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
142 type Locked = RefMut<'a, T>;
144 fn lock(&'a self) -> RefMut<'a, T> {
150 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
151 pub struct MultiThreadedLockableScore<S: Score> {
156 impl<'a, T: Score + 'a> LockableScore<'a> for MultiThreadedLockableScore<T> {
157 type Locked = MutexGuard<'a, T>;
159 fn lock(&'a self) -> MutexGuard<'a, T> {
160 Mutex::lock(&self.score).unwrap()
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)
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)
180 /// [`Score`] implementation that provides reasonable default behavior.
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.
185 /// See [module-level documentation] for usage.
187 /// [module-level documentation]: crate::routing::scoring
188 #[cfg(not(feature = "no-std"))]
189 pub type Scorer = ScorerUsingTime::<std::time::Instant>;
190 /// [`Score`] implementation that provides reasonable default behavior.
192 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
193 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
195 /// See [module-level documentation] for usage.
197 /// [module-level documentation]: crate::routing::scoring
198 #[cfg(feature = "no-std")]
199 pub type Scorer = ScorerUsingTime::<time::Eternity>;
201 // Note that ideally we'd hide ScorerUsingTime from public view by sealing it as well, but rustdoc
202 // doesn't handle this well - instead exposing a `Scorer` which has no trait implementation(s) or
205 /// [`Score`] implementation.
207 /// See [`Scorer`] for details.
211 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
214 /// (C-not exported) generally all users should use the [`Scorer`] type alias.
215 pub struct ScorerUsingTime<T: Time> {
216 params: ScoringParameters,
217 // TODO: Remove entries of closed channels.
218 channel_failures: HashMap<u64, ChannelFailure<T>>,
221 /// Parameters for configuring [`Scorer`].
222 pub struct ScoringParameters {
223 /// A fixed penalty in msats to apply to each channel.
225 /// Default value: 500 msat
226 pub base_penalty_msat: u64,
228 /// A penalty in msats to apply to a channel upon failing to relay a payment.
230 /// This accumulates for each failure but may be reduced over time based on
231 /// [`failure_penalty_half_life`].
233 /// Default value: 1,024,000 msat
235 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
236 pub failure_penalty_msat: u64,
238 /// When the amount being sent over a channel is this many 1024ths of the total channel
239 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
241 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
243 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
244 pub overuse_penalty_start_1024th: u16,
246 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
247 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
249 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
250 /// to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
252 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
253 pub overuse_penalty_msat_per_1024th: u64,
255 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
260 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
263 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
264 pub failure_penalty_half_life: Duration,
267 impl_writeable_tlv_based!(ScoringParameters, {
268 (0, base_penalty_msat, required),
269 (1, overuse_penalty_start_1024th, (default_value, 128)),
270 (2, failure_penalty_msat, required),
271 (3, overuse_penalty_msat_per_1024th, (default_value, 20)),
272 (4, failure_penalty_half_life, required),
275 /// Accounting for penalties against a channel for failing to relay any payments.
277 /// Penalties decay over time, though accumulate as more failures occur.
278 struct ChannelFailure<T: Time> {
279 /// Accumulated penalty in msats for the channel as of `last_failed`.
280 undecayed_penalty_msat: u64,
282 /// Last time the channel failed. Used to decay `undecayed_penalty_msat`.
286 impl<T: Time> ScorerUsingTime<T> {
287 /// Creates a new scorer using the given scoring parameters.
288 pub fn new(params: ScoringParameters) -> Self {
291 channel_failures: HashMap::new(),
295 /// Creates a new scorer using `penalty_msat` as a fixed channel penalty.
296 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
297 pub fn with_fixed_penalty(penalty_msat: u64) -> Self {
298 Self::new(ScoringParameters {
299 base_penalty_msat: penalty_msat,
300 failure_penalty_msat: 0,
301 failure_penalty_half_life: Duration::from_secs(0),
302 overuse_penalty_start_1024th: 1024,
303 overuse_penalty_msat_per_1024th: 0,
308 impl<T: Time> ChannelFailure<T> {
309 fn new(failure_penalty_msat: u64) -> Self {
311 undecayed_penalty_msat: failure_penalty_msat,
312 last_failed: T::now(),
316 fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
317 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
318 self.last_failed = T::now();
321 fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
322 let decays = self.last_failed.elapsed().as_secs().checked_div(half_life.as_secs());
324 Some(decays) => self.undecayed_penalty_msat >> decays,
330 impl<T: Time> Default for ScorerUsingTime<T> {
331 fn default() -> Self {
332 Self::new(ScoringParameters::default())
336 impl Default for ScoringParameters {
337 fn default() -> Self {
339 base_penalty_msat: 500,
340 failure_penalty_msat: 1024 * 1000,
341 failure_penalty_half_life: Duration::from_secs(3600),
342 overuse_penalty_start_1024th: 1024 / 8,
343 overuse_penalty_msat_per_1024th: 20,
348 impl<T: Time> Score for ScorerUsingTime<T> {
349 fn channel_penalty_msat(
350 &self, short_channel_id: u64, send_amt_msat: u64, chan_capacity_opt: Option<u64>, _source: &NodeId, _target: &NodeId
352 let failure_penalty_msat = self.channel_failures
353 .get(&short_channel_id)
354 .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
356 let mut penalty_msat = self.params.base_penalty_msat + failure_penalty_msat;
358 if let Some(chan_capacity_msat) = chan_capacity_opt {
359 let send_1024ths = send_amt_msat.checked_mul(1024).unwrap_or(u64::max_value()) / chan_capacity_msat;
361 if send_1024ths > self.params.overuse_penalty_start_1024th as u64 {
362 penalty_msat = penalty_msat.checked_add(
363 (send_1024ths - self.params.overuse_penalty_start_1024th as u64)
364 .checked_mul(self.params.overuse_penalty_msat_per_1024th).unwrap_or(u64::max_value()))
365 .unwrap_or(u64::max_value());
372 fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
373 let failure_penalty_msat = self.params.failure_penalty_msat;
374 let half_life = self.params.failure_penalty_half_life;
375 self.channel_failures
376 .entry(short_channel_id)
377 .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
378 .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
382 impl<T: Time> Writeable for ScorerUsingTime<T> {
384 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
385 self.params.write(w)?;
386 self.channel_failures.write(w)?;
387 write_tlv_fields!(w, {});
392 impl<T: Time> Readable for ScorerUsingTime<T> {
394 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
396 params: Readable::read(r)?,
397 channel_failures: Readable::read(r)?,
399 read_tlv_fields!(r, {});
404 impl<T: Time> Writeable for ChannelFailure<T> {
406 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
407 let duration_since_epoch = T::duration_since_epoch() - self.last_failed.elapsed();
408 write_tlv_fields!(w, {
409 (0, self.undecayed_penalty_msat, required),
410 (2, duration_since_epoch, required),
416 impl<T: Time> Readable for ChannelFailure<T> {
418 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
419 let mut undecayed_penalty_msat = 0;
420 let mut duration_since_epoch = Duration::from_secs(0);
421 read_tlv_fields!(r, {
422 (0, undecayed_penalty_msat, required),
423 (2, duration_since_epoch, required),
426 undecayed_penalty_msat,
427 last_failed: T::now() - (T::duration_since_epoch() - duration_since_epoch),
432 pub(crate) mod time {
434 use core::time::Duration;
435 /// A measurement of time.
436 pub trait Time: Sub<Duration, Output = Self> where Self: Sized {
437 /// Returns an instance corresponding to the current moment.
440 /// Returns the amount of time elapsed since `self` was created.
441 fn elapsed(&self) -> Duration;
443 /// Returns the amount of time passed since the beginning of [`Time`].
445 /// Used during (de-)serialization.
446 fn duration_since_epoch() -> Duration;
449 /// A state in which time has no meaning.
450 #[derive(Debug, PartialEq, Eq)]
453 #[cfg(not(feature = "no-std"))]
454 impl Time for std::time::Instant {
456 std::time::Instant::now()
459 fn duration_since_epoch() -> Duration {
460 use std::time::SystemTime;
461 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
464 fn elapsed(&self) -> Duration {
465 std::time::Instant::elapsed(self)
469 impl Time for Eternity {
474 fn duration_since_epoch() -> Duration {
475 Duration::from_secs(0)
478 fn elapsed(&self) -> Duration {
479 Duration::from_secs(0)
483 impl Sub<Duration> for Eternity {
486 fn sub(self, _other: Duration) -> Self {
492 pub(crate) use self::time::Time;
496 use super::{ScoringParameters, ScorerUsingTime, Time};
497 use super::time::Eternity;
499 use routing::scoring::Score;
500 use routing::network_graph::NodeId;
501 use util::ser::{Readable, Writeable};
503 use bitcoin::secp256k1::PublicKey;
504 use core::cell::Cell;
506 use core::time::Duration;
509 /// Time that can be advanced manually in tests.
510 #[derive(Debug, PartialEq, Eq)]
511 struct SinceEpoch(Duration);
515 static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
518 fn advance(duration: Duration) {
519 Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
523 impl Time for SinceEpoch {
525 Self(Self::duration_since_epoch())
528 fn duration_since_epoch() -> Duration {
529 Self::ELAPSED.with(|elapsed| elapsed.get())
532 fn elapsed(&self) -> Duration {
533 Self::duration_since_epoch() - self.0
537 impl Sub<Duration> for SinceEpoch {
540 fn sub(self, other: Duration) -> Self {
546 fn time_passes_when_advanced() {
547 let now = SinceEpoch::now();
548 assert_eq!(now.elapsed(), Duration::from_secs(0));
550 SinceEpoch::advance(Duration::from_secs(1));
551 SinceEpoch::advance(Duration::from_secs(1));
553 let elapsed = now.elapsed();
554 let later = SinceEpoch::now();
556 assert_eq!(elapsed, Duration::from_secs(2));
557 assert_eq!(later - elapsed, now);
561 fn time_never_passes_in_an_eternity() {
562 let now = Eternity::now();
563 let elapsed = now.elapsed();
564 let later = Eternity::now();
566 assert_eq!(now.elapsed(), Duration::from_secs(0));
567 assert_eq!(later - elapsed, now);
570 /// A scorer for testing with time that can be manually advanced.
571 type Scorer = ScorerUsingTime::<SinceEpoch>;
573 fn source_node_id() -> NodeId {
574 NodeId::from_pubkey(&PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap())
577 fn target_node_id() -> NodeId {
578 NodeId::from_pubkey(&PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap())
582 fn penalizes_without_channel_failures() {
583 let scorer = Scorer::new(ScoringParameters {
584 base_penalty_msat: 1_000,
585 failure_penalty_msat: 512,
586 failure_penalty_half_life: Duration::from_secs(1),
587 overuse_penalty_start_1024th: 1024,
588 overuse_penalty_msat_per_1024th: 0,
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);
594 SinceEpoch::advance(Duration::from_secs(1));
595 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
599 fn accumulates_channel_failure_penalties() {
600 let mut scorer = Scorer::new(ScoringParameters {
601 base_penalty_msat: 1_000,
602 failure_penalty_msat: 64,
603 failure_penalty_half_life: Duration::from_secs(10),
604 overuse_penalty_start_1024th: 1024,
605 overuse_penalty_msat_per_1024th: 0,
607 let source = source_node_id();
608 let target = target_node_id();
609 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
611 scorer.payment_path_failed(&[], 42);
612 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_064);
614 scorer.payment_path_failed(&[], 42);
615 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_128);
617 scorer.payment_path_failed(&[], 42);
618 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_192);
622 fn decays_channel_failure_penalties_over_time() {
623 let mut scorer = Scorer::new(ScoringParameters {
624 base_penalty_msat: 1_000,
625 failure_penalty_msat: 512,
626 failure_penalty_half_life: Duration::from_secs(10),
627 overuse_penalty_start_1024th: 1024,
628 overuse_penalty_msat_per_1024th: 0,
630 let source = source_node_id();
631 let target = target_node_id();
632 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
634 scorer.payment_path_failed(&[], 42);
635 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
637 SinceEpoch::advance(Duration::from_secs(9));
638 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
640 SinceEpoch::advance(Duration::from_secs(1));
641 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
643 SinceEpoch::advance(Duration::from_secs(10 * 8));
644 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_001);
646 SinceEpoch::advance(Duration::from_secs(10));
647 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
649 SinceEpoch::advance(Duration::from_secs(10));
650 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
654 fn accumulates_channel_failure_penalties_after_decay() {
655 let mut scorer = Scorer::new(ScoringParameters {
656 base_penalty_msat: 1_000,
657 failure_penalty_msat: 512,
658 failure_penalty_half_life: Duration::from_secs(10),
659 overuse_penalty_start_1024th: 1024,
660 overuse_penalty_msat_per_1024th: 0,
662 let source = source_node_id();
663 let target = target_node_id();
664 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_000);
666 scorer.payment_path_failed(&[], 42);
667 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
669 SinceEpoch::advance(Duration::from_secs(10));
670 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
672 scorer.payment_path_failed(&[], 42);
673 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_768);
675 SinceEpoch::advance(Duration::from_secs(10));
676 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_384);
680 fn restores_persisted_channel_failure_penalties() {
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,
688 let source = source_node_id();
689 let target = target_node_id();
691 scorer.payment_path_failed(&[], 42);
692 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
694 SinceEpoch::advance(Duration::from_secs(10));
695 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
697 scorer.payment_path_failed(&[], 43);
698 assert_eq!(scorer.channel_penalty_msat(43, 1, Some(1), &source, &target), 1_512);
700 let mut serialized_scorer = Vec::new();
701 scorer.write(&mut serialized_scorer).unwrap();
703 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
704 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
705 assert_eq!(deserialized_scorer.channel_penalty_msat(43, 1, Some(1), &source, &target), 1_512);
709 fn decays_persisted_channel_failure_penalties() {
710 let mut scorer = Scorer::new(ScoringParameters {
711 base_penalty_msat: 1_000,
712 failure_penalty_msat: 512,
713 failure_penalty_half_life: Duration::from_secs(10),
714 overuse_penalty_start_1024th: 1024,
715 overuse_penalty_msat_per_1024th: 0,
717 let source = source_node_id();
718 let target = target_node_id();
720 scorer.payment_path_failed(&[], 42);
721 assert_eq!(scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_512);
723 let mut serialized_scorer = Vec::new();
724 scorer.write(&mut serialized_scorer).unwrap();
726 SinceEpoch::advance(Duration::from_secs(10));
728 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
729 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_256);
731 SinceEpoch::advance(Duration::from_secs(10));
732 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, Some(1), &source, &target), 1_128);
736 fn charges_per_1024th_penalty() {
737 let scorer = Scorer::new(ScoringParameters {
738 base_penalty_msat: 0,
739 failure_penalty_msat: 0,
740 failure_penalty_half_life: Duration::from_secs(0),
741 overuse_penalty_start_1024th: 256,
742 overuse_penalty_msat_per_1024th: 100,
744 let source = source_node_id();
745 let target = target_node_id();
747 assert_eq!(scorer.channel_penalty_msat(42, 1_000, None, &source, &target), 0);
748 assert_eq!(scorer.channel_penalty_msat(42, 1_000, Some(1_024_000), &source, &target), 0);
749 assert_eq!(scorer.channel_penalty_msat(42, 256_999, Some(1_024_000), &source, &target), 0);
750 assert_eq!(scorer.channel_penalty_msat(42, 257_000, Some(1_024_000), &source, &target), 100);
751 assert_eq!(scorer.channel_penalty_msat(42, 258_000, Some(1_024_000), &source, &target), 200);
752 assert_eq!(scorer.channel_penalty_msat(42, 512_000, Some(1_024_000), &source, &target), 256 * 100);