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 //! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path
13 //! finding when a 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::{ProbabilisticScorer, ProbabilisticScoringParameters, 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, route_params: RouteParameters, network_graph: NetworkGraph) {
31 //! # let logger = FakeLogger {};
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringParameters::default();
35 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
37 //! // Or use custom channel penalties.
38 //! let params = ProbabilisticScoringParameters {
39 //! liquidity_penalty_multiplier_msat: 2 * 1000,
40 //! ..ProbabilisticScoringParameters::default()
42 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
44 //! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer);
50 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
51 //! different types and thus is undefined.
53 //! [`find_route`]: crate::routing::router::find_route
55 use ln::msgs::DecodeError;
56 use routing::network_graph::{NetworkGraph, NodeId};
57 use routing::router::RouteHop;
58 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
61 use core::cell::{RefCell, RefMut};
62 use core::ops::{Deref, DerefMut};
63 use core::time::Duration;
65 use sync::{Mutex, MutexGuard};
67 /// We define Score ever-so-slightly differently based on whether we are being built for C bindings
68 /// or not. For users, `LockableScore` must somehow be writeable to disk. For Rust users, this is
69 /// no problem - you move a `Score` that implements `Writeable` into a `Mutex`, lock it, and now
70 /// you have the original, concrete, `Score` type, which presumably implements `Writeable`.
72 /// For C users, once you've moved the `Score` into a `LockableScore` all you have after locking it
73 /// is an opaque trait object with an opaque pointer with no type info. Users could take the unsafe
74 /// approach of blindly casting that opaque pointer to a concrete type and calling `Writeable` from
75 /// there, but other languages downstream of the C bindings (e.g. Java) can't even do that.
76 /// Instead, we really want `Score` and `LockableScore` to implement `Writeable` directly, which we
77 /// do here by defining `Score` differently for `cfg(c_bindings)`.
78 macro_rules! define_score { ($($supertrait: path)*) => {
79 /// An interface used to score payment channels for path finding.
81 /// Scoring is in terms of fees willing to be paid in order to avoid routing through a channel.
82 pub trait Score $(: $supertrait)* {
83 /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
84 /// given channel in the direction from `source` to `target`.
86 /// The channel's capacity (less any other MPP parts that are also being considered for use in
87 /// the same payment) is given by `capacity_msat`. It may be determined from various sources
88 /// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near
89 /// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount.
90 /// Thus, implementations should be overflow-safe.
91 fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, source: &NodeId, target: &NodeId) -> u64;
93 /// Handles updating channel penalties after failing to route through a channel.
94 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64);
96 /// Handles updating channel penalties after successfully routing along a path.
97 fn payment_path_successful(&mut self, path: &[&RouteHop]);
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, capacity_msat: u64, source: &NodeId, target: &NodeId) -> u64 {
102 self.deref().channel_penalty_msat(short_channel_id, send_amt_msat, 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)
109 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
110 self.deref_mut().payment_path_successful(path)
116 define_score!(Writeable);
117 #[cfg(not(c_bindings))]
120 /// A scorer that is accessed under a lock.
122 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
123 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
124 /// implementations. Internal locking would be detrimental to route finding performance and could
125 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
127 /// [`find_route`]: crate::routing::router::find_route
128 pub trait LockableScore<'a> {
129 /// The locked [`Score`] type.
130 type Locked: 'a + Score;
132 /// Returns the locked scorer.
133 fn lock(&'a self) -> Self::Locked;
137 impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
138 type Locked = MutexGuard<'a, T>;
140 fn lock(&'a self) -> MutexGuard<'a, T> {
141 Mutex::lock(self).unwrap()
145 impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
146 type Locked = RefMut<'a, T>;
148 fn lock(&'a self) -> RefMut<'a, T> {
154 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
155 pub struct MultiThreadedLockableScore<S: Score> {
160 impl<'a, T: Score + 'a> LockableScore<'a> for MultiThreadedLockableScore<T> {
161 type Locked = MutexGuard<'a, T>;
163 fn lock(&'a self) -> MutexGuard<'a, T> {
164 Mutex::lock(&self.score).unwrap()
169 impl<T: Score> MultiThreadedLockableScore<T> {
170 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
171 pub fn new(score: T) -> Self {
172 MultiThreadedLockableScore { score: Mutex::new(score) }
178 impl<'a, T: Writeable> Writeable for RefMut<'a, T> {
179 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
180 T::write(&**self, writer)
186 impl<'a, S: Writeable> Writeable for MutexGuard<'a, S> {
187 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
188 S::write(&**self, writer)
192 /// [`Score`] implementation that uses a fixed penalty.
193 pub struct FixedPenaltyScorer {
197 impl_writeable_tlv_based!(FixedPenaltyScorer, {
198 (0, penalty_msat, required),
201 impl FixedPenaltyScorer {
202 /// Creates a new scorer using `penalty_msat`.
203 pub fn with_penalty(penalty_msat: u64) -> Self {
204 Self { penalty_msat }
208 impl Score for FixedPenaltyScorer {
209 fn channel_penalty_msat(&self, _: u64, _: u64, _: u64, _: &NodeId, _: &NodeId) -> u64 {
213 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
215 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
218 #[cfg(not(feature = "no-std"))]
219 /// [`Score`] implementation that provides reasonable default behavior.
221 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
222 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
224 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
228 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
231 /// [module-level documentation]: crate::routing::scoring
234 note = "ProbabilisticScorer should be used instead of Scorer.",
236 pub type Scorer = ScorerUsingTime::<std::time::Instant>;
237 #[cfg(feature = "no-std")]
238 /// [`Score`] implementation that provides reasonable default behavior.
240 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
241 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
243 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
247 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
250 /// [module-level documentation]: crate::routing::scoring
251 pub type Scorer = ScorerUsingTime::<time::Eternity>;
253 // Note that ideally we'd hide ScorerUsingTime from public view by sealing it as well, but rustdoc
254 // doesn't handle this well - instead exposing a `Scorer` which has no trait implementation(s) or
257 /// [`Score`] implementation.
259 /// (C-not exported) generally all users should use the [`Scorer`] type alias.
260 pub struct ScorerUsingTime<T: Time> {
261 params: ScoringParameters,
262 // TODO: Remove entries of closed channels.
263 channel_failures: HashMap<u64, ChannelFailure<T>>,
266 /// Parameters for configuring [`Scorer`].
267 pub struct ScoringParameters {
268 /// A fixed penalty in msats to apply to each channel.
270 /// Default value: 500 msat
271 pub base_penalty_msat: u64,
273 /// A penalty in msats to apply to a channel upon failing to relay a payment.
275 /// This accumulates for each failure but may be reduced over time based on
276 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
278 /// Default value: 1,024,000 msat
280 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
281 pub failure_penalty_msat: u64,
283 /// When the amount being sent over a channel is this many 1024ths of the total channel
284 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
286 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
288 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
289 pub overuse_penalty_start_1024th: u16,
291 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
292 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
294 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
295 /// to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
297 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
298 pub overuse_penalty_msat_per_1024th: u64,
300 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
303 /// Successfully routing through a channel will immediately cut the penalty in half as well.
305 /// Default value: 1 hour
309 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
312 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
313 pub failure_penalty_half_life: Duration,
316 impl_writeable_tlv_based!(ScoringParameters, {
317 (0, base_penalty_msat, required),
318 (1, overuse_penalty_start_1024th, (default_value, 128)),
319 (2, failure_penalty_msat, required),
320 (3, overuse_penalty_msat_per_1024th, (default_value, 20)),
321 (4, failure_penalty_half_life, required),
324 /// Accounting for penalties against a channel for failing to relay any payments.
326 /// Penalties decay over time, though accumulate as more failures occur.
327 struct ChannelFailure<T: Time> {
328 /// Accumulated penalty in msats for the channel as of `last_updated`.
329 undecayed_penalty_msat: u64,
331 /// Last time the channel either failed to route or successfully routed a payment. Used to decay
332 /// `undecayed_penalty_msat`.
336 impl<T: Time> ScorerUsingTime<T> {
337 /// Creates a new scorer using the given scoring parameters.
338 pub fn new(params: ScoringParameters) -> Self {
341 channel_failures: HashMap::new(),
346 impl<T: Time> ChannelFailure<T> {
347 fn new(failure_penalty_msat: u64) -> Self {
349 undecayed_penalty_msat: failure_penalty_msat,
350 last_updated: T::now(),
354 fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
355 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
356 self.last_updated = T::now();
359 fn reduce_penalty(&mut self, half_life: Duration) {
360 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) >> 1;
361 self.last_updated = T::now();
364 fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
365 self.last_updated.elapsed().as_secs()
366 .checked_div(half_life.as_secs())
367 .and_then(|decays| self.undecayed_penalty_msat.checked_shr(decays as u32))
372 impl<T: Time> Default for ScorerUsingTime<T> {
373 fn default() -> Self {
374 Self::new(ScoringParameters::default())
378 impl Default for ScoringParameters {
379 fn default() -> Self {
381 base_penalty_msat: 500,
382 failure_penalty_msat: 1024 * 1000,
383 failure_penalty_half_life: Duration::from_secs(3600),
384 overuse_penalty_start_1024th: 1024 / 8,
385 overuse_penalty_msat_per_1024th: 20,
390 impl<T: Time> Score for ScorerUsingTime<T> {
391 fn channel_penalty_msat(
392 &self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, _source: &NodeId, _target: &NodeId
394 let failure_penalty_msat = self.channel_failures
395 .get(&short_channel_id)
396 .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
398 let mut penalty_msat = self.params.base_penalty_msat + failure_penalty_msat;
399 let send_1024ths = send_amt_msat.checked_mul(1024).unwrap_or(u64::max_value()) / capacity_msat;
400 if send_1024ths > self.params.overuse_penalty_start_1024th as u64 {
401 penalty_msat = penalty_msat.checked_add(
402 (send_1024ths - self.params.overuse_penalty_start_1024th as u64)
403 .checked_mul(self.params.overuse_penalty_msat_per_1024th).unwrap_or(u64::max_value()))
404 .unwrap_or(u64::max_value());
410 fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
411 let failure_penalty_msat = self.params.failure_penalty_msat;
412 let half_life = self.params.failure_penalty_half_life;
413 self.channel_failures
414 .entry(short_channel_id)
415 .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
416 .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
419 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
420 let half_life = self.params.failure_penalty_half_life;
421 for hop in path.iter() {
422 self.channel_failures
423 .entry(hop.short_channel_id)
424 .and_modify(|failure| failure.reduce_penalty(half_life));
429 impl<T: Time> Writeable for ScorerUsingTime<T> {
431 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
432 self.params.write(w)?;
433 self.channel_failures.write(w)?;
434 write_tlv_fields!(w, {});
439 impl<T: Time> Readable for ScorerUsingTime<T> {
441 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
443 params: Readable::read(r)?,
444 channel_failures: Readable::read(r)?,
446 read_tlv_fields!(r, {});
451 impl<T: Time> Writeable for ChannelFailure<T> {
453 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
454 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
455 write_tlv_fields!(w, {
456 (0, self.undecayed_penalty_msat, required),
457 (2, duration_since_epoch, required),
463 impl<T: Time> Readable for ChannelFailure<T> {
465 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
466 let mut undecayed_penalty_msat = 0;
467 let mut duration_since_epoch = Duration::from_secs(0);
468 read_tlv_fields!(r, {
469 (0, undecayed_penalty_msat, required),
470 (2, duration_since_epoch, required),
473 undecayed_penalty_msat,
474 last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
479 #[cfg(not(feature = "no-std"))]
480 /// [`Score`] implementation using channel success probability distributions.
482 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
483 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
484 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
485 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
486 /// specific HTLC amount through a channel.
488 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
489 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
490 /// [`ProbabilisticScoringParameters`] for details.
492 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
493 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
494 /// volume are more likely to experience failed payment paths, which would need to be retried.
498 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
501 /// [1]: https://arxiv.org/abs/2107.05322
502 pub type ProbabilisticScorer<G> = ProbabilisticScorerUsingTime::<G, std::time::Instant>;
503 #[cfg(feature = "no-std")]
504 /// [`Score`] implementation using channel success probability distributions.
506 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
507 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
508 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
509 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
510 /// specific HTLC amount through a channel.
512 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
513 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
514 /// [`ProbabilisticScoringParameters`] for details.
516 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
517 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
518 /// volume are more likely to experience failed payment paths, which would need to be retried.
522 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
525 /// [1]: https://arxiv.org/abs/2107.05322
526 pub type ProbabilisticScorer<G> = ProbabilisticScorerUsingTime::<G, time::Eternity>;
528 /// Probabilistic [`Score`] implementation.
530 /// (C-not exported) generally all users should use the [`ProbabilisticScorer`] type alias.
531 pub struct ProbabilisticScorerUsingTime<G: Deref<Target = NetworkGraph>, T: Time> {
532 params: ProbabilisticScoringParameters,
534 // TODO: Remove entries of closed channels.
535 channel_liquidities: HashMap<u64, ChannelLiquidity<T>>,
538 /// Parameters for configuring [`ProbabilisticScorer`].
539 #[derive(Clone, Copy)]
540 pub struct ProbabilisticScoringParameters {
541 /// A multiplier used to determine the amount in msats willing to be paid to avoid routing
542 /// through a channel, as per multiplying by the negative `log10` of the channel's success
543 /// probability for a payment.
545 /// The success probability is determined by the effective channel capacity, the payment amount,
546 /// and knowledge learned from prior successful and unsuccessful payments. The lower bound of
547 /// the success probability is 0.01, effectively limiting the penalty to the range
548 /// `0..=2*liquidity_penalty_multiplier_msat`. The knowledge learned is decayed over time based
549 /// on [`liquidity_offset_half_life`].
551 /// Default value: 10,000 msat
553 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
554 pub liquidity_penalty_multiplier_msat: u64,
556 /// The time required to elapse before any knowledge learned about channel liquidity balances is
559 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
560 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
561 /// the certainty of the channel liquidity balance.
563 /// Default value: 1 hour
567 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
568 /// liquidity knowledge will never decay except when the bounds cross.
569 pub liquidity_offset_half_life: Duration,
572 impl_writeable_tlv_based!(ProbabilisticScoringParameters, {
573 (0, liquidity_penalty_multiplier_msat, required),
574 (2, liquidity_offset_half_life, required),
577 /// Accounting for channel liquidity balance uncertainty.
579 /// Direction is defined in terms of [`NodeId`] partial ordering, where the source node is the
580 /// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
581 /// offset fields gives the opposite direction.
582 struct ChannelLiquidity<T: Time> {
583 /// Lower channel liquidity bound in terms of an offset from zero.
584 min_liquidity_offset_msat: u64,
586 /// Upper channel liquidity bound in terms of an offset from the effective capacity.
587 max_liquidity_offset_msat: u64,
589 /// Time when the liquidity bounds were last modified.
593 /// A snapshot of [`ChannelLiquidity`] in one direction assuming a certain channel capacity and
594 /// decayed with a given half life.
595 struct DirectedChannelLiquidity<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> {
596 min_liquidity_offset_msat: L,
597 max_liquidity_offset_msat: L,
604 impl<G: Deref<Target = NetworkGraph>, T: Time> ProbabilisticScorerUsingTime<G, T> {
605 /// Creates a new scorer using the given scoring parameters for sending payments from a node
606 /// through a network graph.
607 pub fn new(params: ProbabilisticScoringParameters, network_graph: G) -> Self {
611 channel_liquidities: HashMap::new(),
616 fn with_channel(mut self, short_channel_id: u64, liquidity: ChannelLiquidity<T>) -> Self {
617 assert!(self.channel_liquidities.insert(short_channel_id, liquidity).is_none());
622 impl Default for ProbabilisticScoringParameters {
623 fn default() -> Self {
625 liquidity_penalty_multiplier_msat: 10_000,
626 liquidity_offset_half_life: Duration::from_secs(3600),
631 impl<T: Time> ChannelLiquidity<T> {
635 min_liquidity_offset_msat: 0,
636 max_liquidity_offset_msat: 0,
637 last_updated: T::now(),
641 /// Returns a view of the channel liquidity directed from `source` to `target` assuming
644 &self, source: &NodeId, target: &NodeId, capacity_msat: u64, half_life: Duration
645 ) -> DirectedChannelLiquidity<&u64, T, &T> {
646 let (min_liquidity_offset_msat, max_liquidity_offset_msat) = if source < target {
647 (&self.min_liquidity_offset_msat, &self.max_liquidity_offset_msat)
649 (&self.max_liquidity_offset_msat, &self.min_liquidity_offset_msat)
652 DirectedChannelLiquidity {
653 min_liquidity_offset_msat,
654 max_liquidity_offset_msat,
656 last_updated: &self.last_updated,
662 /// Returns a mutable view of the channel liquidity directed from `source` to `target` assuming
665 &mut self, source: &NodeId, target: &NodeId, capacity_msat: u64, half_life: Duration
666 ) -> DirectedChannelLiquidity<&mut u64, T, &mut T> {
667 let (min_liquidity_offset_msat, max_liquidity_offset_msat) = if source < target {
668 (&mut self.min_liquidity_offset_msat, &mut self.max_liquidity_offset_msat)
670 (&mut self.max_liquidity_offset_msat, &mut self.min_liquidity_offset_msat)
673 DirectedChannelLiquidity {
674 min_liquidity_offset_msat,
675 max_liquidity_offset_msat,
677 last_updated: &mut self.last_updated,
684 impl<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> DirectedChannelLiquidity<L, T, U> {
685 /// Returns the success probability of routing the given HTLC `amount_msat` through the channel
686 /// in this direction.
687 fn success_probability(&self, amount_msat: u64) -> f64 {
688 let max_liquidity_msat = self.max_liquidity_msat();
689 let min_liquidity_msat = core::cmp::min(self.min_liquidity_msat(), max_liquidity_msat);
690 if amount_msat > max_liquidity_msat {
692 } else if amount_msat <= min_liquidity_msat {
695 let numerator = max_liquidity_msat + 1 - amount_msat;
696 let denominator = max_liquidity_msat + 1 - min_liquidity_msat;
697 numerator as f64 / denominator as f64
698 }.max(0.01) // Lower bound the success probability to ensure some channel is selected.
701 /// Returns the lower bound of the channel liquidity balance in this direction.
702 fn min_liquidity_msat(&self) -> u64 {
703 self.decayed_offset_msat(*self.min_liquidity_offset_msat)
706 /// Returns the upper bound of the channel liquidity balance in this direction.
707 fn max_liquidity_msat(&self) -> u64 {
709 .checked_sub(self.decayed_offset_msat(*self.max_liquidity_offset_msat))
713 fn decayed_offset_msat(&self, offset_msat: u64) -> u64 {
714 self.now.duration_since(*self.last_updated).as_secs()
715 .checked_div(self.half_life.as_secs())
716 .and_then(|decays| offset_msat.checked_shr(decays as u32))
721 impl<L: DerefMut<Target = u64>, T: Time, U: DerefMut<Target = T>> DirectedChannelLiquidity<L, T, U> {
722 /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat`.
723 fn failed_at_channel(&mut self, amount_msat: u64) {
724 if amount_msat < self.max_liquidity_msat() {
725 self.set_max_liquidity_msat(amount_msat);
729 /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat` downstream.
730 fn failed_downstream(&mut self, amount_msat: u64) {
731 if amount_msat > self.min_liquidity_msat() {
732 self.set_min_liquidity_msat(amount_msat);
736 /// Adjusts the channel liquidity balance bounds when successfully routing `amount_msat`.
737 fn successful(&mut self, amount_msat: u64) {
738 let max_liquidity_msat = self.max_liquidity_msat().checked_sub(amount_msat).unwrap_or(0);
739 self.set_max_liquidity_msat(max_liquidity_msat);
742 /// Adjusts the lower bound of the channel liquidity balance in this direction.
743 fn set_min_liquidity_msat(&mut self, amount_msat: u64) {
744 *self.min_liquidity_offset_msat = amount_msat;
745 *self.max_liquidity_offset_msat = if amount_msat > self.max_liquidity_msat() {
748 self.decayed_offset_msat(*self.max_liquidity_offset_msat)
750 *self.last_updated = self.now;
753 /// Adjusts the upper bound of the channel liquidity balance in this direction.
754 fn set_max_liquidity_msat(&mut self, amount_msat: u64) {
755 *self.max_liquidity_offset_msat = self.capacity_msat.checked_sub(amount_msat).unwrap_or(0);
756 *self.min_liquidity_offset_msat = if amount_msat < self.min_liquidity_msat() {
759 self.decayed_offset_msat(*self.min_liquidity_offset_msat)
761 *self.last_updated = self.now;
765 impl<G: Deref<Target = NetworkGraph>, T: Time> Score for ProbabilisticScorerUsingTime<G, T> {
766 fn channel_penalty_msat(
767 &self, short_channel_id: u64, amount_msat: u64, capacity_msat: u64, source: &NodeId,
770 let liquidity_penalty_multiplier_msat = self.params.liquidity_penalty_multiplier_msat;
771 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
772 let success_probability = self.channel_liquidities
773 .get(&short_channel_id)
774 .unwrap_or(&ChannelLiquidity::new())
775 .as_directed(source, target, capacity_msat, liquidity_offset_half_life)
776 .success_probability(amount_msat);
777 // NOTE: If success_probability is ever changed to return 0.0, log10 is undefined so return
778 // u64::max_value instead.
779 debug_assert!(success_probability > core::f64::EPSILON);
780 (-(success_probability.log10()) * liquidity_penalty_multiplier_msat as f64) as u64
783 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
784 let amount_msat = path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0);
785 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
786 let network_graph = self.network_graph.read_only();
788 let target = NodeId::from_pubkey(&hop.pubkey);
789 let channel_directed_from_source = network_graph.channels()
790 .get(&hop.short_channel_id)
791 .and_then(|channel| channel.as_directed_to(&target));
793 // Only score announced channels.
794 if let Some((channel, source)) = channel_directed_from_source {
795 let capacity_msat = channel.effective_capacity().as_msat();
796 if hop.short_channel_id == short_channel_id {
797 self.channel_liquidities
798 .entry(hop.short_channel_id)
799 .or_insert_with(ChannelLiquidity::new)
800 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
801 .failed_at_channel(amount_msat);
805 self.channel_liquidities
806 .entry(hop.short_channel_id)
807 .or_insert_with(ChannelLiquidity::new)
808 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
809 .failed_downstream(amount_msat);
814 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
815 let amount_msat = path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0);
816 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
817 let network_graph = self.network_graph.read_only();
819 let target = NodeId::from_pubkey(&hop.pubkey);
820 let channel_directed_from_source = network_graph.channels()
821 .get(&hop.short_channel_id)
822 .and_then(|channel| channel.as_directed_to(&target));
824 // Only score announced channels.
825 if let Some((channel, source)) = channel_directed_from_source {
826 let capacity_msat = channel.effective_capacity().as_msat();
827 self.channel_liquidities
828 .entry(hop.short_channel_id)
829 .or_insert_with(ChannelLiquidity::new)
830 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
831 .successful(amount_msat);
837 impl<G: Deref<Target = NetworkGraph>, T: Time> Writeable for ProbabilisticScorerUsingTime<G, T> {
839 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
840 write_tlv_fields!(w, {
841 (0, self.channel_liquidities, required)
847 impl<G: Deref<Target = NetworkGraph>, T: Time>
848 ReadableArgs<(ProbabilisticScoringParameters, G)> for ProbabilisticScorerUsingTime<G, T> {
851 r: &mut R, args: (ProbabilisticScoringParameters, G)
852 ) -> Result<Self, DecodeError> {
853 let (params, network_graph) = args;
854 let mut channel_liquidities = HashMap::new();
855 read_tlv_fields!(r, {
856 (0, channel_liquidities, required)
866 impl<T: Time> Writeable for ChannelLiquidity<T> {
868 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
869 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
870 write_tlv_fields!(w, {
871 (0, self.min_liquidity_offset_msat, required),
872 (2, self.max_liquidity_offset_msat, required),
873 (4, duration_since_epoch, required),
879 impl<T: Time> Readable for ChannelLiquidity<T> {
881 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
882 let mut min_liquidity_offset_msat = 0;
883 let mut max_liquidity_offset_msat = 0;
884 let mut duration_since_epoch = Duration::from_secs(0);
885 read_tlv_fields!(r, {
886 (0, min_liquidity_offset_msat, required),
887 (2, max_liquidity_offset_msat, required),
888 (4, duration_since_epoch, required),
891 min_liquidity_offset_msat,
892 max_liquidity_offset_msat,
893 last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
898 pub(crate) mod time {
900 use core::time::Duration;
901 /// A measurement of time.
902 pub trait Time: Copy + Sub<Duration, Output = Self> where Self: Sized {
903 /// Returns an instance corresponding to the current moment.
906 /// Returns the amount of time elapsed since `self` was created.
907 fn elapsed(&self) -> Duration;
909 /// Returns the amount of time passed between `earlier` and `self`.
910 fn duration_since(&self, earlier: Self) -> Duration;
912 /// Returns the amount of time passed since the beginning of [`Time`].
914 /// Used during (de-)serialization.
915 fn duration_since_epoch() -> Duration;
918 /// A state in which time has no meaning.
919 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
922 #[cfg(not(feature = "no-std"))]
923 impl Time for std::time::Instant {
925 std::time::Instant::now()
928 fn duration_since(&self, earlier: Self) -> Duration {
929 self.duration_since(earlier)
932 fn duration_since_epoch() -> Duration {
933 use std::time::SystemTime;
934 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
937 fn elapsed(&self) -> Duration {
938 std::time::Instant::elapsed(self)
942 impl Time for Eternity {
947 fn duration_since(&self, _earlier: Self) -> Duration {
948 Duration::from_secs(0)
951 fn duration_since_epoch() -> Duration {
952 Duration::from_secs(0)
955 fn elapsed(&self) -> Duration {
956 Duration::from_secs(0)
960 impl Sub<Duration> for Eternity {
963 fn sub(self, _other: Duration) -> Self {
969 pub(crate) use self::time::Time;
973 use super::{ChannelLiquidity, ProbabilisticScoringParameters, ProbabilisticScorerUsingTime, ScoringParameters, ScorerUsingTime, Time};
974 use super::time::Eternity;
976 use ln::features::{ChannelFeatures, NodeFeatures};
977 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, OptionalField, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
978 use routing::scoring::Score;
979 use routing::network_graph::{NetworkGraph, NodeId};
980 use routing::router::RouteHop;
981 use util::ser::{Readable, ReadableArgs, Writeable};
983 use bitcoin::blockdata::constants::genesis_block;
984 use bitcoin::hashes::Hash;
985 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
986 use bitcoin::network::constants::Network;
987 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
988 use core::cell::Cell;
990 use core::time::Duration;
995 /// Time that can be advanced manually in tests.
996 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
997 struct SinceEpoch(Duration);
1001 static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
1004 fn advance(duration: Duration) {
1005 Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
1009 impl Time for SinceEpoch {
1011 Self(Self::duration_since_epoch())
1014 fn duration_since(&self, earlier: Self) -> Duration {
1018 fn duration_since_epoch() -> Duration {
1019 Self::ELAPSED.with(|elapsed| elapsed.get())
1022 fn elapsed(&self) -> Duration {
1023 Self::duration_since_epoch() - self.0
1027 impl Sub<Duration> for SinceEpoch {
1030 fn sub(self, other: Duration) -> Self {
1031 Self(self.0 - other)
1036 fn time_passes_when_advanced() {
1037 let now = SinceEpoch::now();
1038 assert_eq!(now.elapsed(), Duration::from_secs(0));
1040 SinceEpoch::advance(Duration::from_secs(1));
1041 SinceEpoch::advance(Duration::from_secs(1));
1043 let elapsed = now.elapsed();
1044 let later = SinceEpoch::now();
1046 assert_eq!(elapsed, Duration::from_secs(2));
1047 assert_eq!(later - elapsed, now);
1051 fn time_never_passes_in_an_eternity() {
1052 let now = Eternity::now();
1053 let elapsed = now.elapsed();
1054 let later = Eternity::now();
1056 assert_eq!(now.elapsed(), Duration::from_secs(0));
1057 assert_eq!(later - elapsed, now);
1062 /// A scorer for testing with time that can be manually advanced.
1063 type Scorer = ScorerUsingTime::<SinceEpoch>;
1065 fn source_privkey() -> SecretKey {
1066 SecretKey::from_slice(&[42; 32]).unwrap()
1069 fn target_privkey() -> SecretKey {
1070 SecretKey::from_slice(&[43; 32]).unwrap()
1073 fn source_pubkey() -> PublicKey {
1074 let secp_ctx = Secp256k1::new();
1075 PublicKey::from_secret_key(&secp_ctx, &source_privkey())
1078 fn target_pubkey() -> PublicKey {
1079 let secp_ctx = Secp256k1::new();
1080 PublicKey::from_secret_key(&secp_ctx, &target_privkey())
1083 fn source_node_id() -> NodeId {
1084 NodeId::from_pubkey(&source_pubkey())
1087 fn target_node_id() -> NodeId {
1088 NodeId::from_pubkey(&target_pubkey())
1092 fn penalizes_without_channel_failures() {
1093 let scorer = Scorer::new(ScoringParameters {
1094 base_penalty_msat: 1_000,
1095 failure_penalty_msat: 512,
1096 failure_penalty_half_life: Duration::from_secs(1),
1097 overuse_penalty_start_1024th: 1024,
1098 overuse_penalty_msat_per_1024th: 0,
1100 let source = source_node_id();
1101 let target = target_node_id();
1102 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1104 SinceEpoch::advance(Duration::from_secs(1));
1105 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1109 fn accumulates_channel_failure_penalties() {
1110 let mut scorer = Scorer::new(ScoringParameters {
1111 base_penalty_msat: 1_000,
1112 failure_penalty_msat: 64,
1113 failure_penalty_half_life: Duration::from_secs(10),
1114 overuse_penalty_start_1024th: 1024,
1115 overuse_penalty_msat_per_1024th: 0,
1117 let source = source_node_id();
1118 let target = target_node_id();
1119 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1121 scorer.payment_path_failed(&[], 42);
1122 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1124 scorer.payment_path_failed(&[], 42);
1125 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1127 scorer.payment_path_failed(&[], 42);
1128 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_192);
1132 fn decays_channel_failure_penalties_over_time() {
1133 let mut scorer = Scorer::new(ScoringParameters {
1134 base_penalty_msat: 1_000,
1135 failure_penalty_msat: 512,
1136 failure_penalty_half_life: Duration::from_secs(10),
1137 overuse_penalty_start_1024th: 1024,
1138 overuse_penalty_msat_per_1024th: 0,
1140 let source = source_node_id();
1141 let target = target_node_id();
1142 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1144 scorer.payment_path_failed(&[], 42);
1145 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1147 SinceEpoch::advance(Duration::from_secs(9));
1148 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1150 SinceEpoch::advance(Duration::from_secs(1));
1151 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1153 SinceEpoch::advance(Duration::from_secs(10 * 8));
1154 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_001);
1156 SinceEpoch::advance(Duration::from_secs(10));
1157 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1159 SinceEpoch::advance(Duration::from_secs(10));
1160 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1164 fn decays_channel_failure_penalties_without_shift_overflow() {
1165 let mut scorer = Scorer::new(ScoringParameters {
1166 base_penalty_msat: 1_000,
1167 failure_penalty_msat: 512,
1168 failure_penalty_half_life: Duration::from_secs(10),
1169 overuse_penalty_start_1024th: 1024,
1170 overuse_penalty_msat_per_1024th: 0,
1172 let source = source_node_id();
1173 let target = target_node_id();
1174 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1176 scorer.payment_path_failed(&[], 42);
1177 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1179 // An unchecked right shift 64 bits or more in ChannelFailure::decayed_penalty_msat would
1180 // cause an overflow.
1181 SinceEpoch::advance(Duration::from_secs(10 * 64));
1182 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1184 SinceEpoch::advance(Duration::from_secs(10));
1185 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1189 fn accumulates_channel_failure_penalties_after_decay() {
1190 let mut scorer = Scorer::new(ScoringParameters {
1191 base_penalty_msat: 1_000,
1192 failure_penalty_msat: 512,
1193 failure_penalty_half_life: Duration::from_secs(10),
1194 overuse_penalty_start_1024th: 1024,
1195 overuse_penalty_msat_per_1024th: 0,
1197 let source = source_node_id();
1198 let target = target_node_id();
1199 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1201 scorer.payment_path_failed(&[], 42);
1202 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1204 SinceEpoch::advance(Duration::from_secs(10));
1205 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1207 scorer.payment_path_failed(&[], 42);
1208 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_768);
1210 SinceEpoch::advance(Duration::from_secs(10));
1211 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_384);
1215 fn reduces_channel_failure_penalties_after_success() {
1216 let mut scorer = Scorer::new(ScoringParameters {
1217 base_penalty_msat: 1_000,
1218 failure_penalty_msat: 512,
1219 failure_penalty_half_life: Duration::from_secs(10),
1220 overuse_penalty_start_1024th: 1024,
1221 overuse_penalty_msat_per_1024th: 0,
1223 let source = source_node_id();
1224 let target = target_node_id();
1225 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1227 scorer.payment_path_failed(&[], 42);
1228 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1230 SinceEpoch::advance(Duration::from_secs(10));
1231 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1233 let hop = RouteHop {
1234 pubkey: PublicKey::from_slice(target.as_slice()).unwrap(),
1235 node_features: NodeFeatures::known(),
1236 short_channel_id: 42,
1237 channel_features: ChannelFeatures::known(),
1239 cltv_expiry_delta: 18,
1241 scorer.payment_path_successful(&[&hop]);
1242 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1244 SinceEpoch::advance(Duration::from_secs(10));
1245 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1249 fn restores_persisted_channel_failure_penalties() {
1250 let mut scorer = Scorer::new(ScoringParameters {
1251 base_penalty_msat: 1_000,
1252 failure_penalty_msat: 512,
1253 failure_penalty_half_life: Duration::from_secs(10),
1254 overuse_penalty_start_1024th: 1024,
1255 overuse_penalty_msat_per_1024th: 0,
1257 let source = source_node_id();
1258 let target = target_node_id();
1260 scorer.payment_path_failed(&[], 42);
1261 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1263 SinceEpoch::advance(Duration::from_secs(10));
1264 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1266 scorer.payment_path_failed(&[], 43);
1267 assert_eq!(scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
1269 let mut serialized_scorer = Vec::new();
1270 scorer.write(&mut serialized_scorer).unwrap();
1272 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
1273 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1274 assert_eq!(deserialized_scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
1278 fn decays_persisted_channel_failure_penalties() {
1279 let mut scorer = Scorer::new(ScoringParameters {
1280 base_penalty_msat: 1_000,
1281 failure_penalty_msat: 512,
1282 failure_penalty_half_life: Duration::from_secs(10),
1283 overuse_penalty_start_1024th: 1024,
1284 overuse_penalty_msat_per_1024th: 0,
1286 let source = source_node_id();
1287 let target = target_node_id();
1289 scorer.payment_path_failed(&[], 42);
1290 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1292 let mut serialized_scorer = Vec::new();
1293 scorer.write(&mut serialized_scorer).unwrap();
1295 SinceEpoch::advance(Duration::from_secs(10));
1297 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
1298 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1300 SinceEpoch::advance(Duration::from_secs(10));
1301 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1305 fn charges_per_1024th_penalty() {
1306 let scorer = Scorer::new(ScoringParameters {
1307 base_penalty_msat: 0,
1308 failure_penalty_msat: 0,
1309 failure_penalty_half_life: Duration::from_secs(0),
1310 overuse_penalty_start_1024th: 256,
1311 overuse_penalty_msat_per_1024th: 100,
1313 let source = source_node_id();
1314 let target = target_node_id();
1316 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 1_024_000, &source, &target), 0);
1317 assert_eq!(scorer.channel_penalty_msat(42, 256_999, 1_024_000, &source, &target), 0);
1318 assert_eq!(scorer.channel_penalty_msat(42, 257_000, 1_024_000, &source, &target), 100);
1319 assert_eq!(scorer.channel_penalty_msat(42, 258_000, 1_024_000, &source, &target), 200);
1320 assert_eq!(scorer.channel_penalty_msat(42, 512_000, 1_024_000, &source, &target), 256 * 100);
1323 // `ProbabilisticScorer` tests
1325 /// A probabilistic scorer for testing with time that can be manually advanced.
1326 type ProbabilisticScorer<'a> = ProbabilisticScorerUsingTime::<&'a NetworkGraph, SinceEpoch>;
1328 fn sender_privkey() -> SecretKey {
1329 SecretKey::from_slice(&[41; 32]).unwrap()
1332 fn recipient_privkey() -> SecretKey {
1333 SecretKey::from_slice(&[45; 32]).unwrap()
1336 fn sender_pubkey() -> PublicKey {
1337 let secp_ctx = Secp256k1::new();
1338 PublicKey::from_secret_key(&secp_ctx, &sender_privkey())
1341 fn recipient_pubkey() -> PublicKey {
1342 let secp_ctx = Secp256k1::new();
1343 PublicKey::from_secret_key(&secp_ctx, &recipient_privkey())
1346 fn sender_node_id() -> NodeId {
1347 NodeId::from_pubkey(&sender_pubkey())
1350 fn recipient_node_id() -> NodeId {
1351 NodeId::from_pubkey(&recipient_pubkey())
1354 fn network_graph() -> NetworkGraph {
1355 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1356 let mut network_graph = NetworkGraph::new(genesis_hash);
1357 add_channel(&mut network_graph, 42, source_privkey(), target_privkey());
1358 add_channel(&mut network_graph, 43, target_privkey(), recipient_privkey());
1364 network_graph: &mut NetworkGraph, short_channel_id: u64, node_1_key: SecretKey,
1365 node_2_key: SecretKey
1367 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1368 let node_1_secret = &SecretKey::from_slice(&[39; 32]).unwrap();
1369 let node_2_secret = &SecretKey::from_slice(&[40; 32]).unwrap();
1370 let secp_ctx = Secp256k1::new();
1371 let unsigned_announcement = UnsignedChannelAnnouncement {
1372 features: ChannelFeatures::known(),
1373 chain_hash: genesis_hash,
1375 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_key),
1376 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_key),
1377 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_secret),
1378 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_secret),
1379 excess_data: Vec::new(),
1381 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1382 let signed_announcement = ChannelAnnouncement {
1383 node_signature_1: secp_ctx.sign(&msghash, &node_1_key),
1384 node_signature_2: secp_ctx.sign(&msghash, &node_2_key),
1385 bitcoin_signature_1: secp_ctx.sign(&msghash, &node_1_secret),
1386 bitcoin_signature_2: secp_ctx.sign(&msghash, &node_2_secret),
1387 contents: unsigned_announcement,
1389 let chain_source: Option<&::util::test_utils::TestChainSource> = None;
1390 network_graph.update_channel_from_announcement(
1391 &signed_announcement, &chain_source, &secp_ctx).unwrap();
1392 update_channel(network_graph, short_channel_id, node_1_key, 0);
1393 update_channel(network_graph, short_channel_id, node_2_key, 1);
1397 network_graph: &mut NetworkGraph, short_channel_id: u64, node_key: SecretKey, flags: u8
1399 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1400 let secp_ctx = Secp256k1::new();
1401 let unsigned_update = UnsignedChannelUpdate {
1402 chain_hash: genesis_hash,
1406 cltv_expiry_delta: 18,
1407 htlc_minimum_msat: 0,
1408 htlc_maximum_msat: OptionalField::Present(1_000),
1410 fee_proportional_millionths: 0,
1411 excess_data: Vec::new(),
1413 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_update.encode()[..])[..]);
1414 let signed_update = ChannelUpdate {
1415 signature: secp_ctx.sign(&msghash, &node_key),
1416 contents: unsigned_update,
1418 network_graph.update_channel(&signed_update, &secp_ctx).unwrap();
1421 fn payment_path_for_amount(amount_msat: u64) -> Vec<RouteHop> {
1424 pubkey: source_pubkey(),
1425 node_features: NodeFeatures::known(),
1426 short_channel_id: 41,
1427 channel_features: ChannelFeatures::known(),
1429 cltv_expiry_delta: 18,
1432 pubkey: target_pubkey(),
1433 node_features: NodeFeatures::known(),
1434 short_channel_id: 42,
1435 channel_features: ChannelFeatures::known(),
1437 cltv_expiry_delta: 18,
1440 pubkey: recipient_pubkey(),
1441 node_features: NodeFeatures::known(),
1442 short_channel_id: 43,
1443 channel_features: ChannelFeatures::known(),
1444 fee_msat: amount_msat,
1445 cltv_expiry_delta: 18,
1451 fn liquidity_bounds_directed_from_lowest_node_id() {
1452 let last_updated = SinceEpoch::now();
1453 let network_graph = network_graph();
1454 let params = ProbabilisticScoringParameters::default();
1455 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1458 min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1462 min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1464 let source = source_node_id();
1465 let target = target_node_id();
1466 let recipient = recipient_node_id();
1467 assert!(source > target);
1468 assert!(target < recipient);
1470 // Update minimum liquidity.
1472 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1473 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1474 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1475 assert_eq!(liquidity.min_liquidity_msat(), 100);
1476 assert_eq!(liquidity.max_liquidity_msat(), 300);
1478 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1479 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1480 assert_eq!(liquidity.min_liquidity_msat(), 700);
1481 assert_eq!(liquidity.max_liquidity_msat(), 900);
1483 scorer.channel_liquidities.get_mut(&42).unwrap()
1484 .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1485 .set_min_liquidity_msat(200);
1487 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1488 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1489 assert_eq!(liquidity.min_liquidity_msat(), 200);
1490 assert_eq!(liquidity.max_liquidity_msat(), 300);
1492 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1493 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1494 assert_eq!(liquidity.min_liquidity_msat(), 700);
1495 assert_eq!(liquidity.max_liquidity_msat(), 800);
1497 // Update maximum liquidity.
1499 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1500 .as_directed(&target, &recipient, 1_000, liquidity_offset_half_life);
1501 assert_eq!(liquidity.min_liquidity_msat(), 700);
1502 assert_eq!(liquidity.max_liquidity_msat(), 900);
1504 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1505 .as_directed(&recipient, &target, 1_000, liquidity_offset_half_life);
1506 assert_eq!(liquidity.min_liquidity_msat(), 100);
1507 assert_eq!(liquidity.max_liquidity_msat(), 300);
1509 scorer.channel_liquidities.get_mut(&43).unwrap()
1510 .as_directed_mut(&target, &recipient, 1_000, liquidity_offset_half_life)
1511 .set_max_liquidity_msat(200);
1513 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1514 .as_directed(&target, &recipient, 1_000, liquidity_offset_half_life);
1515 assert_eq!(liquidity.min_liquidity_msat(), 0);
1516 assert_eq!(liquidity.max_liquidity_msat(), 200);
1518 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1519 .as_directed(&recipient, &target, 1_000, liquidity_offset_half_life);
1520 assert_eq!(liquidity.min_liquidity_msat(), 800);
1521 assert_eq!(liquidity.max_liquidity_msat(), 1000);
1525 fn resets_liquidity_upper_bound_when_crossed_by_lower_bound() {
1526 let last_updated = SinceEpoch::now();
1527 let network_graph = network_graph();
1528 let params = ProbabilisticScoringParameters::default();
1529 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1532 min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1534 let source = source_node_id();
1535 let target = target_node_id();
1536 assert!(source > target);
1538 // Check initial bounds.
1539 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1540 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1541 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1542 assert_eq!(liquidity.min_liquidity_msat(), 400);
1543 assert_eq!(liquidity.max_liquidity_msat(), 800);
1545 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1546 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1547 assert_eq!(liquidity.min_liquidity_msat(), 200);
1548 assert_eq!(liquidity.max_liquidity_msat(), 600);
1550 // Reset from source to target.
1551 scorer.channel_liquidities.get_mut(&42).unwrap()
1552 .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1553 .set_min_liquidity_msat(900);
1555 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1556 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1557 assert_eq!(liquidity.min_liquidity_msat(), 900);
1558 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1560 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1561 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1562 assert_eq!(liquidity.min_liquidity_msat(), 0);
1563 assert_eq!(liquidity.max_liquidity_msat(), 100);
1565 // Reset from target to source.
1566 scorer.channel_liquidities.get_mut(&42).unwrap()
1567 .as_directed_mut(&target, &source, 1_000, liquidity_offset_half_life)
1568 .set_min_liquidity_msat(400);
1570 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1571 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1572 assert_eq!(liquidity.min_liquidity_msat(), 0);
1573 assert_eq!(liquidity.max_liquidity_msat(), 600);
1575 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1576 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1577 assert_eq!(liquidity.min_liquidity_msat(), 400);
1578 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1582 fn resets_liquidity_lower_bound_when_crossed_by_upper_bound() {
1583 let last_updated = SinceEpoch::now();
1584 let network_graph = network_graph();
1585 let params = ProbabilisticScoringParameters::default();
1586 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1589 min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1591 let source = source_node_id();
1592 let target = target_node_id();
1593 assert!(source > target);
1595 // Check initial bounds.
1596 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1597 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1598 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1599 assert_eq!(liquidity.min_liquidity_msat(), 400);
1600 assert_eq!(liquidity.max_liquidity_msat(), 800);
1602 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1603 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1604 assert_eq!(liquidity.min_liquidity_msat(), 200);
1605 assert_eq!(liquidity.max_liquidity_msat(), 600);
1607 // Reset from source to target.
1608 scorer.channel_liquidities.get_mut(&42).unwrap()
1609 .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1610 .set_max_liquidity_msat(300);
1612 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1613 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1614 assert_eq!(liquidity.min_liquidity_msat(), 0);
1615 assert_eq!(liquidity.max_liquidity_msat(), 300);
1617 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1618 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1619 assert_eq!(liquidity.min_liquidity_msat(), 700);
1620 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1622 // Reset from target to source.
1623 scorer.channel_liquidities.get_mut(&42).unwrap()
1624 .as_directed_mut(&target, &source, 1_000, liquidity_offset_half_life)
1625 .set_max_liquidity_msat(600);
1627 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1628 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1629 assert_eq!(liquidity.min_liquidity_msat(), 400);
1630 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1632 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1633 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1634 assert_eq!(liquidity.min_liquidity_msat(), 0);
1635 assert_eq!(liquidity.max_liquidity_msat(), 600);
1639 fn increased_penalty_nearing_liquidity_upper_bound() {
1640 let network_graph = network_graph();
1641 let params = ProbabilisticScoringParameters {
1642 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1644 let scorer = ProbabilisticScorer::new(params, &network_graph);
1645 let source = source_node_id();
1646 let target = target_node_id();
1648 assert_eq!(scorer.channel_penalty_msat(42, 100, 100_000, &source, &target), 0);
1649 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 100_000, &source, &target), 4);
1650 assert_eq!(scorer.channel_penalty_msat(42, 10_000, 100_000, &source, &target), 45);
1651 assert_eq!(scorer.channel_penalty_msat(42, 100_000, 100_000, &source, &target), 2_000);
1653 assert_eq!(scorer.channel_penalty_msat(42, 125, 1_000, &source, &target), 57);
1654 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1655 assert_eq!(scorer.channel_penalty_msat(42, 375, 1_000, &source, &target), 203);
1656 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1657 assert_eq!(scorer.channel_penalty_msat(42, 625, 1_000, &source, &target), 425);
1658 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1659 assert_eq!(scorer.channel_penalty_msat(42, 875, 1_000, &source, &target), 900);
1663 fn constant_penalty_outside_liquidity_bounds() {
1664 let last_updated = SinceEpoch::now();
1665 let network_graph = network_graph();
1666 let params = ProbabilisticScoringParameters {
1667 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1669 let scorer = ProbabilisticScorer::new(params, &network_graph)
1672 min_liquidity_offset_msat: 40, max_liquidity_offset_msat: 40, last_updated
1674 let source = source_node_id();
1675 let target = target_node_id();
1677 assert_eq!(scorer.channel_penalty_msat(42, 39, 100, &source, &target), 0);
1678 assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 0);
1679 assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 2_000);
1680 assert_eq!(scorer.channel_penalty_msat(42, 61, 100, &source, &target), 2_000);
1684 fn does_not_further_penalize_own_channel() {
1685 let network_graph = network_graph();
1686 let params = ProbabilisticScoringParameters {
1687 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1689 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1690 let sender = sender_node_id();
1691 let source = source_node_id();
1692 let failed_path = payment_path_for_amount(500);
1693 let successful_path = payment_path_for_amount(200);
1695 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1697 scorer.payment_path_failed(&failed_path.iter().collect::<Vec<_>>(), 41);
1698 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1700 scorer.payment_path_successful(&successful_path.iter().collect::<Vec<_>>());
1701 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1705 fn sets_liquidity_lower_bound_on_downstream_failure() {
1706 let network_graph = network_graph();
1707 let params = ProbabilisticScoringParameters {
1708 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1710 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1711 let source = source_node_id();
1712 let target = target_node_id();
1713 let path = payment_path_for_amount(500);
1715 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1716 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1717 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1719 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 43);
1721 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 0);
1722 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 0);
1723 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 300);
1727 fn sets_liquidity_upper_bound_on_failure() {
1728 let network_graph = network_graph();
1729 let params = ProbabilisticScoringParameters {
1730 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1732 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1733 let source = source_node_id();
1734 let target = target_node_id();
1735 let path = payment_path_for_amount(500);
1737 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1738 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1739 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1741 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 42);
1743 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 300);
1744 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1745 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 2_000);
1749 fn reduces_liquidity_upper_bound_along_path_on_success() {
1750 let network_graph = network_graph();
1751 let params = ProbabilisticScoringParameters {
1752 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1754 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1755 let sender = sender_node_id();
1756 let source = source_node_id();
1757 let target = target_node_id();
1758 let recipient = recipient_node_id();
1759 let path = payment_path_for_amount(500);
1761 assert_eq!(scorer.channel_penalty_msat(41, 250, 1_000, &sender, &source), 124);
1762 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1763 assert_eq!(scorer.channel_penalty_msat(43, 250, 1_000, &target, &recipient), 124);
1765 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
1767 assert_eq!(scorer.channel_penalty_msat(41, 250, 1_000, &sender, &source), 124);
1768 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 300);
1769 assert_eq!(scorer.channel_penalty_msat(43, 250, 1_000, &target, &recipient), 300);
1773 fn decays_liquidity_bounds_over_time() {
1774 let network_graph = network_graph();
1775 let params = ProbabilisticScoringParameters {
1776 liquidity_penalty_multiplier_msat: 1_000,
1777 liquidity_offset_half_life: Duration::from_secs(10),
1779 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1780 let source = source_node_id();
1781 let target = target_node_id();
1783 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1784 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1786 scorer.payment_path_failed(&payment_path_for_amount(768).iter().collect::<Vec<_>>(), 42);
1787 scorer.payment_path_failed(&payment_path_for_amount(128).iter().collect::<Vec<_>>(), 43);
1789 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
1790 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 92);
1791 assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_424);
1792 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
1794 SinceEpoch::advance(Duration::from_secs(9));
1795 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
1796 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 92);
1797 assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_424);
1798 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
1800 SinceEpoch::advance(Duration::from_secs(1));
1801 assert_eq!(scorer.channel_penalty_msat(42, 64, 1_024, &source, &target), 0);
1802 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 34);
1803 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 1_812);
1804 assert_eq!(scorer.channel_penalty_msat(42, 960, 1_024, &source, &target), 2_000);
1806 // Fully decay liquidity lower bound.
1807 SinceEpoch::advance(Duration::from_secs(10 * 7));
1808 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1809 assert_eq!(scorer.channel_penalty_msat(42, 1, 1_024, &source, &target), 0);
1810 assert_eq!(scorer.channel_penalty_msat(42, 1_023, 1_024, &source, &target), 2_000);
1811 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1813 // Fully decay liquidity upper bound.
1814 SinceEpoch::advance(Duration::from_secs(10));
1815 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1816 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1818 SinceEpoch::advance(Duration::from_secs(10));
1819 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1820 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1824 fn decays_liquidity_bounds_without_shift_overflow() {
1825 let network_graph = network_graph();
1826 let params = ProbabilisticScoringParameters {
1827 liquidity_penalty_multiplier_msat: 1_000,
1828 liquidity_offset_half_life: Duration::from_secs(10),
1830 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1831 let source = source_node_id();
1832 let target = target_node_id();
1833 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1835 scorer.payment_path_failed(&payment_path_for_amount(512).iter().collect::<Vec<_>>(), 42);
1836 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 281);
1838 // An unchecked right shift 64 bits or more in DirectedChannelLiquidity::decayed_offset_msat
1839 // would cause an overflow.
1840 SinceEpoch::advance(Duration::from_secs(10 * 64));
1841 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1843 SinceEpoch::advance(Duration::from_secs(10));
1844 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1848 fn restricts_liquidity_bounds_after_decay() {
1849 let network_graph = network_graph();
1850 let params = ProbabilisticScoringParameters {
1851 liquidity_penalty_multiplier_msat: 1_000,
1852 liquidity_offset_half_life: Duration::from_secs(10),
1854 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1855 let source = source_node_id();
1856 let target = target_node_id();
1858 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 300);
1860 // More knowledge gives higher confidence (256, 768), meaning a lower penalty.
1861 scorer.payment_path_failed(&payment_path_for_amount(768).iter().collect::<Vec<_>>(), 42);
1862 scorer.payment_path_failed(&payment_path_for_amount(256).iter().collect::<Vec<_>>(), 43);
1863 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 281);
1865 // Decaying knowledge gives less confidence (128, 896), meaning a higher penalty.
1866 SinceEpoch::advance(Duration::from_secs(10));
1867 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 293);
1869 // Reducing the upper bound gives more confidence (128, 832) that the payment amount (512)
1870 // is closer to the upper bound, meaning a higher penalty.
1871 scorer.payment_path_successful(&payment_path_for_amount(64).iter().collect::<Vec<_>>());
1872 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 333);
1874 // Increasing the lower bound gives more confidence (256, 832) that the payment amount (512)
1875 // is closer to the lower bound, meaning a lower penalty.
1876 scorer.payment_path_failed(&payment_path_for_amount(256).iter().collect::<Vec<_>>(), 43);
1877 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 247);
1879 // Further decaying affects the lower bound more than the upper bound (128, 928).
1880 SinceEpoch::advance(Duration::from_secs(10));
1881 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 280);
1885 fn restores_persisted_liquidity_bounds() {
1886 let network_graph = network_graph();
1887 let params = ProbabilisticScoringParameters {
1888 liquidity_penalty_multiplier_msat: 1_000,
1889 liquidity_offset_half_life: Duration::from_secs(10),
1891 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1892 let source = source_node_id();
1893 let target = target_node_id();
1895 scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
1896 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1898 SinceEpoch::advance(Duration::from_secs(10));
1899 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 475);
1901 scorer.payment_path_failed(&payment_path_for_amount(250).iter().collect::<Vec<_>>(), 43);
1902 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1904 let mut serialized_scorer = Vec::new();
1905 scorer.write(&mut serialized_scorer).unwrap();
1907 let mut serialized_scorer = io::Cursor::new(&serialized_scorer);
1908 let deserialized_scorer =
1909 <ProbabilisticScorer>::read(&mut serialized_scorer, (params, &network_graph)).unwrap();
1910 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1914 fn decays_persisted_liquidity_bounds() {
1915 let network_graph = network_graph();
1916 let params = ProbabilisticScoringParameters {
1917 liquidity_penalty_multiplier_msat: 1_000,
1918 liquidity_offset_half_life: Duration::from_secs(10),
1920 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1921 let source = source_node_id();
1922 let target = target_node_id();
1924 scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
1925 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1927 let mut serialized_scorer = Vec::new();
1928 scorer.write(&mut serialized_scorer).unwrap();
1930 SinceEpoch::advance(Duration::from_secs(10));
1932 let mut serialized_scorer = io::Cursor::new(&serialized_scorer);
1933 let deserialized_scorer =
1934 <ProbabilisticScorer>::read(&mut serialized_scorer, (params, &network_graph)).unwrap();
1935 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 475);
1937 scorer.payment_path_failed(&payment_path_for_amount(250).iter().collect::<Vec<_>>(), 43);
1938 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1940 SinceEpoch::advance(Duration::from_secs(10));
1941 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 367);