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 that are also being considered for use in
86 /// the same payment) is given by `capacity_msat`. It may be determined from various sources
87 /// such as a chain data, network gossip, or invoice hints, the latter indicating sufficient
88 /// capacity (i.e., near [`u64::max_value`]). Thus, implementations should be overflow-safe.
89 fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, source: &NodeId, target: &NodeId) -> u64;
91 /// Handles updating channel penalties after failing to route through a channel.
92 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64);
94 /// Handles updating channel penalties after successfully routing along a path.
95 fn payment_path_successful(&mut self, path: &[&RouteHop]);
98 impl<S: Score, T: DerefMut<Target=S> $(+ $supertrait)*> Score for T {
99 fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, source: &NodeId, target: &NodeId) -> u64 {
100 self.deref().channel_penalty_msat(short_channel_id, send_amt_msat, capacity_msat, source, target)
103 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
104 self.deref_mut().payment_path_failed(path, short_channel_id)
107 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
108 self.deref_mut().payment_path_successful(path)
114 define_score!(Writeable);
115 #[cfg(not(c_bindings))]
118 /// A scorer that is accessed under a lock.
120 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
121 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
122 /// implementations. Internal locking would be detrimental to route finding performance and could
123 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
125 /// [`find_route`]: crate::routing::router::find_route
126 pub trait LockableScore<'a> {
127 /// The locked [`Score`] type.
128 type Locked: 'a + Score;
130 /// Returns the locked scorer.
131 fn lock(&'a self) -> Self::Locked;
135 impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
136 type Locked = MutexGuard<'a, T>;
138 fn lock(&'a self) -> MutexGuard<'a, T> {
139 Mutex::lock(self).unwrap()
143 impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
144 type Locked = RefMut<'a, T>;
146 fn lock(&'a self) -> RefMut<'a, T> {
152 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
153 pub struct MultiThreadedLockableScore<S: Score> {
158 impl<'a, T: Score + 'a> LockableScore<'a> for MultiThreadedLockableScore<T> {
159 type Locked = MutexGuard<'a, T>;
161 fn lock(&'a self) -> MutexGuard<'a, T> {
162 Mutex::lock(&self.score).unwrap()
167 impl<T: Score> MultiThreadedLockableScore<T> {
168 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
169 pub fn new(score: T) -> Self {
170 MultiThreadedLockableScore { score: Mutex::new(score) }
176 impl<'a, T: Writeable> Writeable for RefMut<'a, T> {
177 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
178 T::write(&**self, writer)
184 impl<'a, S: Writeable> Writeable for MutexGuard<'a, S> {
185 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
186 S::write(&**self, writer)
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(not(feature = "no-std"))]
199 pub type Scorer = ScorerUsingTime::<std::time::Instant>;
200 /// [`Score`] implementation that provides reasonable default behavior.
202 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
203 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
205 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
207 /// [module-level documentation]: crate::routing::scoring
208 #[cfg(feature = "no-std")]
209 pub type Scorer = ScorerUsingTime::<time::Eternity>;
211 // Note that ideally we'd hide ScorerUsingTime from public view by sealing it as well, but rustdoc
212 // doesn't handle this well - instead exposing a `Scorer` which has no trait implementation(s) or
215 /// [`Score`] implementation.
217 /// See [`Scorer`] for details.
221 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
224 /// (C-not exported) generally all users should use the [`Scorer`] type alias.
225 pub struct ScorerUsingTime<T: Time> {
226 params: ScoringParameters,
227 // TODO: Remove entries of closed channels.
228 channel_failures: HashMap<u64, ChannelFailure<T>>,
231 /// Parameters for configuring [`Scorer`].
232 pub struct ScoringParameters {
233 /// A fixed penalty in msats to apply to each channel.
235 /// Default value: 500 msat
236 pub base_penalty_msat: u64,
238 /// A penalty in msats to apply to a channel upon failing to relay a payment.
240 /// This accumulates for each failure but may be reduced over time based on
241 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
243 /// Default value: 1,024,000 msat
245 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
246 pub failure_penalty_msat: u64,
248 /// When the amount being sent over a channel is this many 1024ths of the total channel
249 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
251 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
253 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
254 pub overuse_penalty_start_1024th: u16,
256 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
257 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
259 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
260 /// to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
262 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
263 pub overuse_penalty_msat_per_1024th: u64,
265 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
268 /// Successfully routing through a channel will immediately cut the penalty in half as well.
272 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
275 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
276 pub failure_penalty_half_life: Duration,
279 impl_writeable_tlv_based!(ScoringParameters, {
280 (0, base_penalty_msat, required),
281 (1, overuse_penalty_start_1024th, (default_value, 128)),
282 (2, failure_penalty_msat, required),
283 (3, overuse_penalty_msat_per_1024th, (default_value, 20)),
284 (4, failure_penalty_half_life, required),
287 /// Accounting for penalties against a channel for failing to relay any payments.
289 /// Penalties decay over time, though accumulate as more failures occur.
290 struct ChannelFailure<T: Time> {
291 /// Accumulated penalty in msats for the channel as of `last_updated`.
292 undecayed_penalty_msat: u64,
294 /// Last time the channel either failed to route or successfully routed a payment. Used to decay
295 /// `undecayed_penalty_msat`.
299 impl<T: Time> ScorerUsingTime<T> {
300 /// Creates a new scorer using the given scoring parameters.
301 pub fn new(params: ScoringParameters) -> Self {
304 channel_failures: HashMap::new(),
308 /// Creates a new scorer using `penalty_msat` as a fixed channel penalty.
309 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
310 pub fn with_fixed_penalty(penalty_msat: u64) -> Self {
311 Self::new(ScoringParameters {
312 base_penalty_msat: penalty_msat,
313 failure_penalty_msat: 0,
314 failure_penalty_half_life: Duration::from_secs(0),
315 overuse_penalty_start_1024th: 1024,
316 overuse_penalty_msat_per_1024th: 0,
321 impl<T: Time> ChannelFailure<T> {
322 fn new(failure_penalty_msat: u64) -> Self {
324 undecayed_penalty_msat: failure_penalty_msat,
325 last_updated: T::now(),
329 fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
330 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
331 self.last_updated = T::now();
334 fn reduce_penalty(&mut self, half_life: Duration) {
335 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) >> 1;
336 self.last_updated = T::now();
339 fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
340 self.last_updated.elapsed().as_secs()
341 .checked_div(half_life.as_secs())
342 .and_then(|decays| self.undecayed_penalty_msat.checked_shr(decays as u32))
347 impl<T: Time> Default for ScorerUsingTime<T> {
348 fn default() -> Self {
349 Self::new(ScoringParameters::default())
353 impl Default for ScoringParameters {
354 fn default() -> Self {
356 base_penalty_msat: 500,
357 failure_penalty_msat: 1024 * 1000,
358 failure_penalty_half_life: Duration::from_secs(3600),
359 overuse_penalty_start_1024th: 1024 / 8,
360 overuse_penalty_msat_per_1024th: 20,
365 impl<T: Time> Score for ScorerUsingTime<T> {
366 fn channel_penalty_msat(
367 &self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, _source: &NodeId, _target: &NodeId
369 let failure_penalty_msat = self.channel_failures
370 .get(&short_channel_id)
371 .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
373 let mut penalty_msat = self.params.base_penalty_msat + failure_penalty_msat;
374 let send_1024ths = send_amt_msat.checked_mul(1024).unwrap_or(u64::max_value()) / capacity_msat;
375 if send_1024ths > self.params.overuse_penalty_start_1024th as u64 {
376 penalty_msat = penalty_msat.checked_add(
377 (send_1024ths - self.params.overuse_penalty_start_1024th as u64)
378 .checked_mul(self.params.overuse_penalty_msat_per_1024th).unwrap_or(u64::max_value()))
379 .unwrap_or(u64::max_value());
385 fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
386 let failure_penalty_msat = self.params.failure_penalty_msat;
387 let half_life = self.params.failure_penalty_half_life;
388 self.channel_failures
389 .entry(short_channel_id)
390 .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
391 .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
394 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
395 let half_life = self.params.failure_penalty_half_life;
396 for hop in path.iter() {
397 self.channel_failures
398 .entry(hop.short_channel_id)
399 .and_modify(|failure| failure.reduce_penalty(half_life));
404 impl<T: Time> Writeable for ScorerUsingTime<T> {
406 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
407 self.params.write(w)?;
408 self.channel_failures.write(w)?;
409 write_tlv_fields!(w, {});
414 impl<T: Time> Readable for ScorerUsingTime<T> {
416 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
418 params: Readable::read(r)?,
419 channel_failures: Readable::read(r)?,
421 read_tlv_fields!(r, {});
426 impl<T: Time> Writeable for ChannelFailure<T> {
428 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
429 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
430 write_tlv_fields!(w, {
431 (0, self.undecayed_penalty_msat, required),
432 (2, duration_since_epoch, required),
438 impl<T: Time> Readable for ChannelFailure<T> {
440 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
441 let mut undecayed_penalty_msat = 0;
442 let mut duration_since_epoch = Duration::from_secs(0);
443 read_tlv_fields!(r, {
444 (0, undecayed_penalty_msat, required),
445 (2, duration_since_epoch, required),
448 undecayed_penalty_msat,
449 last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
454 pub(crate) mod time {
456 use core::time::Duration;
457 /// A measurement of time.
458 pub trait Time: Sub<Duration, Output = Self> where Self: Sized {
459 /// Returns an instance corresponding to the current moment.
462 /// Returns the amount of time elapsed since `self` was created.
463 fn elapsed(&self) -> Duration;
465 /// Returns the amount of time passed since the beginning of [`Time`].
467 /// Used during (de-)serialization.
468 fn duration_since_epoch() -> Duration;
471 /// A state in which time has no meaning.
472 #[derive(Debug, PartialEq, Eq)]
475 #[cfg(not(feature = "no-std"))]
476 impl Time for std::time::Instant {
478 std::time::Instant::now()
481 fn duration_since_epoch() -> Duration {
482 use std::time::SystemTime;
483 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
486 fn elapsed(&self) -> Duration {
487 std::time::Instant::elapsed(self)
491 impl Time for Eternity {
496 fn duration_since_epoch() -> Duration {
497 Duration::from_secs(0)
500 fn elapsed(&self) -> Duration {
501 Duration::from_secs(0)
505 impl Sub<Duration> for Eternity {
508 fn sub(self, _other: Duration) -> Self {
514 pub(crate) use self::time::Time;
518 use super::{ScoringParameters, ScorerUsingTime, Time};
519 use super::time::Eternity;
521 use ln::features::{ChannelFeatures, NodeFeatures};
522 use routing::scoring::Score;
523 use routing::network_graph::NodeId;
524 use routing::router::RouteHop;
525 use util::ser::{Readable, Writeable};
527 use bitcoin::secp256k1::PublicKey;
528 use core::cell::Cell;
530 use core::time::Duration;
533 /// Time that can be advanced manually in tests.
534 #[derive(Debug, PartialEq, Eq)]
535 struct SinceEpoch(Duration);
539 static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
542 fn advance(duration: Duration) {
543 Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
547 impl Time for SinceEpoch {
549 Self(Self::duration_since_epoch())
552 fn duration_since_epoch() -> Duration {
553 Self::ELAPSED.with(|elapsed| elapsed.get())
556 fn elapsed(&self) -> Duration {
557 Self::duration_since_epoch() - self.0
561 impl Sub<Duration> for SinceEpoch {
564 fn sub(self, other: Duration) -> Self {
570 fn time_passes_when_advanced() {
571 let now = SinceEpoch::now();
572 assert_eq!(now.elapsed(), Duration::from_secs(0));
574 SinceEpoch::advance(Duration::from_secs(1));
575 SinceEpoch::advance(Duration::from_secs(1));
577 let elapsed = now.elapsed();
578 let later = SinceEpoch::now();
580 assert_eq!(elapsed, Duration::from_secs(2));
581 assert_eq!(later - elapsed, now);
585 fn time_never_passes_in_an_eternity() {
586 let now = Eternity::now();
587 let elapsed = now.elapsed();
588 let later = Eternity::now();
590 assert_eq!(now.elapsed(), Duration::from_secs(0));
591 assert_eq!(later - elapsed, now);
594 /// A scorer for testing with time that can be manually advanced.
595 type Scorer = ScorerUsingTime::<SinceEpoch>;
597 fn source_node_id() -> NodeId {
598 NodeId::from_pubkey(&PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap())
601 fn target_node_id() -> NodeId {
602 NodeId::from_pubkey(&PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap())
606 fn penalizes_without_channel_failures() {
607 let scorer = Scorer::new(ScoringParameters {
608 base_penalty_msat: 1_000,
609 failure_penalty_msat: 512,
610 failure_penalty_half_life: Duration::from_secs(1),
611 overuse_penalty_start_1024th: 1024,
612 overuse_penalty_msat_per_1024th: 0,
614 let source = source_node_id();
615 let target = target_node_id();
616 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
618 SinceEpoch::advance(Duration::from_secs(1));
619 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
623 fn accumulates_channel_failure_penalties() {
624 let mut scorer = Scorer::new(ScoringParameters {
625 base_penalty_msat: 1_000,
626 failure_penalty_msat: 64,
627 failure_penalty_half_life: Duration::from_secs(10),
628 overuse_penalty_start_1024th: 1024,
629 overuse_penalty_msat_per_1024th: 0,
631 let source = source_node_id();
632 let target = target_node_id();
633 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
635 scorer.payment_path_failed(&[], 42);
636 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
638 scorer.payment_path_failed(&[], 42);
639 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
641 scorer.payment_path_failed(&[], 42);
642 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_192);
646 fn decays_channel_failure_penalties_over_time() {
647 let mut scorer = Scorer::new(ScoringParameters {
648 base_penalty_msat: 1_000,
649 failure_penalty_msat: 512,
650 failure_penalty_half_life: Duration::from_secs(10),
651 overuse_penalty_start_1024th: 1024,
652 overuse_penalty_msat_per_1024th: 0,
654 let source = source_node_id();
655 let target = target_node_id();
656 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
658 scorer.payment_path_failed(&[], 42);
659 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
661 SinceEpoch::advance(Duration::from_secs(9));
662 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
664 SinceEpoch::advance(Duration::from_secs(1));
665 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
667 SinceEpoch::advance(Duration::from_secs(10 * 8));
668 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_001);
670 SinceEpoch::advance(Duration::from_secs(10));
671 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
673 SinceEpoch::advance(Duration::from_secs(10));
674 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
678 fn decays_channel_failure_penalties_without_shift_overflow() {
679 let mut scorer = Scorer::new(ScoringParameters {
680 base_penalty_msat: 1_000,
681 failure_penalty_msat: 512,
682 failure_penalty_half_life: Duration::from_secs(10),
683 overuse_penalty_start_1024th: 1024,
684 overuse_penalty_msat_per_1024th: 0,
686 let source = source_node_id();
687 let target = target_node_id();
688 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
690 scorer.payment_path_failed(&[], 42);
691 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
693 // An unchecked right shift 64 bits or more in ChannelFailure::decayed_penalty_msat would
694 // cause an overflow.
695 SinceEpoch::advance(Duration::from_secs(10 * 64));
696 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
698 SinceEpoch::advance(Duration::from_secs(10));
699 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
703 fn accumulates_channel_failure_penalties_after_decay() {
704 let mut scorer = Scorer::new(ScoringParameters {
705 base_penalty_msat: 1_000,
706 failure_penalty_msat: 512,
707 failure_penalty_half_life: Duration::from_secs(10),
708 overuse_penalty_start_1024th: 1024,
709 overuse_penalty_msat_per_1024th: 0,
711 let source = source_node_id();
712 let target = target_node_id();
713 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
715 scorer.payment_path_failed(&[], 42);
716 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
718 SinceEpoch::advance(Duration::from_secs(10));
719 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
721 scorer.payment_path_failed(&[], 42);
722 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_768);
724 SinceEpoch::advance(Duration::from_secs(10));
725 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_384);
729 fn reduces_channel_failure_penalties_after_success() {
730 let mut scorer = Scorer::new(ScoringParameters {
731 base_penalty_msat: 1_000,
732 failure_penalty_msat: 512,
733 failure_penalty_half_life: Duration::from_secs(10),
734 overuse_penalty_start_1024th: 1024,
735 overuse_penalty_msat_per_1024th: 0,
737 let source = source_node_id();
738 let target = target_node_id();
739 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
741 scorer.payment_path_failed(&[], 42);
742 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
744 SinceEpoch::advance(Duration::from_secs(10));
745 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
748 pubkey: PublicKey::from_slice(target.as_slice()).unwrap(),
749 node_features: NodeFeatures::known(),
750 short_channel_id: 42,
751 channel_features: ChannelFeatures::known(),
753 cltv_expiry_delta: 18,
755 scorer.payment_path_successful(&[&hop]);
756 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
758 SinceEpoch::advance(Duration::from_secs(10));
759 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
763 fn restores_persisted_channel_failure_penalties() {
764 let mut scorer = Scorer::new(ScoringParameters {
765 base_penalty_msat: 1_000,
766 failure_penalty_msat: 512,
767 failure_penalty_half_life: Duration::from_secs(10),
768 overuse_penalty_start_1024th: 1024,
769 overuse_penalty_msat_per_1024th: 0,
771 let source = source_node_id();
772 let target = target_node_id();
774 scorer.payment_path_failed(&[], 42);
775 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
777 SinceEpoch::advance(Duration::from_secs(10));
778 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
780 scorer.payment_path_failed(&[], 43);
781 assert_eq!(scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
783 let mut serialized_scorer = Vec::new();
784 scorer.write(&mut serialized_scorer).unwrap();
786 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
787 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
788 assert_eq!(deserialized_scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
792 fn decays_persisted_channel_failure_penalties() {
793 let mut scorer = Scorer::new(ScoringParameters {
794 base_penalty_msat: 1_000,
795 failure_penalty_msat: 512,
796 failure_penalty_half_life: Duration::from_secs(10),
797 overuse_penalty_start_1024th: 1024,
798 overuse_penalty_msat_per_1024th: 0,
800 let source = source_node_id();
801 let target = target_node_id();
803 scorer.payment_path_failed(&[], 42);
804 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
806 let mut serialized_scorer = Vec::new();
807 scorer.write(&mut serialized_scorer).unwrap();
809 SinceEpoch::advance(Duration::from_secs(10));
811 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
812 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
814 SinceEpoch::advance(Duration::from_secs(10));
815 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
819 fn charges_per_1024th_penalty() {
820 let scorer = Scorer::new(ScoringParameters {
821 base_penalty_msat: 0,
822 failure_penalty_msat: 0,
823 failure_penalty_half_life: Duration::from_secs(0),
824 overuse_penalty_start_1024th: 256,
825 overuse_penalty_msat_per_1024th: 100,
827 let source = source_node_id();
828 let target = target_node_id();
830 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 1_024_000, &source, &target), 0);
831 assert_eq!(scorer.channel_penalty_msat(42, 256_999, 1_024_000, &source, &target), 0);
832 assert_eq!(scorer.channel_penalty_msat(42, 257_000, 1_024_000, &source, &target), 100);
833 assert_eq!(scorer.channel_penalty_msat(42, 258_000, 1_024_000, &source, &target), 200);
834 assert_eq!(scorer.channel_penalty_msat(42, 512_000, 1_024_000, &source, &target), 256 * 100);