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 /// [`Score`] implementation that provides reasonable default behavior.
220 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
221 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
223 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
227 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
230 /// [module-level documentation]: crate::routing::scoring
233 note = "ProbabilisticScorer should be used instead of Scorer.",
235 pub type Scorer = ScorerUsingTime::<ConfiguredTime>;
237 #[cfg(not(feature = "no-std"))]
238 type ConfiguredTime = std::time::Instant;
239 #[cfg(feature = "no-std")]
240 type ConfiguredTime = time::Eternity;
242 // Note that ideally we'd hide ScorerUsingTime from public view by sealing it as well, but rustdoc
243 // doesn't handle this well - instead exposing a `Scorer` which has no trait implementation(s) or
246 /// [`Score`] implementation.
248 /// (C-not exported) generally all users should use the [`Scorer`] type alias.
250 pub struct ScorerUsingTime<T: Time> {
251 params: ScoringParameters,
252 // TODO: Remove entries of closed channels.
253 channel_failures: HashMap<u64, ChannelFailure<T>>,
256 /// Parameters for configuring [`Scorer`].
257 pub struct ScoringParameters {
258 /// A fixed penalty in msats to apply to each channel.
260 /// Default value: 500 msat
261 pub base_penalty_msat: u64,
263 /// A penalty in msats to apply to a channel upon failing to relay a payment.
265 /// This accumulates for each failure but may be reduced over time based on
266 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
268 /// Default value: 1,024,000 msat
270 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
271 pub failure_penalty_msat: u64,
273 /// When the amount being sent over a channel is this many 1024ths of the total channel
274 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
276 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
278 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
279 pub overuse_penalty_start_1024th: u16,
281 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
282 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
284 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
285 /// to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
287 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
288 pub overuse_penalty_msat_per_1024th: u64,
290 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
293 /// Successfully routing through a channel will immediately cut the penalty in half as well.
295 /// Default value: 1 hour
299 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
302 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
303 pub failure_penalty_half_life: Duration,
306 impl_writeable_tlv_based!(ScoringParameters, {
307 (0, base_penalty_msat, required),
308 (1, overuse_penalty_start_1024th, (default_value, 128)),
309 (2, failure_penalty_msat, required),
310 (3, overuse_penalty_msat_per_1024th, (default_value, 20)),
311 (4, failure_penalty_half_life, required),
314 /// Accounting for penalties against a channel for failing to relay any payments.
316 /// Penalties decay over time, though accumulate as more failures occur.
317 struct ChannelFailure<T: Time> {
318 /// Accumulated penalty in msats for the channel as of `last_updated`.
319 undecayed_penalty_msat: u64,
321 /// Last time the channel either failed to route or successfully routed a payment. Used to decay
322 /// `undecayed_penalty_msat`.
326 impl<T: Time> ScorerUsingTime<T> {
327 /// Creates a new scorer using the given scoring parameters.
328 pub fn new(params: ScoringParameters) -> Self {
331 channel_failures: HashMap::new(),
336 impl<T: Time> ChannelFailure<T> {
337 fn new(failure_penalty_msat: u64) -> Self {
339 undecayed_penalty_msat: failure_penalty_msat,
340 last_updated: T::now(),
344 fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
345 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
346 self.last_updated = T::now();
349 fn reduce_penalty(&mut self, half_life: Duration) {
350 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) >> 1;
351 self.last_updated = T::now();
354 fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
355 self.last_updated.elapsed().as_secs()
356 .checked_div(half_life.as_secs())
357 .and_then(|decays| self.undecayed_penalty_msat.checked_shr(decays as u32))
362 impl<T: Time> Default for ScorerUsingTime<T> {
363 fn default() -> Self {
364 Self::new(ScoringParameters::default())
368 impl Default for ScoringParameters {
369 fn default() -> Self {
371 base_penalty_msat: 500,
372 failure_penalty_msat: 1024 * 1000,
373 failure_penalty_half_life: Duration::from_secs(3600),
374 overuse_penalty_start_1024th: 1024 / 8,
375 overuse_penalty_msat_per_1024th: 20,
380 impl<T: Time> Score for ScorerUsingTime<T> {
381 fn channel_penalty_msat(
382 &self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, _source: &NodeId, _target: &NodeId
384 let failure_penalty_msat = self.channel_failures
385 .get(&short_channel_id)
386 .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
388 let mut penalty_msat = self.params.base_penalty_msat + failure_penalty_msat;
389 let send_1024ths = send_amt_msat.checked_mul(1024).unwrap_or(u64::max_value()) / capacity_msat;
390 if send_1024ths > self.params.overuse_penalty_start_1024th as u64 {
391 penalty_msat = penalty_msat.checked_add(
392 (send_1024ths - self.params.overuse_penalty_start_1024th as u64)
393 .checked_mul(self.params.overuse_penalty_msat_per_1024th).unwrap_or(u64::max_value()))
394 .unwrap_or(u64::max_value());
400 fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
401 let failure_penalty_msat = self.params.failure_penalty_msat;
402 let half_life = self.params.failure_penalty_half_life;
403 self.channel_failures
404 .entry(short_channel_id)
405 .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
406 .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
409 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
410 let half_life = self.params.failure_penalty_half_life;
411 for hop in path.iter() {
412 self.channel_failures
413 .entry(hop.short_channel_id)
414 .and_modify(|failure| failure.reduce_penalty(half_life));
419 impl<T: Time> Writeable for ScorerUsingTime<T> {
421 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
422 self.params.write(w)?;
423 self.channel_failures.write(w)?;
424 write_tlv_fields!(w, {});
429 impl<T: Time> Readable for ScorerUsingTime<T> {
431 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
433 params: Readable::read(r)?,
434 channel_failures: Readable::read(r)?,
436 read_tlv_fields!(r, {});
441 impl<T: Time> Writeable for ChannelFailure<T> {
443 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
444 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
445 write_tlv_fields!(w, {
446 (0, self.undecayed_penalty_msat, required),
447 (2, duration_since_epoch, required),
453 impl<T: Time> Readable for ChannelFailure<T> {
455 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
456 let mut undecayed_penalty_msat = 0;
457 let mut duration_since_epoch = Duration::from_secs(0);
458 read_tlv_fields!(r, {
459 (0, undecayed_penalty_msat, required),
460 (2, duration_since_epoch, required),
463 undecayed_penalty_msat,
464 last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
469 /// [`Score`] implementation using channel success probability distributions.
471 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
472 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
473 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
474 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
475 /// specific HTLC amount through a channel.
477 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
478 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
479 /// [`ProbabilisticScoringParameters`] for details.
481 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
482 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
483 /// volume are more likely to experience failed payment paths, which would need to be retried.
487 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
490 /// [1]: https://arxiv.org/abs/2107.05322
491 pub type ProbabilisticScorer<G> = ProbabilisticScorerUsingTime::<G, ConfiguredTime>;
493 /// Probabilistic [`Score`] implementation.
495 /// (C-not exported) generally all users should use the [`ProbabilisticScorer`] type alias.
497 pub struct ProbabilisticScorerUsingTime<G: Deref<Target = NetworkGraph>, T: Time> {
498 params: ProbabilisticScoringParameters,
500 // TODO: Remove entries of closed channels.
501 channel_liquidities: HashMap<u64, ChannelLiquidity<T>>,
504 /// Parameters for configuring [`ProbabilisticScorer`].
505 #[derive(Clone, Copy)]
506 pub struct ProbabilisticScoringParameters {
507 /// A multiplier used to determine the amount in msats willing to be paid to avoid routing
508 /// through a channel, as per multiplying by the negative `log10` of the channel's success
509 /// probability for a payment.
511 /// The success probability is determined by the effective channel capacity, the payment amount,
512 /// and knowledge learned from prior successful and unsuccessful payments. The lower bound of
513 /// the success probability is 0.01, effectively limiting the penalty to the range
514 /// `0..=2*liquidity_penalty_multiplier_msat`. The knowledge learned is decayed over time based
515 /// on [`liquidity_offset_half_life`].
517 /// Default value: 10,000 msat
519 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
520 pub liquidity_penalty_multiplier_msat: u64,
522 /// The time required to elapse before any knowledge learned about channel liquidity balances is
525 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
526 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
527 /// the certainty of the channel liquidity balance.
529 /// Default value: 1 hour
533 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
534 /// liquidity knowledge will never decay except when the bounds cross.
535 pub liquidity_offset_half_life: Duration,
538 impl_writeable_tlv_based!(ProbabilisticScoringParameters, {
539 (0, liquidity_penalty_multiplier_msat, required),
540 (2, liquidity_offset_half_life, required),
543 /// Accounting for channel liquidity balance uncertainty.
545 /// Direction is defined in terms of [`NodeId`] partial ordering, where the source node is the
546 /// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
547 /// offset fields gives the opposite direction.
548 struct ChannelLiquidity<T: Time> {
549 /// Lower channel liquidity bound in terms of an offset from zero.
550 min_liquidity_offset_msat: u64,
552 /// Upper channel liquidity bound in terms of an offset from the effective capacity.
553 max_liquidity_offset_msat: u64,
555 /// Time when the liquidity bounds were last modified.
559 /// A snapshot of [`ChannelLiquidity`] in one direction assuming a certain channel capacity and
560 /// decayed with a given half life.
561 struct DirectedChannelLiquidity<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> {
562 min_liquidity_offset_msat: L,
563 max_liquidity_offset_msat: L,
570 impl<G: Deref<Target = NetworkGraph>, T: Time> ProbabilisticScorerUsingTime<G, T> {
571 /// Creates a new scorer using the given scoring parameters for sending payments from a node
572 /// through a network graph.
573 pub fn new(params: ProbabilisticScoringParameters, network_graph: G) -> Self {
577 channel_liquidities: HashMap::new(),
582 fn with_channel(mut self, short_channel_id: u64, liquidity: ChannelLiquidity<T>) -> Self {
583 assert!(self.channel_liquidities.insert(short_channel_id, liquidity).is_none());
588 impl Default for ProbabilisticScoringParameters {
589 fn default() -> Self {
591 liquidity_penalty_multiplier_msat: 10_000,
592 liquidity_offset_half_life: Duration::from_secs(3600),
597 impl<T: Time> ChannelLiquidity<T> {
601 min_liquidity_offset_msat: 0,
602 max_liquidity_offset_msat: 0,
603 last_updated: T::now(),
607 /// Returns a view of the channel liquidity directed from `source` to `target` assuming
610 &self, source: &NodeId, target: &NodeId, capacity_msat: u64, half_life: Duration
611 ) -> DirectedChannelLiquidity<&u64, T, &T> {
612 let (min_liquidity_offset_msat, max_liquidity_offset_msat) = if source < target {
613 (&self.min_liquidity_offset_msat, &self.max_liquidity_offset_msat)
615 (&self.max_liquidity_offset_msat, &self.min_liquidity_offset_msat)
618 DirectedChannelLiquidity {
619 min_liquidity_offset_msat,
620 max_liquidity_offset_msat,
622 last_updated: &self.last_updated,
628 /// Returns a mutable view of the channel liquidity directed from `source` to `target` assuming
631 &mut self, source: &NodeId, target: &NodeId, capacity_msat: u64, half_life: Duration
632 ) -> DirectedChannelLiquidity<&mut u64, T, &mut T> {
633 let (min_liquidity_offset_msat, max_liquidity_offset_msat) = if source < target {
634 (&mut self.min_liquidity_offset_msat, &mut self.max_liquidity_offset_msat)
636 (&mut self.max_liquidity_offset_msat, &mut self.min_liquidity_offset_msat)
639 DirectedChannelLiquidity {
640 min_liquidity_offset_msat,
641 max_liquidity_offset_msat,
643 last_updated: &mut self.last_updated,
650 impl<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> DirectedChannelLiquidity<L, T, U> {
651 /// Returns the success probability of routing the given HTLC `amount_msat` through the channel
652 /// in this direction.
653 fn success_probability(&self, amount_msat: u64) -> f64 {
654 let max_liquidity_msat = self.max_liquidity_msat();
655 let min_liquidity_msat = core::cmp::min(self.min_liquidity_msat(), max_liquidity_msat);
656 if amount_msat > max_liquidity_msat {
658 } else if amount_msat <= min_liquidity_msat {
661 let numerator = max_liquidity_msat + 1 - amount_msat;
662 let denominator = max_liquidity_msat + 1 - min_liquidity_msat;
663 numerator as f64 / denominator as f64
664 }.max(0.01) // Lower bound the success probability to ensure some channel is selected.
667 /// Returns the lower bound of the channel liquidity balance in this direction.
668 fn min_liquidity_msat(&self) -> u64 {
669 self.decayed_offset_msat(*self.min_liquidity_offset_msat)
672 /// Returns the upper bound of the channel liquidity balance in this direction.
673 fn max_liquidity_msat(&self) -> u64 {
675 .checked_sub(self.decayed_offset_msat(*self.max_liquidity_offset_msat))
679 fn decayed_offset_msat(&self, offset_msat: u64) -> u64 {
680 self.now.duration_since(*self.last_updated).as_secs()
681 .checked_div(self.half_life.as_secs())
682 .and_then(|decays| offset_msat.checked_shr(decays as u32))
687 impl<L: DerefMut<Target = u64>, T: Time, U: DerefMut<Target = T>> DirectedChannelLiquidity<L, T, U> {
688 /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat`.
689 fn failed_at_channel(&mut self, amount_msat: u64) {
690 if amount_msat < self.max_liquidity_msat() {
691 self.set_max_liquidity_msat(amount_msat);
695 /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat` downstream.
696 fn failed_downstream(&mut self, amount_msat: u64) {
697 if amount_msat > self.min_liquidity_msat() {
698 self.set_min_liquidity_msat(amount_msat);
702 /// Adjusts the channel liquidity balance bounds when successfully routing `amount_msat`.
703 fn successful(&mut self, amount_msat: u64) {
704 let max_liquidity_msat = self.max_liquidity_msat().checked_sub(amount_msat).unwrap_or(0);
705 self.set_max_liquidity_msat(max_liquidity_msat);
708 /// Adjusts the lower bound of the channel liquidity balance in this direction.
709 fn set_min_liquidity_msat(&mut self, amount_msat: u64) {
710 *self.min_liquidity_offset_msat = amount_msat;
711 *self.max_liquidity_offset_msat = if amount_msat > self.max_liquidity_msat() {
714 self.decayed_offset_msat(*self.max_liquidity_offset_msat)
716 *self.last_updated = self.now;
719 /// Adjusts the upper bound of the channel liquidity balance in this direction.
720 fn set_max_liquidity_msat(&mut self, amount_msat: u64) {
721 *self.max_liquidity_offset_msat = self.capacity_msat.checked_sub(amount_msat).unwrap_or(0);
722 *self.min_liquidity_offset_msat = if amount_msat < self.min_liquidity_msat() {
725 self.decayed_offset_msat(*self.min_liquidity_offset_msat)
727 *self.last_updated = self.now;
731 impl<G: Deref<Target = NetworkGraph>, T: Time> Score for ProbabilisticScorerUsingTime<G, T> {
732 fn channel_penalty_msat(
733 &self, short_channel_id: u64, amount_msat: u64, capacity_msat: u64, source: &NodeId,
736 let liquidity_penalty_multiplier_msat = self.params.liquidity_penalty_multiplier_msat;
737 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
738 let success_probability = self.channel_liquidities
739 .get(&short_channel_id)
740 .unwrap_or(&ChannelLiquidity::new())
741 .as_directed(source, target, capacity_msat, liquidity_offset_half_life)
742 .success_probability(amount_msat);
743 // NOTE: If success_probability is ever changed to return 0.0, log10 is undefined so return
744 // u64::max_value instead.
745 debug_assert!(success_probability > core::f64::EPSILON);
746 (-(success_probability.log10()) * liquidity_penalty_multiplier_msat as f64) as u64
749 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
750 let amount_msat = path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0);
751 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
752 let network_graph = self.network_graph.read_only();
754 let target = NodeId::from_pubkey(&hop.pubkey);
755 let channel_directed_from_source = network_graph.channels()
756 .get(&hop.short_channel_id)
757 .and_then(|channel| channel.as_directed_to(&target));
759 // Only score announced channels.
760 if let Some((channel, source)) = channel_directed_from_source {
761 let capacity_msat = channel.effective_capacity().as_msat();
762 if hop.short_channel_id == short_channel_id {
763 self.channel_liquidities
764 .entry(hop.short_channel_id)
765 .or_insert_with(ChannelLiquidity::new)
766 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
767 .failed_at_channel(amount_msat);
771 self.channel_liquidities
772 .entry(hop.short_channel_id)
773 .or_insert_with(ChannelLiquidity::new)
774 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
775 .failed_downstream(amount_msat);
780 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
781 let amount_msat = path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0);
782 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
783 let network_graph = self.network_graph.read_only();
785 let target = NodeId::from_pubkey(&hop.pubkey);
786 let channel_directed_from_source = network_graph.channels()
787 .get(&hop.short_channel_id)
788 .and_then(|channel| channel.as_directed_to(&target));
790 // Only score announced channels.
791 if let Some((channel, source)) = channel_directed_from_source {
792 let capacity_msat = channel.effective_capacity().as_msat();
793 self.channel_liquidities
794 .entry(hop.short_channel_id)
795 .or_insert_with(ChannelLiquidity::new)
796 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
797 .successful(amount_msat);
803 impl<G: Deref<Target = NetworkGraph>, T: Time> Writeable for ProbabilisticScorerUsingTime<G, T> {
805 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
806 write_tlv_fields!(w, {
807 (0, self.channel_liquidities, required)
813 impl<G, T> ReadableArgs<(ProbabilisticScoringParameters, G)> for ProbabilisticScorerUsingTime<G, T>
815 G: Deref<Target = NetworkGraph>,
820 r: &mut R, args: (ProbabilisticScoringParameters, G)
821 ) -> Result<Self, DecodeError> {
822 let (params, network_graph) = args;
823 let mut channel_liquidities = HashMap::new();
824 read_tlv_fields!(r, {
825 (0, channel_liquidities, required)
835 impl<T: Time> Writeable for ChannelLiquidity<T> {
837 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
838 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
839 write_tlv_fields!(w, {
840 (0, self.min_liquidity_offset_msat, required),
841 (2, self.max_liquidity_offset_msat, required),
842 (4, duration_since_epoch, required),
848 impl<T: Time> Readable for ChannelLiquidity<T> {
850 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
851 let mut min_liquidity_offset_msat = 0;
852 let mut max_liquidity_offset_msat = 0;
853 let mut duration_since_epoch = Duration::from_secs(0);
854 read_tlv_fields!(r, {
855 (0, min_liquidity_offset_msat, required),
856 (2, max_liquidity_offset_msat, required),
857 (4, duration_since_epoch, required),
860 min_liquidity_offset_msat,
861 max_liquidity_offset_msat,
862 last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
867 pub(crate) mod time {
869 use core::time::Duration;
870 /// A measurement of time.
871 pub trait Time: Copy + Sub<Duration, Output = Self> where Self: Sized {
872 /// Returns an instance corresponding to the current moment.
875 /// Returns the amount of time elapsed since `self` was created.
876 fn elapsed(&self) -> Duration;
878 /// Returns the amount of time passed between `earlier` and `self`.
879 fn duration_since(&self, earlier: Self) -> Duration;
881 /// Returns the amount of time passed since the beginning of [`Time`].
883 /// Used during (de-)serialization.
884 fn duration_since_epoch() -> Duration;
887 /// A state in which time has no meaning.
888 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
891 #[cfg(not(feature = "no-std"))]
892 impl Time for std::time::Instant {
894 std::time::Instant::now()
897 fn duration_since(&self, earlier: Self) -> Duration {
898 self.duration_since(earlier)
901 fn duration_since_epoch() -> Duration {
902 use std::time::SystemTime;
903 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
906 fn elapsed(&self) -> Duration {
907 std::time::Instant::elapsed(self)
911 impl Time for Eternity {
916 fn duration_since(&self, _earlier: Self) -> Duration {
917 Duration::from_secs(0)
920 fn duration_since_epoch() -> Duration {
921 Duration::from_secs(0)
924 fn elapsed(&self) -> Duration {
925 Duration::from_secs(0)
929 impl Sub<Duration> for Eternity {
932 fn sub(self, _other: Duration) -> Self {
938 pub(crate) use self::time::Time;
942 use super::{ChannelLiquidity, ProbabilisticScoringParameters, ProbabilisticScorerUsingTime, ScoringParameters, ScorerUsingTime, Time};
943 use super::time::Eternity;
945 use ln::features::{ChannelFeatures, NodeFeatures};
946 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, OptionalField, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
947 use routing::scoring::Score;
948 use routing::network_graph::{NetworkGraph, NodeId};
949 use routing::router::RouteHop;
950 use util::ser::{Readable, ReadableArgs, Writeable};
952 use bitcoin::blockdata::constants::genesis_block;
953 use bitcoin::hashes::Hash;
954 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
955 use bitcoin::network::constants::Network;
956 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
957 use core::cell::Cell;
959 use core::time::Duration;
964 /// Time that can be advanced manually in tests.
965 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
966 struct SinceEpoch(Duration);
970 static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
973 fn advance(duration: Duration) {
974 Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
978 impl Time for SinceEpoch {
980 Self(Self::duration_since_epoch())
983 fn duration_since(&self, earlier: Self) -> Duration {
987 fn duration_since_epoch() -> Duration {
988 Self::ELAPSED.with(|elapsed| elapsed.get())
991 fn elapsed(&self) -> Duration {
992 Self::duration_since_epoch() - self.0
996 impl Sub<Duration> for SinceEpoch {
999 fn sub(self, other: Duration) -> Self {
1000 Self(self.0 - other)
1005 fn time_passes_when_advanced() {
1006 let now = SinceEpoch::now();
1007 assert_eq!(now.elapsed(), Duration::from_secs(0));
1009 SinceEpoch::advance(Duration::from_secs(1));
1010 SinceEpoch::advance(Duration::from_secs(1));
1012 let elapsed = now.elapsed();
1013 let later = SinceEpoch::now();
1015 assert_eq!(elapsed, Duration::from_secs(2));
1016 assert_eq!(later - elapsed, now);
1020 fn time_never_passes_in_an_eternity() {
1021 let now = Eternity::now();
1022 let elapsed = now.elapsed();
1023 let later = Eternity::now();
1025 assert_eq!(now.elapsed(), Duration::from_secs(0));
1026 assert_eq!(later - elapsed, now);
1031 /// A scorer for testing with time that can be manually advanced.
1032 type Scorer = ScorerUsingTime::<SinceEpoch>;
1034 fn source_privkey() -> SecretKey {
1035 SecretKey::from_slice(&[42; 32]).unwrap()
1038 fn target_privkey() -> SecretKey {
1039 SecretKey::from_slice(&[43; 32]).unwrap()
1042 fn source_pubkey() -> PublicKey {
1043 let secp_ctx = Secp256k1::new();
1044 PublicKey::from_secret_key(&secp_ctx, &source_privkey())
1047 fn target_pubkey() -> PublicKey {
1048 let secp_ctx = Secp256k1::new();
1049 PublicKey::from_secret_key(&secp_ctx, &target_privkey())
1052 fn source_node_id() -> NodeId {
1053 NodeId::from_pubkey(&source_pubkey())
1056 fn target_node_id() -> NodeId {
1057 NodeId::from_pubkey(&target_pubkey())
1061 fn penalizes_without_channel_failures() {
1062 let scorer = Scorer::new(ScoringParameters {
1063 base_penalty_msat: 1_000,
1064 failure_penalty_msat: 512,
1065 failure_penalty_half_life: Duration::from_secs(1),
1066 overuse_penalty_start_1024th: 1024,
1067 overuse_penalty_msat_per_1024th: 0,
1069 let source = source_node_id();
1070 let target = target_node_id();
1071 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1073 SinceEpoch::advance(Duration::from_secs(1));
1074 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1078 fn accumulates_channel_failure_penalties() {
1079 let mut scorer = Scorer::new(ScoringParameters {
1080 base_penalty_msat: 1_000,
1081 failure_penalty_msat: 64,
1082 failure_penalty_half_life: Duration::from_secs(10),
1083 overuse_penalty_start_1024th: 1024,
1084 overuse_penalty_msat_per_1024th: 0,
1086 let source = source_node_id();
1087 let target = target_node_id();
1088 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1090 scorer.payment_path_failed(&[], 42);
1091 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1093 scorer.payment_path_failed(&[], 42);
1094 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1096 scorer.payment_path_failed(&[], 42);
1097 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_192);
1101 fn decays_channel_failure_penalties_over_time() {
1102 let mut scorer = Scorer::new(ScoringParameters {
1103 base_penalty_msat: 1_000,
1104 failure_penalty_msat: 512,
1105 failure_penalty_half_life: Duration::from_secs(10),
1106 overuse_penalty_start_1024th: 1024,
1107 overuse_penalty_msat_per_1024th: 0,
1109 let source = source_node_id();
1110 let target = target_node_id();
1111 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1113 scorer.payment_path_failed(&[], 42);
1114 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1116 SinceEpoch::advance(Duration::from_secs(9));
1117 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1119 SinceEpoch::advance(Duration::from_secs(1));
1120 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1122 SinceEpoch::advance(Duration::from_secs(10 * 8));
1123 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_001);
1125 SinceEpoch::advance(Duration::from_secs(10));
1126 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1128 SinceEpoch::advance(Duration::from_secs(10));
1129 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1133 fn decays_channel_failure_penalties_without_shift_overflow() {
1134 let mut scorer = Scorer::new(ScoringParameters {
1135 base_penalty_msat: 1_000,
1136 failure_penalty_msat: 512,
1137 failure_penalty_half_life: Duration::from_secs(10),
1138 overuse_penalty_start_1024th: 1024,
1139 overuse_penalty_msat_per_1024th: 0,
1141 let source = source_node_id();
1142 let target = target_node_id();
1143 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1145 scorer.payment_path_failed(&[], 42);
1146 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1148 // An unchecked right shift 64 bits or more in ChannelFailure::decayed_penalty_msat would
1149 // cause an overflow.
1150 SinceEpoch::advance(Duration::from_secs(10 * 64));
1151 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1153 SinceEpoch::advance(Duration::from_secs(10));
1154 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1158 fn accumulates_channel_failure_penalties_after_decay() {
1159 let mut scorer = Scorer::new(ScoringParameters {
1160 base_penalty_msat: 1_000,
1161 failure_penalty_msat: 512,
1162 failure_penalty_half_life: Duration::from_secs(10),
1163 overuse_penalty_start_1024th: 1024,
1164 overuse_penalty_msat_per_1024th: 0,
1166 let source = source_node_id();
1167 let target = target_node_id();
1168 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1170 scorer.payment_path_failed(&[], 42);
1171 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1173 SinceEpoch::advance(Duration::from_secs(10));
1174 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1176 scorer.payment_path_failed(&[], 42);
1177 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_768);
1179 SinceEpoch::advance(Duration::from_secs(10));
1180 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_384);
1184 fn reduces_channel_failure_penalties_after_success() {
1185 let mut scorer = Scorer::new(ScoringParameters {
1186 base_penalty_msat: 1_000,
1187 failure_penalty_msat: 512,
1188 failure_penalty_half_life: Duration::from_secs(10),
1189 overuse_penalty_start_1024th: 1024,
1190 overuse_penalty_msat_per_1024th: 0,
1192 let source = source_node_id();
1193 let target = target_node_id();
1194 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1196 scorer.payment_path_failed(&[], 42);
1197 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1199 SinceEpoch::advance(Duration::from_secs(10));
1200 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1202 let hop = RouteHop {
1203 pubkey: PublicKey::from_slice(target.as_slice()).unwrap(),
1204 node_features: NodeFeatures::known(),
1205 short_channel_id: 42,
1206 channel_features: ChannelFeatures::known(),
1208 cltv_expiry_delta: 18,
1210 scorer.payment_path_successful(&[&hop]);
1211 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1213 SinceEpoch::advance(Duration::from_secs(10));
1214 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1218 fn restores_persisted_channel_failure_penalties() {
1219 let mut scorer = Scorer::new(ScoringParameters {
1220 base_penalty_msat: 1_000,
1221 failure_penalty_msat: 512,
1222 failure_penalty_half_life: Duration::from_secs(10),
1223 overuse_penalty_start_1024th: 1024,
1224 overuse_penalty_msat_per_1024th: 0,
1226 let source = source_node_id();
1227 let target = target_node_id();
1229 scorer.payment_path_failed(&[], 42);
1230 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1232 SinceEpoch::advance(Duration::from_secs(10));
1233 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1235 scorer.payment_path_failed(&[], 43);
1236 assert_eq!(scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
1238 let mut serialized_scorer = Vec::new();
1239 scorer.write(&mut serialized_scorer).unwrap();
1241 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
1242 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1243 assert_eq!(deserialized_scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
1247 fn decays_persisted_channel_failure_penalties() {
1248 let mut scorer = Scorer::new(ScoringParameters {
1249 base_penalty_msat: 1_000,
1250 failure_penalty_msat: 512,
1251 failure_penalty_half_life: Duration::from_secs(10),
1252 overuse_penalty_start_1024th: 1024,
1253 overuse_penalty_msat_per_1024th: 0,
1255 let source = source_node_id();
1256 let target = target_node_id();
1258 scorer.payment_path_failed(&[], 42);
1259 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1261 let mut serialized_scorer = Vec::new();
1262 scorer.write(&mut serialized_scorer).unwrap();
1264 SinceEpoch::advance(Duration::from_secs(10));
1266 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
1267 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1269 SinceEpoch::advance(Duration::from_secs(10));
1270 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1274 fn charges_per_1024th_penalty() {
1275 let scorer = Scorer::new(ScoringParameters {
1276 base_penalty_msat: 0,
1277 failure_penalty_msat: 0,
1278 failure_penalty_half_life: Duration::from_secs(0),
1279 overuse_penalty_start_1024th: 256,
1280 overuse_penalty_msat_per_1024th: 100,
1282 let source = source_node_id();
1283 let target = target_node_id();
1285 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 1_024_000, &source, &target), 0);
1286 assert_eq!(scorer.channel_penalty_msat(42, 256_999, 1_024_000, &source, &target), 0);
1287 assert_eq!(scorer.channel_penalty_msat(42, 257_000, 1_024_000, &source, &target), 100);
1288 assert_eq!(scorer.channel_penalty_msat(42, 258_000, 1_024_000, &source, &target), 200);
1289 assert_eq!(scorer.channel_penalty_msat(42, 512_000, 1_024_000, &source, &target), 256 * 100);
1292 // `ProbabilisticScorer` tests
1294 /// A probabilistic scorer for testing with time that can be manually advanced.
1295 type ProbabilisticScorer<'a> = ProbabilisticScorerUsingTime::<&'a NetworkGraph, SinceEpoch>;
1297 fn sender_privkey() -> SecretKey {
1298 SecretKey::from_slice(&[41; 32]).unwrap()
1301 fn recipient_privkey() -> SecretKey {
1302 SecretKey::from_slice(&[45; 32]).unwrap()
1305 fn sender_pubkey() -> PublicKey {
1306 let secp_ctx = Secp256k1::new();
1307 PublicKey::from_secret_key(&secp_ctx, &sender_privkey())
1310 fn recipient_pubkey() -> PublicKey {
1311 let secp_ctx = Secp256k1::new();
1312 PublicKey::from_secret_key(&secp_ctx, &recipient_privkey())
1315 fn sender_node_id() -> NodeId {
1316 NodeId::from_pubkey(&sender_pubkey())
1319 fn recipient_node_id() -> NodeId {
1320 NodeId::from_pubkey(&recipient_pubkey())
1323 fn network_graph() -> NetworkGraph {
1324 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1325 let mut network_graph = NetworkGraph::new(genesis_hash);
1326 add_channel(&mut network_graph, 42, source_privkey(), target_privkey());
1327 add_channel(&mut network_graph, 43, target_privkey(), recipient_privkey());
1333 network_graph: &mut NetworkGraph, short_channel_id: u64, node_1_key: SecretKey,
1334 node_2_key: SecretKey
1336 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1337 let node_1_secret = &SecretKey::from_slice(&[39; 32]).unwrap();
1338 let node_2_secret = &SecretKey::from_slice(&[40; 32]).unwrap();
1339 let secp_ctx = Secp256k1::new();
1340 let unsigned_announcement = UnsignedChannelAnnouncement {
1341 features: ChannelFeatures::known(),
1342 chain_hash: genesis_hash,
1344 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_key),
1345 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_key),
1346 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_secret),
1347 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_secret),
1348 excess_data: Vec::new(),
1350 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1351 let signed_announcement = ChannelAnnouncement {
1352 node_signature_1: secp_ctx.sign(&msghash, &node_1_key),
1353 node_signature_2: secp_ctx.sign(&msghash, &node_2_key),
1354 bitcoin_signature_1: secp_ctx.sign(&msghash, &node_1_secret),
1355 bitcoin_signature_2: secp_ctx.sign(&msghash, &node_2_secret),
1356 contents: unsigned_announcement,
1358 let chain_source: Option<&::util::test_utils::TestChainSource> = None;
1359 network_graph.update_channel_from_announcement(
1360 &signed_announcement, &chain_source, &secp_ctx).unwrap();
1361 update_channel(network_graph, short_channel_id, node_1_key, 0);
1362 update_channel(network_graph, short_channel_id, node_2_key, 1);
1366 network_graph: &mut NetworkGraph, short_channel_id: u64, node_key: SecretKey, flags: u8
1368 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1369 let secp_ctx = Secp256k1::new();
1370 let unsigned_update = UnsignedChannelUpdate {
1371 chain_hash: genesis_hash,
1375 cltv_expiry_delta: 18,
1376 htlc_minimum_msat: 0,
1377 htlc_maximum_msat: OptionalField::Present(1_000),
1379 fee_proportional_millionths: 0,
1380 excess_data: Vec::new(),
1382 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_update.encode()[..])[..]);
1383 let signed_update = ChannelUpdate {
1384 signature: secp_ctx.sign(&msghash, &node_key),
1385 contents: unsigned_update,
1387 network_graph.update_channel(&signed_update, &secp_ctx).unwrap();
1390 fn payment_path_for_amount(amount_msat: u64) -> Vec<RouteHop> {
1393 pubkey: source_pubkey(),
1394 node_features: NodeFeatures::known(),
1395 short_channel_id: 41,
1396 channel_features: ChannelFeatures::known(),
1398 cltv_expiry_delta: 18,
1401 pubkey: target_pubkey(),
1402 node_features: NodeFeatures::known(),
1403 short_channel_id: 42,
1404 channel_features: ChannelFeatures::known(),
1406 cltv_expiry_delta: 18,
1409 pubkey: recipient_pubkey(),
1410 node_features: NodeFeatures::known(),
1411 short_channel_id: 43,
1412 channel_features: ChannelFeatures::known(),
1413 fee_msat: amount_msat,
1414 cltv_expiry_delta: 18,
1420 fn liquidity_bounds_directed_from_lowest_node_id() {
1421 let last_updated = SinceEpoch::now();
1422 let network_graph = network_graph();
1423 let params = ProbabilisticScoringParameters::default();
1424 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1427 min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1431 min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1433 let source = source_node_id();
1434 let target = target_node_id();
1435 let recipient = recipient_node_id();
1436 assert!(source > target);
1437 assert!(target < recipient);
1439 // Update minimum liquidity.
1441 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1442 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1443 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1444 assert_eq!(liquidity.min_liquidity_msat(), 100);
1445 assert_eq!(liquidity.max_liquidity_msat(), 300);
1447 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1448 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1449 assert_eq!(liquidity.min_liquidity_msat(), 700);
1450 assert_eq!(liquidity.max_liquidity_msat(), 900);
1452 scorer.channel_liquidities.get_mut(&42).unwrap()
1453 .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1454 .set_min_liquidity_msat(200);
1456 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1457 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1458 assert_eq!(liquidity.min_liquidity_msat(), 200);
1459 assert_eq!(liquidity.max_liquidity_msat(), 300);
1461 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1462 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1463 assert_eq!(liquidity.min_liquidity_msat(), 700);
1464 assert_eq!(liquidity.max_liquidity_msat(), 800);
1466 // Update maximum liquidity.
1468 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1469 .as_directed(&target, &recipient, 1_000, liquidity_offset_half_life);
1470 assert_eq!(liquidity.min_liquidity_msat(), 700);
1471 assert_eq!(liquidity.max_liquidity_msat(), 900);
1473 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1474 .as_directed(&recipient, &target, 1_000, liquidity_offset_half_life);
1475 assert_eq!(liquidity.min_liquidity_msat(), 100);
1476 assert_eq!(liquidity.max_liquidity_msat(), 300);
1478 scorer.channel_liquidities.get_mut(&43).unwrap()
1479 .as_directed_mut(&target, &recipient, 1_000, liquidity_offset_half_life)
1480 .set_max_liquidity_msat(200);
1482 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1483 .as_directed(&target, &recipient, 1_000, liquidity_offset_half_life);
1484 assert_eq!(liquidity.min_liquidity_msat(), 0);
1485 assert_eq!(liquidity.max_liquidity_msat(), 200);
1487 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1488 .as_directed(&recipient, &target, 1_000, liquidity_offset_half_life);
1489 assert_eq!(liquidity.min_liquidity_msat(), 800);
1490 assert_eq!(liquidity.max_liquidity_msat(), 1000);
1494 fn resets_liquidity_upper_bound_when_crossed_by_lower_bound() {
1495 let last_updated = SinceEpoch::now();
1496 let network_graph = network_graph();
1497 let params = ProbabilisticScoringParameters::default();
1498 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1501 min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1503 let source = source_node_id();
1504 let target = target_node_id();
1505 assert!(source > target);
1507 // Check initial bounds.
1508 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1509 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1510 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1511 assert_eq!(liquidity.min_liquidity_msat(), 400);
1512 assert_eq!(liquidity.max_liquidity_msat(), 800);
1514 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1515 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1516 assert_eq!(liquidity.min_liquidity_msat(), 200);
1517 assert_eq!(liquidity.max_liquidity_msat(), 600);
1519 // Reset from source to target.
1520 scorer.channel_liquidities.get_mut(&42).unwrap()
1521 .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1522 .set_min_liquidity_msat(900);
1524 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1525 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1526 assert_eq!(liquidity.min_liquidity_msat(), 900);
1527 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1529 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1530 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1531 assert_eq!(liquidity.min_liquidity_msat(), 0);
1532 assert_eq!(liquidity.max_liquidity_msat(), 100);
1534 // Reset from target to source.
1535 scorer.channel_liquidities.get_mut(&42).unwrap()
1536 .as_directed_mut(&target, &source, 1_000, liquidity_offset_half_life)
1537 .set_min_liquidity_msat(400);
1539 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1540 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1541 assert_eq!(liquidity.min_liquidity_msat(), 0);
1542 assert_eq!(liquidity.max_liquidity_msat(), 600);
1544 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1545 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1546 assert_eq!(liquidity.min_liquidity_msat(), 400);
1547 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1551 fn resets_liquidity_lower_bound_when_crossed_by_upper_bound() {
1552 let last_updated = SinceEpoch::now();
1553 let network_graph = network_graph();
1554 let params = ProbabilisticScoringParameters::default();
1555 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1558 min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1560 let source = source_node_id();
1561 let target = target_node_id();
1562 assert!(source > target);
1564 // Check initial bounds.
1565 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1566 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1567 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1568 assert_eq!(liquidity.min_liquidity_msat(), 400);
1569 assert_eq!(liquidity.max_liquidity_msat(), 800);
1571 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1572 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1573 assert_eq!(liquidity.min_liquidity_msat(), 200);
1574 assert_eq!(liquidity.max_liquidity_msat(), 600);
1576 // Reset from source to target.
1577 scorer.channel_liquidities.get_mut(&42).unwrap()
1578 .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1579 .set_max_liquidity_msat(300);
1581 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1582 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1583 assert_eq!(liquidity.min_liquidity_msat(), 0);
1584 assert_eq!(liquidity.max_liquidity_msat(), 300);
1586 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1587 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1588 assert_eq!(liquidity.min_liquidity_msat(), 700);
1589 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1591 // Reset from target to source.
1592 scorer.channel_liquidities.get_mut(&42).unwrap()
1593 .as_directed_mut(&target, &source, 1_000, liquidity_offset_half_life)
1594 .set_max_liquidity_msat(600);
1596 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1597 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1598 assert_eq!(liquidity.min_liquidity_msat(), 400);
1599 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1601 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1602 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1603 assert_eq!(liquidity.min_liquidity_msat(), 0);
1604 assert_eq!(liquidity.max_liquidity_msat(), 600);
1608 fn increased_penalty_nearing_liquidity_upper_bound() {
1609 let network_graph = network_graph();
1610 let params = ProbabilisticScoringParameters {
1611 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1613 let scorer = ProbabilisticScorer::new(params, &network_graph);
1614 let source = source_node_id();
1615 let target = target_node_id();
1617 assert_eq!(scorer.channel_penalty_msat(42, 100, 100_000, &source, &target), 0);
1618 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 100_000, &source, &target), 4);
1619 assert_eq!(scorer.channel_penalty_msat(42, 10_000, 100_000, &source, &target), 45);
1620 assert_eq!(scorer.channel_penalty_msat(42, 100_000, 100_000, &source, &target), 2_000);
1622 assert_eq!(scorer.channel_penalty_msat(42, 125, 1_000, &source, &target), 57);
1623 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1624 assert_eq!(scorer.channel_penalty_msat(42, 375, 1_000, &source, &target), 203);
1625 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1626 assert_eq!(scorer.channel_penalty_msat(42, 625, 1_000, &source, &target), 425);
1627 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1628 assert_eq!(scorer.channel_penalty_msat(42, 875, 1_000, &source, &target), 900);
1632 fn constant_penalty_outside_liquidity_bounds() {
1633 let last_updated = SinceEpoch::now();
1634 let network_graph = network_graph();
1635 let params = ProbabilisticScoringParameters {
1636 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1638 let scorer = ProbabilisticScorer::new(params, &network_graph)
1641 min_liquidity_offset_msat: 40, max_liquidity_offset_msat: 40, last_updated
1643 let source = source_node_id();
1644 let target = target_node_id();
1646 assert_eq!(scorer.channel_penalty_msat(42, 39, 100, &source, &target), 0);
1647 assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 0);
1648 assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 2_000);
1649 assert_eq!(scorer.channel_penalty_msat(42, 61, 100, &source, &target), 2_000);
1653 fn does_not_further_penalize_own_channel() {
1654 let network_graph = network_graph();
1655 let params = ProbabilisticScoringParameters {
1656 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1658 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1659 let sender = sender_node_id();
1660 let source = source_node_id();
1661 let failed_path = payment_path_for_amount(500);
1662 let successful_path = payment_path_for_amount(200);
1664 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1666 scorer.payment_path_failed(&failed_path.iter().collect::<Vec<_>>(), 41);
1667 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1669 scorer.payment_path_successful(&successful_path.iter().collect::<Vec<_>>());
1670 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1674 fn sets_liquidity_lower_bound_on_downstream_failure() {
1675 let network_graph = network_graph();
1676 let params = ProbabilisticScoringParameters {
1677 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1679 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1680 let source = source_node_id();
1681 let target = target_node_id();
1682 let path = payment_path_for_amount(500);
1684 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1685 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1686 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1688 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 43);
1690 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 0);
1691 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 0);
1692 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 300);
1696 fn sets_liquidity_upper_bound_on_failure() {
1697 let network_graph = network_graph();
1698 let params = ProbabilisticScoringParameters {
1699 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1701 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1702 let source = source_node_id();
1703 let target = target_node_id();
1704 let path = payment_path_for_amount(500);
1706 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1707 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1708 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1710 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 42);
1712 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 300);
1713 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1714 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 2_000);
1718 fn reduces_liquidity_upper_bound_along_path_on_success() {
1719 let network_graph = network_graph();
1720 let params = ProbabilisticScoringParameters {
1721 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1723 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1724 let sender = sender_node_id();
1725 let source = source_node_id();
1726 let target = target_node_id();
1727 let recipient = recipient_node_id();
1728 let path = payment_path_for_amount(500);
1730 assert_eq!(scorer.channel_penalty_msat(41, 250, 1_000, &sender, &source), 124);
1731 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1732 assert_eq!(scorer.channel_penalty_msat(43, 250, 1_000, &target, &recipient), 124);
1734 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
1736 assert_eq!(scorer.channel_penalty_msat(41, 250, 1_000, &sender, &source), 124);
1737 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 300);
1738 assert_eq!(scorer.channel_penalty_msat(43, 250, 1_000, &target, &recipient), 300);
1742 fn decays_liquidity_bounds_over_time() {
1743 let network_graph = network_graph();
1744 let params = ProbabilisticScoringParameters {
1745 liquidity_penalty_multiplier_msat: 1_000,
1746 liquidity_offset_half_life: Duration::from_secs(10),
1748 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1749 let source = source_node_id();
1750 let target = target_node_id();
1752 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1753 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1755 scorer.payment_path_failed(&payment_path_for_amount(768).iter().collect::<Vec<_>>(), 42);
1756 scorer.payment_path_failed(&payment_path_for_amount(128).iter().collect::<Vec<_>>(), 43);
1758 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
1759 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 92);
1760 assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_424);
1761 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
1763 SinceEpoch::advance(Duration::from_secs(9));
1764 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
1765 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 92);
1766 assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_424);
1767 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
1769 SinceEpoch::advance(Duration::from_secs(1));
1770 assert_eq!(scorer.channel_penalty_msat(42, 64, 1_024, &source, &target), 0);
1771 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 34);
1772 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 1_812);
1773 assert_eq!(scorer.channel_penalty_msat(42, 960, 1_024, &source, &target), 2_000);
1775 // Fully decay liquidity lower bound.
1776 SinceEpoch::advance(Duration::from_secs(10 * 7));
1777 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1778 assert_eq!(scorer.channel_penalty_msat(42, 1, 1_024, &source, &target), 0);
1779 assert_eq!(scorer.channel_penalty_msat(42, 1_023, 1_024, &source, &target), 2_000);
1780 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1782 // Fully decay liquidity upper bound.
1783 SinceEpoch::advance(Duration::from_secs(10));
1784 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1785 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1787 SinceEpoch::advance(Duration::from_secs(10));
1788 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1789 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1793 fn decays_liquidity_bounds_without_shift_overflow() {
1794 let network_graph = network_graph();
1795 let params = ProbabilisticScoringParameters {
1796 liquidity_penalty_multiplier_msat: 1_000,
1797 liquidity_offset_half_life: Duration::from_secs(10),
1799 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1800 let source = source_node_id();
1801 let target = target_node_id();
1802 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1804 scorer.payment_path_failed(&payment_path_for_amount(512).iter().collect::<Vec<_>>(), 42);
1805 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 281);
1807 // An unchecked right shift 64 bits or more in DirectedChannelLiquidity::decayed_offset_msat
1808 // would cause an overflow.
1809 SinceEpoch::advance(Duration::from_secs(10 * 64));
1810 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1812 SinceEpoch::advance(Duration::from_secs(10));
1813 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1817 fn restricts_liquidity_bounds_after_decay() {
1818 let network_graph = network_graph();
1819 let params = ProbabilisticScoringParameters {
1820 liquidity_penalty_multiplier_msat: 1_000,
1821 liquidity_offset_half_life: Duration::from_secs(10),
1823 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1824 let source = source_node_id();
1825 let target = target_node_id();
1827 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 300);
1829 // More knowledge gives higher confidence (256, 768), meaning a lower penalty.
1830 scorer.payment_path_failed(&payment_path_for_amount(768).iter().collect::<Vec<_>>(), 42);
1831 scorer.payment_path_failed(&payment_path_for_amount(256).iter().collect::<Vec<_>>(), 43);
1832 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 281);
1834 // Decaying knowledge gives less confidence (128, 896), meaning a higher penalty.
1835 SinceEpoch::advance(Duration::from_secs(10));
1836 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 293);
1838 // Reducing the upper bound gives more confidence (128, 832) that the payment amount (512)
1839 // is closer to the upper bound, meaning a higher penalty.
1840 scorer.payment_path_successful(&payment_path_for_amount(64).iter().collect::<Vec<_>>());
1841 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 333);
1843 // Increasing the lower bound gives more confidence (256, 832) that the payment amount (512)
1844 // is closer to the lower bound, meaning a lower penalty.
1845 scorer.payment_path_failed(&payment_path_for_amount(256).iter().collect::<Vec<_>>(), 43);
1846 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 247);
1848 // Further decaying affects the lower bound more than the upper bound (128, 928).
1849 SinceEpoch::advance(Duration::from_secs(10));
1850 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 280);
1854 fn restores_persisted_liquidity_bounds() {
1855 let network_graph = network_graph();
1856 let params = ProbabilisticScoringParameters {
1857 liquidity_penalty_multiplier_msat: 1_000,
1858 liquidity_offset_half_life: Duration::from_secs(10),
1860 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1861 let source = source_node_id();
1862 let target = target_node_id();
1864 scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
1865 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1867 SinceEpoch::advance(Duration::from_secs(10));
1868 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 475);
1870 scorer.payment_path_failed(&payment_path_for_amount(250).iter().collect::<Vec<_>>(), 43);
1871 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1873 let mut serialized_scorer = Vec::new();
1874 scorer.write(&mut serialized_scorer).unwrap();
1876 let mut serialized_scorer = io::Cursor::new(&serialized_scorer);
1877 let deserialized_scorer =
1878 <ProbabilisticScorer>::read(&mut serialized_scorer, (params, &network_graph)).unwrap();
1879 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1883 fn decays_persisted_liquidity_bounds() {
1884 let network_graph = network_graph();
1885 let params = ProbabilisticScoringParameters {
1886 liquidity_penalty_multiplier_msat: 1_000,
1887 liquidity_offset_half_life: Duration::from_secs(10),
1889 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1890 let source = source_node_id();
1891 let target = target_node_id();
1893 scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
1894 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1896 let mut serialized_scorer = Vec::new();
1897 scorer.write(&mut serialized_scorer).unwrap();
1899 SinceEpoch::advance(Duration::from_secs(10));
1901 let mut serialized_scorer = io::Cursor::new(&serialized_scorer);
1902 let deserialized_scorer =
1903 <ProbabilisticScorer>::read(&mut serialized_scorer, (params, &network_graph)).unwrap();
1904 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 475);
1906 scorer.payment_path_failed(&payment_path_for_amount(250).iter().collect::<Vec<_>>(), 43);
1907 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1909 SinceEpoch::advance(Duration::from_secs(10));
1910 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 367);