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 provides reasonable default behavior.
194 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
195 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
197 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
199 /// [module-level documentation]: crate::routing::scoring
200 pub type Scorer = ScorerUsingTime::<ConfiguredTime>;
202 #[cfg(not(feature = "no-std"))]
203 type ConfiguredTime = std::time::Instant;
204 #[cfg(feature = "no-std")]
205 type ConfiguredTime = time::Eternity;
207 // Note that ideally we'd hide ScorerUsingTime from public view by sealing it as well, but rustdoc
208 // doesn't handle this well - instead exposing a `Scorer` which has no trait implementation(s) or
211 /// [`Score`] implementation.
215 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
218 /// (C-not exported) generally all users should use the [`Scorer`] type alias.
220 pub struct ScorerUsingTime<T: Time> {
221 params: ScoringParameters,
222 // TODO: Remove entries of closed channels.
223 channel_failures: HashMap<u64, ChannelFailure<T>>,
226 /// Parameters for configuring [`Scorer`].
227 pub struct ScoringParameters {
228 /// A fixed penalty in msats to apply to each channel.
230 /// Default value: 500 msat
231 pub base_penalty_msat: u64,
233 /// A penalty in msats to apply to a channel upon failing to relay a payment.
235 /// This accumulates for each failure but may be reduced over time based on
236 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
238 /// Default value: 1,024,000 msat
240 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
241 pub failure_penalty_msat: u64,
243 /// When the amount being sent over a channel is this many 1024ths of the total channel
244 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
246 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
248 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
249 pub overuse_penalty_start_1024th: u16,
251 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
252 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
254 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
255 /// to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
257 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
258 pub overuse_penalty_msat_per_1024th: u64,
260 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
263 /// Successfully routing through a channel will immediately cut the penalty in half as well.
265 /// Default value: 1 hour
269 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
272 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
273 pub failure_penalty_half_life: Duration,
276 impl_writeable_tlv_based!(ScoringParameters, {
277 (0, base_penalty_msat, required),
278 (1, overuse_penalty_start_1024th, (default_value, 128)),
279 (2, failure_penalty_msat, required),
280 (3, overuse_penalty_msat_per_1024th, (default_value, 20)),
281 (4, failure_penalty_half_life, required),
284 /// Accounting for penalties against a channel for failing to relay any payments.
286 /// Penalties decay over time, though accumulate as more failures occur.
287 struct ChannelFailure<T: Time> {
288 /// Accumulated penalty in msats for the channel as of `last_updated`.
289 undecayed_penalty_msat: u64,
291 /// Last time the channel either failed to route or successfully routed a payment. Used to decay
292 /// `undecayed_penalty_msat`.
296 impl<T: Time> ScorerUsingTime<T> {
297 /// Creates a new scorer using the given scoring parameters.
298 pub fn new(params: ScoringParameters) -> Self {
301 channel_failures: HashMap::new(),
305 /// Creates a new scorer using `penalty_msat` as a fixed channel penalty.
306 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
307 pub fn with_fixed_penalty(penalty_msat: u64) -> Self {
308 Self::new(ScoringParameters {
309 base_penalty_msat: penalty_msat,
310 failure_penalty_msat: 0,
311 failure_penalty_half_life: Duration::from_secs(0),
312 overuse_penalty_start_1024th: 1024,
313 overuse_penalty_msat_per_1024th: 0,
318 impl<T: Time> ChannelFailure<T> {
319 fn new(failure_penalty_msat: u64) -> Self {
321 undecayed_penalty_msat: failure_penalty_msat,
322 last_updated: T::now(),
326 fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
327 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
328 self.last_updated = T::now();
331 fn reduce_penalty(&mut self, half_life: Duration) {
332 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) >> 1;
333 self.last_updated = T::now();
336 fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
337 self.last_updated.elapsed().as_secs()
338 .checked_div(half_life.as_secs())
339 .and_then(|decays| self.undecayed_penalty_msat.checked_shr(decays as u32))
344 impl<T: Time> Default for ScorerUsingTime<T> {
345 fn default() -> Self {
346 Self::new(ScoringParameters::default())
350 impl Default for ScoringParameters {
351 fn default() -> Self {
353 base_penalty_msat: 500,
354 failure_penalty_msat: 1024 * 1000,
355 failure_penalty_half_life: Duration::from_secs(3600),
356 overuse_penalty_start_1024th: 1024 / 8,
357 overuse_penalty_msat_per_1024th: 20,
362 impl<T: Time> Score for ScorerUsingTime<T> {
363 fn channel_penalty_msat(
364 &self, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, _source: &NodeId, _target: &NodeId
366 let failure_penalty_msat = self.channel_failures
367 .get(&short_channel_id)
368 .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
370 let mut penalty_msat = self.params.base_penalty_msat + failure_penalty_msat;
371 let send_1024ths = send_amt_msat.checked_mul(1024).unwrap_or(u64::max_value()) / capacity_msat;
372 if send_1024ths > self.params.overuse_penalty_start_1024th as u64 {
373 penalty_msat = penalty_msat.checked_add(
374 (send_1024ths - self.params.overuse_penalty_start_1024th as u64)
375 .checked_mul(self.params.overuse_penalty_msat_per_1024th).unwrap_or(u64::max_value()))
376 .unwrap_or(u64::max_value());
382 fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
383 let failure_penalty_msat = self.params.failure_penalty_msat;
384 let half_life = self.params.failure_penalty_half_life;
385 self.channel_failures
386 .entry(short_channel_id)
387 .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
388 .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
391 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
392 let half_life = self.params.failure_penalty_half_life;
393 for hop in path.iter() {
394 self.channel_failures
395 .entry(hop.short_channel_id)
396 .and_modify(|failure| failure.reduce_penalty(half_life));
401 impl<T: Time> Writeable for ScorerUsingTime<T> {
403 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
404 self.params.write(w)?;
405 self.channel_failures.write(w)?;
406 write_tlv_fields!(w, {});
411 impl<T: Time> Readable for ScorerUsingTime<T> {
413 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
415 params: Readable::read(r)?,
416 channel_failures: Readable::read(r)?,
418 read_tlv_fields!(r, {});
423 impl<T: Time> Writeable for ChannelFailure<T> {
425 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
426 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
427 write_tlv_fields!(w, {
428 (0, self.undecayed_penalty_msat, required),
429 (2, duration_since_epoch, required),
435 impl<T: Time> Readable for ChannelFailure<T> {
437 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
438 let mut undecayed_penalty_msat = 0;
439 let mut duration_since_epoch = Duration::from_secs(0);
440 read_tlv_fields!(r, {
441 (0, undecayed_penalty_msat, required),
442 (2, duration_since_epoch, required),
445 undecayed_penalty_msat,
446 last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
451 /// [`Score`] implementation using channel success probability distributions.
453 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
454 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
455 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
456 /// Then the negative log of the success probability is used to determine the cost of routing a
457 /// specific HTLC amount through a channel.
459 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
460 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
461 /// [`ProbabilisticScoringParameters`] for details.
463 /// [1]: https://arxiv.org/abs/2107.05322
464 pub type ProbabilisticScorer<G> = ProbabilisticScorerUsingTime::<G, ConfiguredTime>;
466 /// Probabilistic [`Score`] implementation.
470 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
473 /// (C-not exported) generally all users should use the [`ProbabilisticScorer`] type alias.
475 pub struct ProbabilisticScorerUsingTime<G: Deref<Target = NetworkGraph>, T: Time> {
476 params: ProbabilisticScoringParameters,
478 // TODO: Remove entries of closed channels.
479 channel_liquidities: HashMap<u64, ChannelLiquidity<T>>,
482 /// Parameters for configuring [`ProbabilisticScorer`].
483 #[derive(Clone, Copy)]
484 pub struct ProbabilisticScoringParameters {
485 /// A penalty applied after multiplying by the negative log of the channel's success probability
488 /// The success probability is determined by the effective channel capacity, the payment amount,
489 /// and knowledge learned from prior successful and unsuccessful payments. The lower bound of
490 /// the success probability is 0.01, effectively limiting the penalty to the range
491 /// `0..=2*liquidity_penalty_multiplier_msat`. The knowledge learned is reduced over time based
492 /// on [`liquidity_offset_half_life`].
494 /// Default value: 10,000 msat
496 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
497 pub liquidity_penalty_multiplier_msat: u64,
499 /// The time required to elapse before any knowledge learned about channel liquidity balances is
502 /// The bounds are defined in terms offsets and are initially zero. Increasing the offsets gives
503 /// tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases the
504 /// certainty of the channel liquidity balance.
506 /// Default value: 1 hour
510 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
511 /// liquidity knowledge will never decay except when the bounds cross.
512 pub liquidity_offset_half_life: Duration,
515 impl_writeable_tlv_based!(ProbabilisticScoringParameters, {
516 (0, liquidity_penalty_multiplier_msat, required),
517 (2, liquidity_offset_half_life, required),
520 /// Accounting for channel liquidity balance uncertainty.
522 /// Direction is defined in terms of [`NodeId`] partial ordering, where the source node is the
523 /// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
524 /// offset fields gives the opposite direction.
525 struct ChannelLiquidity<T: Time> {
526 /// Lower channel liquidity bound in terms of an offset from zero.
527 min_liquidity_offset_msat: u64,
529 /// Upper channel liquidity bound in terms of an offset from the effective capacity.
530 max_liquidity_offset_msat: u64,
532 /// Time when the liquidity bounds were last modified.
536 /// A view of [`ChannelLiquidity`] in one direction assuming a certain channel capacity and decayed
537 /// with a given half life.
538 struct DirectedChannelLiquidity<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> {
539 min_liquidity_offset_msat: L,
540 max_liquidity_offset_msat: L,
547 impl<G: Deref<Target = NetworkGraph>, T: Time> ProbabilisticScorerUsingTime<G, T> {
548 /// Creates a new scorer using the given scoring parameters for sending payments from a node
549 /// through a network graph.
550 pub fn new(params: ProbabilisticScoringParameters, network_graph: G) -> Self {
554 channel_liquidities: HashMap::new(),
559 fn with_channel(mut self, short_channel_id: u64, liquidity: ChannelLiquidity<T>) -> Self {
560 assert!(self.channel_liquidities.insert(short_channel_id, liquidity).is_none());
565 impl Default for ProbabilisticScoringParameters {
566 fn default() -> Self {
568 liquidity_penalty_multiplier_msat: 10_000,
569 liquidity_offset_half_life: Duration::from_secs(3600),
574 impl<T: Time> ChannelLiquidity<T> {
578 min_liquidity_offset_msat: 0,
579 max_liquidity_offset_msat: 0,
580 last_updated: T::now(),
584 /// Returns a view of the channel liquidity directed from `source` to `target` assuming
587 &self, source: &NodeId, target: &NodeId, capacity_msat: u64, half_life: Duration
588 ) -> DirectedChannelLiquidity<&u64, T, &T> {
589 let (min_liquidity_offset_msat, max_liquidity_offset_msat) = if source < target {
590 (&self.min_liquidity_offset_msat, &self.max_liquidity_offset_msat)
592 (&self.max_liquidity_offset_msat, &self.min_liquidity_offset_msat)
595 DirectedChannelLiquidity {
596 min_liquidity_offset_msat,
597 max_liquidity_offset_msat,
599 last_updated: &self.last_updated,
605 /// Returns a mutable view of the channel liquidity directed from `source` to `target` assuming
608 &mut self, source: &NodeId, target: &NodeId, capacity_msat: u64, half_life: Duration
609 ) -> DirectedChannelLiquidity<&mut u64, T, &mut T> {
610 let (min_liquidity_offset_msat, max_liquidity_offset_msat) = if source < target {
611 (&mut self.min_liquidity_offset_msat, &mut self.max_liquidity_offset_msat)
613 (&mut self.max_liquidity_offset_msat, &mut self.min_liquidity_offset_msat)
616 DirectedChannelLiquidity {
617 min_liquidity_offset_msat,
618 max_liquidity_offset_msat,
620 last_updated: &mut self.last_updated,
627 impl<L: Deref<Target = u64>, T: Time, U: Deref<Target = T>> DirectedChannelLiquidity<L, T, U> {
628 /// Returns the success probability of routing the given HTLC `amount_msat` through the channel
629 /// in this direction.
630 fn success_probability(&self, amount_msat: u64) -> f64 {
631 let max_liquidity_msat = self.max_liquidity_msat();
632 let min_liquidity_msat = core::cmp::min(self.min_liquidity_msat(), max_liquidity_msat);
633 if amount_msat > max_liquidity_msat {
635 } else if amount_msat <= min_liquidity_msat {
638 let numerator = max_liquidity_msat + 1 - amount_msat;
639 let denominator = max_liquidity_msat + 1 - min_liquidity_msat;
640 numerator as f64 / denominator as f64
641 }.max(0.01) // Lower bound the success probability to ensure some channel is selected.
644 /// Returns the lower bound of the channel liquidity balance in this direction.
645 fn min_liquidity_msat(&self) -> u64 {
646 self.decayed_offset_msat(*self.min_liquidity_offset_msat)
649 /// Returns the upper bound of the channel liquidity balance in this direction.
650 fn max_liquidity_msat(&self) -> u64 {
652 .checked_sub(self.decayed_offset_msat(*self.max_liquidity_offset_msat))
656 fn decayed_offset_msat(&self, offset_msat: u64) -> u64 {
657 self.now.duration_since(*self.last_updated).as_secs()
658 .checked_div(self.half_life.as_secs())
659 .and_then(|decays| offset_msat.checked_shr(decays as u32))
664 impl<L: DerefMut<Target = u64>, T: Time, U: DerefMut<Target = T>> DirectedChannelLiquidity<L, T, U> {
665 /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat`.
666 fn failed_at_channel(&mut self, amount_msat: u64) {
667 if amount_msat < self.max_liquidity_msat() {
668 self.set_max_liquidity_msat(amount_msat);
672 /// Adjusts the channel liquidity balance bounds when failing to route `amount_msat` downstream.
673 fn failed_downstream(&mut self, amount_msat: u64) {
674 if amount_msat > self.min_liquidity_msat() {
675 self.set_min_liquidity_msat(amount_msat);
679 /// Adjusts the channel liquidity balance bounds when successfully routing `amount_msat`.
680 fn successful(&mut self, amount_msat: u64) {
681 let max_liquidity_msat = self.max_liquidity_msat().checked_sub(amount_msat).unwrap_or(0);
682 self.set_max_liquidity_msat(max_liquidity_msat);
685 /// Adjusts the lower bound of the channel liquidity balance in this direction.
686 fn set_min_liquidity_msat(&mut self, amount_msat: u64) {
687 *self.min_liquidity_offset_msat = amount_msat;
688 *self.max_liquidity_offset_msat = if amount_msat > self.max_liquidity_msat() {
691 self.decayed_offset_msat(*self.max_liquidity_offset_msat)
693 *self.last_updated = self.now;
696 /// Adjusts the upper bound of the channel liquidity balance in this direction.
697 fn set_max_liquidity_msat(&mut self, amount_msat: u64) {
698 *self.max_liquidity_offset_msat = self.capacity_msat.checked_sub(amount_msat).unwrap_or(0);
699 *self.min_liquidity_offset_msat = if amount_msat < self.min_liquidity_msat() {
702 self.decayed_offset_msat(*self.min_liquidity_offset_msat)
704 *self.last_updated = self.now;
708 impl<G: Deref<Target = NetworkGraph>, T: Time> Score for ProbabilisticScorerUsingTime<G, T> {
709 fn channel_penalty_msat(
710 &self, short_channel_id: u64, amount_msat: u64, capacity_msat: u64, source: &NodeId,
713 let liquidity_penalty_multiplier_msat = self.params.liquidity_penalty_multiplier_msat;
714 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
715 let success_probability = self.channel_liquidities
716 .get(&short_channel_id)
717 .unwrap_or(&ChannelLiquidity::new())
718 .as_directed(source, target, capacity_msat, liquidity_offset_half_life)
719 .success_probability(amount_msat);
720 // NOTE: If success_probability is ever changed to return 0.0, log10 is undefined so return
721 // u64::max_value instead.
722 debug_assert!(success_probability > core::f64::EPSILON);
723 (-(success_probability.log10()) * liquidity_penalty_multiplier_msat as f64) as u64
726 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
727 let amount_msat = path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0);
728 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
729 let network_graph = self.network_graph.read_only();
731 let target = NodeId::from_pubkey(&hop.pubkey);
732 let channel_directed_from_source = network_graph.channels()
733 .get(&hop.short_channel_id)
734 .and_then(|channel| channel.as_directed_to(&target));
736 // Only score announced channels.
737 if let Some((channel, source)) = channel_directed_from_source {
738 let capacity_msat = channel.effective_capacity().as_msat();
739 if hop.short_channel_id == short_channel_id {
740 self.channel_liquidities
741 .entry(hop.short_channel_id)
742 .or_insert_with(ChannelLiquidity::new)
743 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
744 .failed_at_channel(amount_msat);
748 self.channel_liquidities
749 .entry(hop.short_channel_id)
750 .or_insert_with(ChannelLiquidity::new)
751 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
752 .failed_downstream(amount_msat);
757 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
758 let amount_msat = path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0);
759 let liquidity_offset_half_life = self.params.liquidity_offset_half_life;
760 let network_graph = self.network_graph.read_only();
762 let target = NodeId::from_pubkey(&hop.pubkey);
763 let channel_directed_from_source = network_graph.channels()
764 .get(&hop.short_channel_id)
765 .and_then(|channel| channel.as_directed_to(&target));
767 // Only score announced channels.
768 if let Some((channel, source)) = channel_directed_from_source {
769 let capacity_msat = channel.effective_capacity().as_msat();
770 self.channel_liquidities
771 .entry(hop.short_channel_id)
772 .or_insert_with(ChannelLiquidity::new)
773 .as_directed_mut(source, &target, capacity_msat, liquidity_offset_half_life)
774 .successful(amount_msat);
780 impl<G: Deref<Target = NetworkGraph>, T: Time> Writeable for ProbabilisticScorerUsingTime<G, T> {
782 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
783 write_tlv_fields!(w, {
784 (0, self.channel_liquidities, required)
790 impl<G, T> ReadableArgs<(ProbabilisticScoringParameters, G)> for ProbabilisticScorerUsingTime<G, T>
792 G: Deref<Target = NetworkGraph>,
797 r: &mut R, args: (ProbabilisticScoringParameters, G)
798 ) -> Result<Self, DecodeError> {
799 let (params, network_graph) = args;
800 let mut channel_liquidities = HashMap::new();
801 read_tlv_fields!(r, {
802 (0, channel_liquidities, required)
812 impl<T: Time> Writeable for ChannelLiquidity<T> {
814 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
815 let duration_since_epoch = T::duration_since_epoch() - self.last_updated.elapsed();
816 write_tlv_fields!(w, {
817 (0, self.min_liquidity_offset_msat, required),
818 (2, self.max_liquidity_offset_msat, required),
819 (4, duration_since_epoch, required),
825 impl<T: Time> Readable for ChannelLiquidity<T> {
827 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
828 let mut min_liquidity_offset_msat = 0;
829 let mut max_liquidity_offset_msat = 0;
830 let mut duration_since_epoch = Duration::from_secs(0);
831 read_tlv_fields!(r, {
832 (0, min_liquidity_offset_msat, required),
833 (2, max_liquidity_offset_msat, required),
834 (4, duration_since_epoch, required),
837 min_liquidity_offset_msat,
838 max_liquidity_offset_msat,
839 last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
844 pub(crate) mod time {
846 use core::time::Duration;
847 /// A measurement of time.
848 pub trait Time: Copy + Sub<Duration, Output = Self> where Self: Sized {
849 /// Returns an instance corresponding to the current moment.
852 /// Returns the amount of time elapsed since `self` was created.
853 fn elapsed(&self) -> Duration;
855 /// Returns the amount of time passed between `earlier` and `self`.
856 fn duration_since(&self, earlier: Self) -> Duration;
858 /// Returns the amount of time passed since the beginning of [`Time`].
860 /// Used during (de-)serialization.
861 fn duration_since_epoch() -> Duration;
864 /// A state in which time has no meaning.
865 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
868 #[cfg(not(feature = "no-std"))]
869 impl Time for std::time::Instant {
871 std::time::Instant::now()
874 fn duration_since(&self, earlier: Self) -> Duration {
875 self.duration_since(earlier)
878 fn duration_since_epoch() -> Duration {
879 use std::time::SystemTime;
880 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
883 fn elapsed(&self) -> Duration {
884 std::time::Instant::elapsed(self)
888 impl Time for Eternity {
893 fn duration_since(&self, _earlier: Self) -> Duration {
894 Duration::from_secs(0)
897 fn duration_since_epoch() -> Duration {
898 Duration::from_secs(0)
901 fn elapsed(&self) -> Duration {
902 Duration::from_secs(0)
906 impl Sub<Duration> for Eternity {
909 fn sub(self, _other: Duration) -> Self {
915 pub(crate) use self::time::Time;
919 use super::{ChannelLiquidity, ProbabilisticScoringParameters, ProbabilisticScorerUsingTime, ScoringParameters, ScorerUsingTime, Time};
920 use super::time::Eternity;
922 use ln::features::{ChannelFeatures, NodeFeatures};
923 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, OptionalField, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
924 use routing::scoring::Score;
925 use routing::network_graph::{NetworkGraph, NodeId};
926 use routing::router::RouteHop;
927 use util::ser::{Readable, ReadableArgs, Writeable};
929 use bitcoin::blockdata::constants::genesis_block;
930 use bitcoin::hashes::Hash;
931 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
932 use bitcoin::network::constants::Network;
933 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
934 use core::cell::Cell;
936 use core::time::Duration;
941 /// Time that can be advanced manually in tests.
942 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
943 struct SinceEpoch(Duration);
947 static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
950 fn advance(duration: Duration) {
951 Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
955 impl Time for SinceEpoch {
957 Self(Self::duration_since_epoch())
960 fn duration_since(&self, earlier: Self) -> Duration {
964 fn duration_since_epoch() -> Duration {
965 Self::ELAPSED.with(|elapsed| elapsed.get())
968 fn elapsed(&self) -> Duration {
969 Self::duration_since_epoch() - self.0
973 impl Sub<Duration> for SinceEpoch {
976 fn sub(self, other: Duration) -> Self {
982 fn time_passes_when_advanced() {
983 let now = SinceEpoch::now();
984 assert_eq!(now.elapsed(), Duration::from_secs(0));
986 SinceEpoch::advance(Duration::from_secs(1));
987 SinceEpoch::advance(Duration::from_secs(1));
989 let elapsed = now.elapsed();
990 let later = SinceEpoch::now();
992 assert_eq!(elapsed, Duration::from_secs(2));
993 assert_eq!(later - elapsed, now);
997 fn time_never_passes_in_an_eternity() {
998 let now = Eternity::now();
999 let elapsed = now.elapsed();
1000 let later = Eternity::now();
1002 assert_eq!(now.elapsed(), Duration::from_secs(0));
1003 assert_eq!(later - elapsed, now);
1008 /// A scorer for testing with time that can be manually advanced.
1009 type Scorer = ScorerUsingTime::<SinceEpoch>;
1011 fn source_privkey() -> SecretKey {
1012 SecretKey::from_slice(&[42; 32]).unwrap()
1015 fn target_privkey() -> SecretKey {
1016 SecretKey::from_slice(&[43; 32]).unwrap()
1019 fn source_pubkey() -> PublicKey {
1020 let secp_ctx = Secp256k1::new();
1021 PublicKey::from_secret_key(&secp_ctx, &source_privkey())
1024 fn target_pubkey() -> PublicKey {
1025 let secp_ctx = Secp256k1::new();
1026 PublicKey::from_secret_key(&secp_ctx, &target_privkey())
1029 fn source_node_id() -> NodeId {
1030 NodeId::from_pubkey(&source_pubkey())
1033 fn target_node_id() -> NodeId {
1034 NodeId::from_pubkey(&target_pubkey())
1038 fn penalizes_without_channel_failures() {
1039 let scorer = Scorer::new(ScoringParameters {
1040 base_penalty_msat: 1_000,
1041 failure_penalty_msat: 512,
1042 failure_penalty_half_life: Duration::from_secs(1),
1043 overuse_penalty_start_1024th: 1024,
1044 overuse_penalty_msat_per_1024th: 0,
1046 let source = source_node_id();
1047 let target = target_node_id();
1048 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1050 SinceEpoch::advance(Duration::from_secs(1));
1051 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1055 fn accumulates_channel_failure_penalties() {
1056 let mut scorer = Scorer::new(ScoringParameters {
1057 base_penalty_msat: 1_000,
1058 failure_penalty_msat: 64,
1059 failure_penalty_half_life: Duration::from_secs(10),
1060 overuse_penalty_start_1024th: 1024,
1061 overuse_penalty_msat_per_1024th: 0,
1063 let source = source_node_id();
1064 let target = target_node_id();
1065 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1067 scorer.payment_path_failed(&[], 42);
1068 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1070 scorer.payment_path_failed(&[], 42);
1071 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1073 scorer.payment_path_failed(&[], 42);
1074 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_192);
1078 fn decays_channel_failure_penalties_over_time() {
1079 let mut scorer = Scorer::new(ScoringParameters {
1080 base_penalty_msat: 1_000,
1081 failure_penalty_msat: 512,
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_512);
1093 SinceEpoch::advance(Duration::from_secs(9));
1094 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1096 SinceEpoch::advance(Duration::from_secs(1));
1097 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1099 SinceEpoch::advance(Duration::from_secs(10 * 8));
1100 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_001);
1102 SinceEpoch::advance(Duration::from_secs(10));
1103 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1105 SinceEpoch::advance(Duration::from_secs(10));
1106 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1110 fn decays_channel_failure_penalties_without_shift_overflow() {
1111 let mut scorer = Scorer::new(ScoringParameters {
1112 base_penalty_msat: 1_000,
1113 failure_penalty_msat: 512,
1114 failure_penalty_half_life: Duration::from_secs(10),
1115 overuse_penalty_start_1024th: 1024,
1116 overuse_penalty_msat_per_1024th: 0,
1118 let source = source_node_id();
1119 let target = target_node_id();
1120 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1122 scorer.payment_path_failed(&[], 42);
1123 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1125 // An unchecked right shift 64 bits or more in ChannelFailure::decayed_penalty_msat would
1126 // cause an overflow.
1127 SinceEpoch::advance(Duration::from_secs(10 * 64));
1128 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1130 SinceEpoch::advance(Duration::from_secs(10));
1131 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1135 fn accumulates_channel_failure_penalties_after_decay() {
1136 let mut scorer = Scorer::new(ScoringParameters {
1137 base_penalty_msat: 1_000,
1138 failure_penalty_msat: 512,
1139 failure_penalty_half_life: Duration::from_secs(10),
1140 overuse_penalty_start_1024th: 1024,
1141 overuse_penalty_msat_per_1024th: 0,
1143 let source = source_node_id();
1144 let target = target_node_id();
1145 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1147 scorer.payment_path_failed(&[], 42);
1148 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1150 SinceEpoch::advance(Duration::from_secs(10));
1151 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1153 scorer.payment_path_failed(&[], 42);
1154 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_768);
1156 SinceEpoch::advance(Duration::from_secs(10));
1157 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_384);
1161 fn reduces_channel_failure_penalties_after_success() {
1162 let mut scorer = Scorer::new(ScoringParameters {
1163 base_penalty_msat: 1_000,
1164 failure_penalty_msat: 512,
1165 failure_penalty_half_life: Duration::from_secs(10),
1166 overuse_penalty_start_1024th: 1024,
1167 overuse_penalty_msat_per_1024th: 0,
1169 let source = source_node_id();
1170 let target = target_node_id();
1171 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1173 scorer.payment_path_failed(&[], 42);
1174 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1176 SinceEpoch::advance(Duration::from_secs(10));
1177 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1179 let hop = RouteHop {
1180 pubkey: PublicKey::from_slice(target.as_slice()).unwrap(),
1181 node_features: NodeFeatures::known(),
1182 short_channel_id: 42,
1183 channel_features: ChannelFeatures::known(),
1185 cltv_expiry_delta: 18,
1187 scorer.payment_path_successful(&[&hop]);
1188 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1190 SinceEpoch::advance(Duration::from_secs(10));
1191 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1195 fn restores_persisted_channel_failure_penalties() {
1196 let mut scorer = Scorer::new(ScoringParameters {
1197 base_penalty_msat: 1_000,
1198 failure_penalty_msat: 512,
1199 failure_penalty_half_life: Duration::from_secs(10),
1200 overuse_penalty_start_1024th: 1024,
1201 overuse_penalty_msat_per_1024th: 0,
1203 let source = source_node_id();
1204 let target = target_node_id();
1206 scorer.payment_path_failed(&[], 42);
1207 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1209 SinceEpoch::advance(Duration::from_secs(10));
1210 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1212 scorer.payment_path_failed(&[], 43);
1213 assert_eq!(scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
1215 let mut serialized_scorer = Vec::new();
1216 scorer.write(&mut serialized_scorer).unwrap();
1218 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
1219 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1220 assert_eq!(deserialized_scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
1224 fn decays_persisted_channel_failure_penalties() {
1225 let mut scorer = Scorer::new(ScoringParameters {
1226 base_penalty_msat: 1_000,
1227 failure_penalty_msat: 512,
1228 failure_penalty_half_life: Duration::from_secs(10),
1229 overuse_penalty_start_1024th: 1024,
1230 overuse_penalty_msat_per_1024th: 0,
1232 let source = source_node_id();
1233 let target = target_node_id();
1235 scorer.payment_path_failed(&[], 42);
1236 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1238 let mut serialized_scorer = Vec::new();
1239 scorer.write(&mut serialized_scorer).unwrap();
1241 SinceEpoch::advance(Duration::from_secs(10));
1243 let deserialized_scorer = <Scorer>::read(&mut io::Cursor::new(&serialized_scorer)).unwrap();
1244 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1246 SinceEpoch::advance(Duration::from_secs(10));
1247 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1251 fn charges_per_1024th_penalty() {
1252 let scorer = Scorer::new(ScoringParameters {
1253 base_penalty_msat: 0,
1254 failure_penalty_msat: 0,
1255 failure_penalty_half_life: Duration::from_secs(0),
1256 overuse_penalty_start_1024th: 256,
1257 overuse_penalty_msat_per_1024th: 100,
1259 let source = source_node_id();
1260 let target = target_node_id();
1262 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 1_024_000, &source, &target), 0);
1263 assert_eq!(scorer.channel_penalty_msat(42, 256_999, 1_024_000, &source, &target), 0);
1264 assert_eq!(scorer.channel_penalty_msat(42, 257_000, 1_024_000, &source, &target), 100);
1265 assert_eq!(scorer.channel_penalty_msat(42, 258_000, 1_024_000, &source, &target), 200);
1266 assert_eq!(scorer.channel_penalty_msat(42, 512_000, 1_024_000, &source, &target), 256 * 100);
1269 // `ProbabilisticScorer` tests
1271 /// A probabilistic scorer for testing with time that can be manually advanced.
1272 type ProbabilisticScorer<'a> = ProbabilisticScorerUsingTime::<&'a NetworkGraph, SinceEpoch>;
1274 fn sender_privkey() -> SecretKey {
1275 SecretKey::from_slice(&[41; 32]).unwrap()
1278 fn recipient_privkey() -> SecretKey {
1279 SecretKey::from_slice(&[45; 32]).unwrap()
1282 fn sender_pubkey() -> PublicKey {
1283 let secp_ctx = Secp256k1::new();
1284 PublicKey::from_secret_key(&secp_ctx, &sender_privkey())
1287 fn recipient_pubkey() -> PublicKey {
1288 let secp_ctx = Secp256k1::new();
1289 PublicKey::from_secret_key(&secp_ctx, &recipient_privkey())
1292 fn sender_node_id() -> NodeId {
1293 NodeId::from_pubkey(&sender_pubkey())
1296 fn recipient_node_id() -> NodeId {
1297 NodeId::from_pubkey(&recipient_pubkey())
1300 fn network_graph() -> NetworkGraph {
1301 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1302 let mut network_graph = NetworkGraph::new(genesis_hash);
1303 add_channel(&mut network_graph, 42, source_privkey(), target_privkey());
1304 add_channel(&mut network_graph, 43, target_privkey(), recipient_privkey());
1310 network_graph: &mut NetworkGraph, short_channel_id: u64, node_1_key: SecretKey,
1311 node_2_key: SecretKey
1313 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1314 let node_1_secret = &SecretKey::from_slice(&[39; 32]).unwrap();
1315 let node_2_secret = &SecretKey::from_slice(&[40; 32]).unwrap();
1316 let secp_ctx = Secp256k1::new();
1317 let unsigned_announcement = UnsignedChannelAnnouncement {
1318 features: ChannelFeatures::known(),
1319 chain_hash: genesis_hash,
1321 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_key),
1322 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_key),
1323 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_secret),
1324 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_secret),
1325 excess_data: Vec::new(),
1327 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1328 let signed_announcement = ChannelAnnouncement {
1329 node_signature_1: secp_ctx.sign(&msghash, &node_1_key),
1330 node_signature_2: secp_ctx.sign(&msghash, &node_2_key),
1331 bitcoin_signature_1: secp_ctx.sign(&msghash, &node_1_secret),
1332 bitcoin_signature_2: secp_ctx.sign(&msghash, &node_2_secret),
1333 contents: unsigned_announcement,
1335 let chain_source: Option<&::util::test_utils::TestChainSource> = None;
1336 network_graph.update_channel_from_announcement(
1337 &signed_announcement, &chain_source, &secp_ctx).unwrap();
1338 update_channel(network_graph, short_channel_id, node_1_key, 0);
1339 update_channel(network_graph, short_channel_id, node_2_key, 1);
1343 network_graph: &mut NetworkGraph, short_channel_id: u64, node_key: SecretKey, flags: u8
1345 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1346 let secp_ctx = Secp256k1::new();
1347 let unsigned_update = UnsignedChannelUpdate {
1348 chain_hash: genesis_hash,
1352 cltv_expiry_delta: 18,
1353 htlc_minimum_msat: 0,
1354 htlc_maximum_msat: OptionalField::Present(1_000),
1356 fee_proportional_millionths: 0,
1357 excess_data: Vec::new(),
1359 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_update.encode()[..])[..]);
1360 let signed_update = ChannelUpdate {
1361 signature: secp_ctx.sign(&msghash, &node_key),
1362 contents: unsigned_update,
1364 network_graph.update_channel(&signed_update, &secp_ctx).unwrap();
1367 fn payment_path_for_amount(amount_msat: u64) -> Vec<RouteHop> {
1370 pubkey: source_pubkey(),
1371 node_features: NodeFeatures::known(),
1372 short_channel_id: 41,
1373 channel_features: ChannelFeatures::known(),
1375 cltv_expiry_delta: 18,
1378 pubkey: target_pubkey(),
1379 node_features: NodeFeatures::known(),
1380 short_channel_id: 42,
1381 channel_features: ChannelFeatures::known(),
1383 cltv_expiry_delta: 18,
1386 pubkey: recipient_pubkey(),
1387 node_features: NodeFeatures::known(),
1388 short_channel_id: 43,
1389 channel_features: ChannelFeatures::known(),
1390 fee_msat: amount_msat,
1391 cltv_expiry_delta: 18,
1397 fn liquidity_bounds_directed_from_lowest_node_id() {
1398 let last_updated = SinceEpoch::now();
1399 let network_graph = network_graph();
1400 let params = ProbabilisticScoringParameters::default();
1401 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1404 min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1408 min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1410 let source = source_node_id();
1411 let target = target_node_id();
1412 let recipient = recipient_node_id();
1413 assert!(source > target);
1414 assert!(target < recipient);
1416 // Update minimum liquidity.
1418 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1419 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1420 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1421 assert_eq!(liquidity.min_liquidity_msat(), 100);
1422 assert_eq!(liquidity.max_liquidity_msat(), 300);
1424 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1425 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1426 assert_eq!(liquidity.min_liquidity_msat(), 700);
1427 assert_eq!(liquidity.max_liquidity_msat(), 900);
1429 scorer.channel_liquidities.get_mut(&42).unwrap()
1430 .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1431 .set_min_liquidity_msat(200);
1433 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1434 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1435 assert_eq!(liquidity.min_liquidity_msat(), 200);
1436 assert_eq!(liquidity.max_liquidity_msat(), 300);
1438 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1439 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1440 assert_eq!(liquidity.min_liquidity_msat(), 700);
1441 assert_eq!(liquidity.max_liquidity_msat(), 800);
1443 // Update maximum liquidity.
1445 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1446 .as_directed(&target, &recipient, 1_000, liquidity_offset_half_life);
1447 assert_eq!(liquidity.min_liquidity_msat(), 700);
1448 assert_eq!(liquidity.max_liquidity_msat(), 900);
1450 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1451 .as_directed(&recipient, &target, 1_000, liquidity_offset_half_life);
1452 assert_eq!(liquidity.min_liquidity_msat(), 100);
1453 assert_eq!(liquidity.max_liquidity_msat(), 300);
1455 scorer.channel_liquidities.get_mut(&43).unwrap()
1456 .as_directed_mut(&target, &recipient, 1_000, liquidity_offset_half_life)
1457 .set_max_liquidity_msat(200);
1459 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1460 .as_directed(&target, &recipient, 1_000, liquidity_offset_half_life);
1461 assert_eq!(liquidity.min_liquidity_msat(), 0);
1462 assert_eq!(liquidity.max_liquidity_msat(), 200);
1464 let liquidity = scorer.channel_liquidities.get(&43).unwrap()
1465 .as_directed(&recipient, &target, 1_000, liquidity_offset_half_life);
1466 assert_eq!(liquidity.min_liquidity_msat(), 800);
1467 assert_eq!(liquidity.max_liquidity_msat(), 1000);
1471 fn resets_liquidity_upper_bound_when_crossed_by_lower_bound() {
1472 let last_updated = SinceEpoch::now();
1473 let network_graph = network_graph();
1474 let params = ProbabilisticScoringParameters::default();
1475 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1478 min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1480 let source = source_node_id();
1481 let target = target_node_id();
1482 assert!(source > target);
1484 // Check initial bounds.
1485 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1486 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1487 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1488 assert_eq!(liquidity.min_liquidity_msat(), 400);
1489 assert_eq!(liquidity.max_liquidity_msat(), 800);
1491 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1492 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1493 assert_eq!(liquidity.min_liquidity_msat(), 200);
1494 assert_eq!(liquidity.max_liquidity_msat(), 600);
1496 // Reset from source to target.
1497 scorer.channel_liquidities.get_mut(&42).unwrap()
1498 .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1499 .set_min_liquidity_msat(900);
1501 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1502 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1503 assert_eq!(liquidity.min_liquidity_msat(), 900);
1504 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1506 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1507 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1508 assert_eq!(liquidity.min_liquidity_msat(), 0);
1509 assert_eq!(liquidity.max_liquidity_msat(), 100);
1511 // Reset from target to source.
1512 scorer.channel_liquidities.get_mut(&42).unwrap()
1513 .as_directed_mut(&target, &source, 1_000, liquidity_offset_half_life)
1514 .set_min_liquidity_msat(400);
1516 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1517 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1518 assert_eq!(liquidity.min_liquidity_msat(), 0);
1519 assert_eq!(liquidity.max_liquidity_msat(), 600);
1521 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1522 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1523 assert_eq!(liquidity.min_liquidity_msat(), 400);
1524 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1528 fn resets_liquidity_lower_bound_when_crossed_by_upper_bound() {
1529 let last_updated = SinceEpoch::now();
1530 let network_graph = network_graph();
1531 let params = ProbabilisticScoringParameters::default();
1532 let mut scorer = ProbabilisticScorer::new(params, &network_graph)
1535 min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1537 let source = source_node_id();
1538 let target = target_node_id();
1539 assert!(source > target);
1541 // Check initial bounds.
1542 let liquidity_offset_half_life = scorer.params.liquidity_offset_half_life;
1543 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1544 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1545 assert_eq!(liquidity.min_liquidity_msat(), 400);
1546 assert_eq!(liquidity.max_liquidity_msat(), 800);
1548 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1549 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1550 assert_eq!(liquidity.min_liquidity_msat(), 200);
1551 assert_eq!(liquidity.max_liquidity_msat(), 600);
1553 // Reset from source to target.
1554 scorer.channel_liquidities.get_mut(&42).unwrap()
1555 .as_directed_mut(&source, &target, 1_000, liquidity_offset_half_life)
1556 .set_max_liquidity_msat(300);
1558 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1559 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1560 assert_eq!(liquidity.min_liquidity_msat(), 0);
1561 assert_eq!(liquidity.max_liquidity_msat(), 300);
1563 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1564 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1565 assert_eq!(liquidity.min_liquidity_msat(), 700);
1566 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1568 // Reset from target to source.
1569 scorer.channel_liquidities.get_mut(&42).unwrap()
1570 .as_directed_mut(&target, &source, 1_000, liquidity_offset_half_life)
1571 .set_max_liquidity_msat(600);
1573 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1574 .as_directed(&source, &target, 1_000, liquidity_offset_half_life);
1575 assert_eq!(liquidity.min_liquidity_msat(), 400);
1576 assert_eq!(liquidity.max_liquidity_msat(), 1_000);
1578 let liquidity = scorer.channel_liquidities.get(&42).unwrap()
1579 .as_directed(&target, &source, 1_000, liquidity_offset_half_life);
1580 assert_eq!(liquidity.min_liquidity_msat(), 0);
1581 assert_eq!(liquidity.max_liquidity_msat(), 600);
1585 fn increased_penalty_nearing_liquidity_upper_bound() {
1586 let network_graph = network_graph();
1587 let params = ProbabilisticScoringParameters {
1588 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1590 let scorer = ProbabilisticScorer::new(params, &network_graph);
1591 let source = source_node_id();
1592 let target = target_node_id();
1594 assert_eq!(scorer.channel_penalty_msat(42, 100, 100_000, &source, &target), 0);
1595 assert_eq!(scorer.channel_penalty_msat(42, 1_000, 100_000, &source, &target), 4);
1596 assert_eq!(scorer.channel_penalty_msat(42, 10_000, 100_000, &source, &target), 45);
1597 assert_eq!(scorer.channel_penalty_msat(42, 100_000, 100_000, &source, &target), 2_000);
1599 assert_eq!(scorer.channel_penalty_msat(42, 125, 1_000, &source, &target), 57);
1600 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1601 assert_eq!(scorer.channel_penalty_msat(42, 375, 1_000, &source, &target), 203);
1602 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1603 assert_eq!(scorer.channel_penalty_msat(42, 625, 1_000, &source, &target), 425);
1604 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1605 assert_eq!(scorer.channel_penalty_msat(42, 875, 1_000, &source, &target), 900);
1609 fn constant_penalty_outside_liquidity_bounds() {
1610 let last_updated = SinceEpoch::now();
1611 let network_graph = network_graph();
1612 let params = ProbabilisticScoringParameters {
1613 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1615 let scorer = ProbabilisticScorer::new(params, &network_graph)
1618 min_liquidity_offset_msat: 40, max_liquidity_offset_msat: 40, last_updated
1620 let source = source_node_id();
1621 let target = target_node_id();
1623 assert_eq!(scorer.channel_penalty_msat(42, 39, 100, &source, &target), 0);
1624 assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 0);
1625 assert_ne!(scorer.channel_penalty_msat(42, 50, 100, &source, &target), 2_000);
1626 assert_eq!(scorer.channel_penalty_msat(42, 61, 100, &source, &target), 2_000);
1630 fn does_not_further_penalize_own_channel() {
1631 let network_graph = network_graph();
1632 let params = ProbabilisticScoringParameters {
1633 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1635 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1636 let sender = sender_node_id();
1637 let source = source_node_id();
1638 let failed_path = payment_path_for_amount(500);
1639 let successful_path = payment_path_for_amount(200);
1641 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1643 scorer.payment_path_failed(&failed_path.iter().collect::<Vec<_>>(), 41);
1644 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1646 scorer.payment_path_successful(&successful_path.iter().collect::<Vec<_>>());
1647 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1651 fn sets_liquidity_lower_bound_on_downstream_failure() {
1652 let network_graph = network_graph();
1653 let params = ProbabilisticScoringParameters {
1654 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1656 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1657 let source = source_node_id();
1658 let target = target_node_id();
1659 let path = payment_path_for_amount(500);
1661 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1662 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1663 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1665 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 43);
1667 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 0);
1668 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 0);
1669 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 300);
1673 fn sets_liquidity_upper_bound_on_failure() {
1674 let network_graph = network_graph();
1675 let params = ProbabilisticScoringParameters {
1676 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1678 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1679 let source = source_node_id();
1680 let target = target_node_id();
1681 let path = payment_path_for_amount(500);
1683 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1684 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1685 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 600);
1687 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 42);
1689 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 300);
1690 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1691 assert_eq!(scorer.channel_penalty_msat(42, 750, 1_000, &source, &target), 2_000);
1695 fn reduces_liquidity_upper_bound_along_path_on_success() {
1696 let network_graph = network_graph();
1697 let params = ProbabilisticScoringParameters {
1698 liquidity_penalty_multiplier_msat: 1_000, ..Default::default()
1700 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1701 let sender = sender_node_id();
1702 let source = source_node_id();
1703 let target = target_node_id();
1704 let recipient = recipient_node_id();
1705 let path = payment_path_for_amount(500);
1707 assert_eq!(scorer.channel_penalty_msat(41, 250, 1_000, &sender, &source), 124);
1708 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 124);
1709 assert_eq!(scorer.channel_penalty_msat(43, 250, 1_000, &target, &recipient), 124);
1711 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
1713 assert_eq!(scorer.channel_penalty_msat(41, 250, 1_000, &sender, &source), 124);
1714 assert_eq!(scorer.channel_penalty_msat(42, 250, 1_000, &source, &target), 300);
1715 assert_eq!(scorer.channel_penalty_msat(43, 250, 1_000, &target, &recipient), 300);
1719 fn decays_liquidity_bounds_over_time() {
1720 let network_graph = network_graph();
1721 let params = ProbabilisticScoringParameters {
1722 liquidity_penalty_multiplier_msat: 1_000,
1723 liquidity_offset_half_life: Duration::from_secs(10),
1725 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1726 let source = source_node_id();
1727 let target = target_node_id();
1729 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1730 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1732 scorer.payment_path_failed(&payment_path_for_amount(768).iter().collect::<Vec<_>>(), 42);
1733 scorer.payment_path_failed(&payment_path_for_amount(128).iter().collect::<Vec<_>>(), 43);
1735 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
1736 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 92);
1737 assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_424);
1738 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
1740 SinceEpoch::advance(Duration::from_secs(9));
1741 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 0);
1742 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 92);
1743 assert_eq!(scorer.channel_penalty_msat(42, 768, 1_024, &source, &target), 1_424);
1744 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 2_000);
1746 SinceEpoch::advance(Duration::from_secs(1));
1747 assert_eq!(scorer.channel_penalty_msat(42, 64, 1_024, &source, &target), 0);
1748 assert_eq!(scorer.channel_penalty_msat(42, 128, 1_024, &source, &target), 34);
1749 assert_eq!(scorer.channel_penalty_msat(42, 896, 1_024, &source, &target), 1_812);
1750 assert_eq!(scorer.channel_penalty_msat(42, 960, 1_024, &source, &target), 2_000);
1752 // Fully decay liquidity lower bound.
1753 SinceEpoch::advance(Duration::from_secs(10 * 7));
1754 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1755 assert_eq!(scorer.channel_penalty_msat(42, 1, 1_024, &source, &target), 0);
1756 assert_eq!(scorer.channel_penalty_msat(42, 1_023, 1_024, &source, &target), 2_000);
1757 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1759 // Fully decay liquidity upper bound.
1760 SinceEpoch::advance(Duration::from_secs(10));
1761 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1762 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1764 SinceEpoch::advance(Duration::from_secs(10));
1765 assert_eq!(scorer.channel_penalty_msat(42, 0, 1_024, &source, &target), 0);
1766 assert_eq!(scorer.channel_penalty_msat(42, 1_024, 1_024, &source, &target), 2_000);
1770 fn decays_liquidity_bounds_without_shift_overflow() {
1771 let network_graph = network_graph();
1772 let params = ProbabilisticScoringParameters {
1773 liquidity_penalty_multiplier_msat: 1_000,
1774 liquidity_offset_half_life: Duration::from_secs(10),
1776 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1777 let source = source_node_id();
1778 let target = target_node_id();
1779 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1781 scorer.payment_path_failed(&payment_path_for_amount(512).iter().collect::<Vec<_>>(), 42);
1782 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 281);
1784 // An unchecked right shift 64 bits or more in DirectedChannelLiquidity::decayed_offset_msat
1785 // would cause an overflow.
1786 SinceEpoch::advance(Duration::from_secs(10 * 64));
1787 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1789 SinceEpoch::advance(Duration::from_secs(10));
1790 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1794 fn restricts_liquidity_bounds_after_decay() {
1795 let network_graph = network_graph();
1796 let params = ProbabilisticScoringParameters {
1797 liquidity_penalty_multiplier_msat: 1_000,
1798 liquidity_offset_half_life: Duration::from_secs(10),
1800 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1801 let source = source_node_id();
1802 let target = target_node_id();
1804 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 300);
1806 // More knowledge gives higher confidence (256, 768), meaning a lower penalty.
1807 scorer.payment_path_failed(&payment_path_for_amount(768).iter().collect::<Vec<_>>(), 42);
1808 scorer.payment_path_failed(&payment_path_for_amount(256).iter().collect::<Vec<_>>(), 43);
1809 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 281);
1811 // Decaying knowledge gives less confidence (128, 896), meaning a higher penalty.
1812 SinceEpoch::advance(Duration::from_secs(10));
1813 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 293);
1815 // Reducing the upper bound gives more confidence (128, 832) that the payment amount (512)
1816 // is closer to the upper bound, meaning a higher penalty.
1817 scorer.payment_path_successful(&payment_path_for_amount(64).iter().collect::<Vec<_>>());
1818 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 333);
1820 // Increasing the lower bound gives more confidence (256, 832) that the payment amount (512)
1821 // is closer to the lower bound, meaning a lower penalty.
1822 scorer.payment_path_failed(&payment_path_for_amount(256).iter().collect::<Vec<_>>(), 43);
1823 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 247);
1825 // Further decaying affects the lower bound more than the upper bound (128, 928).
1826 SinceEpoch::advance(Duration::from_secs(10));
1827 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 280);
1831 fn restores_persisted_liquidity_bounds() {
1832 let network_graph = network_graph();
1833 let params = ProbabilisticScoringParameters {
1834 liquidity_penalty_multiplier_msat: 1_000,
1835 liquidity_offset_half_life: Duration::from_secs(10),
1837 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1838 let source = source_node_id();
1839 let target = target_node_id();
1841 scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
1842 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1844 SinceEpoch::advance(Duration::from_secs(10));
1845 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 475);
1847 scorer.payment_path_failed(&payment_path_for_amount(250).iter().collect::<Vec<_>>(), 43);
1848 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1850 let mut serialized_scorer = Vec::new();
1851 scorer.write(&mut serialized_scorer).unwrap();
1853 let mut serialized_scorer = io::Cursor::new(&serialized_scorer);
1854 let deserialized_scorer =
1855 <ProbabilisticScorer>::read(&mut serialized_scorer, (params, &network_graph)).unwrap();
1856 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1860 fn decays_persisted_liquidity_bounds() {
1861 let network_graph = network_graph();
1862 let params = ProbabilisticScoringParameters {
1863 liquidity_penalty_multiplier_msat: 1_000,
1864 liquidity_offset_half_life: Duration::from_secs(10),
1866 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1867 let source = source_node_id();
1868 let target = target_node_id();
1870 scorer.payment_path_failed(&payment_path_for_amount(500).iter().collect::<Vec<_>>(), 42);
1871 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 2_000);
1873 let mut serialized_scorer = Vec::new();
1874 scorer.write(&mut serialized_scorer).unwrap();
1876 SinceEpoch::advance(Duration::from_secs(10));
1878 let mut serialized_scorer = io::Cursor::new(&serialized_scorer);
1879 let deserialized_scorer =
1880 <ProbabilisticScorer>::read(&mut serialized_scorer, (params, &network_graph)).unwrap();
1881 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 475);
1883 scorer.payment_path_failed(&payment_path_for_amount(250).iter().collect::<Vec<_>>(), 43);
1884 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 300);
1886 SinceEpoch::advance(Duration::from_secs(10));
1887 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 367);