Merge pull request #1292 from TheBlueMatt/2022-02-override-handshake-limits
[rust-lightning] / lightning / src / routing / scoring.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Utilities for scoring payment channels.
11 //!
12 //! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path
13 //! finding when a custom [`Score`] implementation is not needed.
14 //!
15 //! # Example
16 //!
17 //! ```
18 //! # extern crate secp256k1;
19 //! #
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;
25 //! #
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! #     fn log(&self, record: &Record) { unimplemented!() }
29 //! # }
30 //! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph) {
31 //! # let logger = FakeLogger {};
32 //! #
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringParameters::default();
35 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
36 //!
37 //! // Or use custom channel penalties.
38 //! let params = ProbabilisticScoringParameters {
39 //!     liquidity_penalty_multiplier_msat: 2 * 1000,
40 //!     ..ProbabilisticScoringParameters::default()
41 //! };
42 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
43 //!
44 //! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer);
45 //! # }
46 //! ```
47 //!
48 //! # Note
49 //!
50 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
51 //! different types and thus is undefined.
52 //!
53 //! [`find_route`]: crate::routing::router::find_route
54
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};
59
60 use prelude::*;
61 use core::cell::{RefCell, RefMut};
62 use core::ops::{Deref, DerefMut};
63 use core::time::Duration;
64 use io::{self, Read};
65 use sync::{Mutex, MutexGuard};
66
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`.
71 ///
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.
80 ///
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`.
85         ///
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;
92
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);
95
96         /// Handles updating channel penalties after successfully routing along a path.
97         fn payment_path_successful(&mut self, path: &[&RouteHop]);
98 }
99
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)
103         }
104
105         fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
106                 self.deref_mut().payment_path_failed(path, short_channel_id)
107         }
108
109         fn payment_path_successful(&mut self, path: &[&RouteHop]) {
110                 self.deref_mut().payment_path_successful(path)
111         }
112 }
113 } }
114
115 #[cfg(c_bindings)]
116 define_score!(Writeable);
117 #[cfg(not(c_bindings))]
118 define_score!();
119
120 /// A scorer that is accessed under a lock.
121 ///
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.
126 ///
127 /// [`find_route`]: crate::routing::router::find_route
128 pub trait LockableScore<'a> {
129         /// The locked [`Score`] type.
130         type Locked: 'a + Score;
131
132         /// Returns the locked scorer.
133         fn lock(&'a self) -> Self::Locked;
134 }
135
136 /// (C-not exported)
137 impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
138         type Locked = MutexGuard<'a, T>;
139
140         fn lock(&'a self) -> MutexGuard<'a, T> {
141                 Mutex::lock(self).unwrap()
142         }
143 }
144
145 impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
146         type Locked = RefMut<'a, T>;
147
148         fn lock(&'a self) -> RefMut<'a, T> {
149                 self.borrow_mut()
150         }
151 }
152
153 #[cfg(c_bindings)]
154 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
155 pub struct MultiThreadedLockableScore<S: Score> {
156         score: Mutex<S>,
157 }
158 #[cfg(c_bindings)]
159 /// (C-not exported)
160 impl<'a, T: Score + 'a> LockableScore<'a> for MultiThreadedLockableScore<T> {
161         type Locked = MutexGuard<'a, T>;
162
163         fn lock(&'a self) -> MutexGuard<'a, T> {
164                 Mutex::lock(&self.score).unwrap()
165         }
166 }
167
168 #[cfg(c_bindings)]
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) }
173         }
174 }
175
176 #[cfg(c_bindings)]
177 /// (C-not exported)
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)
181         }
182 }
183
184 #[cfg(c_bindings)]
185 /// (C-not exported)
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)
189         }
190 }
191
192 /// [`Score`] implementation that uses a fixed penalty.
193 pub struct FixedPenaltyScorer {
194         penalty_msat: u64,
195 }
196
197 impl_writeable_tlv_based!(FixedPenaltyScorer, {
198         (0, penalty_msat, required),
199 });
200
201 impl FixedPenaltyScorer {
202         /// Creates a new scorer using `penalty_msat`.
203         pub fn with_penalty(penalty_msat: u64) -> Self {
204                 Self { penalty_msat }
205         }
206 }
207
208 impl Score for FixedPenaltyScorer {
209         fn channel_penalty_msat(&self, _: u64, _: u64, _: u64, _: &NodeId, _: &NodeId) -> u64 {
210                 self.penalty_msat
211         }
212
213         fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
214
215         fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
216 }
217
218 /// [`Score`] implementation that provides reasonable default behavior.
219 ///
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.
222 ///
223 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
224 ///
225 /// # Note
226 ///
227 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
228 /// behavior.
229 ///
230 /// [module-level documentation]: crate::routing::scoring
231 #[deprecated(
232         since = "0.0.105",
233         note = "ProbabilisticScorer should be used instead of Scorer.",
234 )]
235 pub type Scorer = ScorerUsingTime::<ConfiguredTime>;
236
237 #[cfg(not(feature = "no-std"))]
238 type ConfiguredTime = std::time::Instant;
239 #[cfg(feature = "no-std")]
240 type ConfiguredTime = time::Eternity;
241
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
244 // methods at all.
245
246 /// [`Score`] implementation.
247 ///
248 /// (C-not exported) generally all users should use the [`Scorer`] type alias.
249 #[doc(hidden)]
250 pub struct ScorerUsingTime<T: Time> {
251         params: ScoringParameters,
252         // TODO: Remove entries of closed channels.
253         channel_failures: HashMap<u64, ChannelFailure<T>>,
254 }
255
256 /// Parameters for configuring [`Scorer`].
257 pub struct ScoringParameters {
258         /// A fixed penalty in msats to apply to each channel.
259         ///
260         /// Default value: 500 msat
261         pub base_penalty_msat: u64,
262
263         /// A penalty in msats to apply to a channel upon failing to relay a payment.
264         ///
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.
267         ///
268         /// Default value: 1,024,000 msat
269         ///
270         /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
271         pub failure_penalty_msat: u64,
272
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`].
275         ///
276         /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
277         ///
278         /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
279         pub overuse_penalty_start_1024th: u16,
280
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.
283         ///
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)
286         ///
287         /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
288         pub overuse_penalty_msat_per_1024th: u64,
289
290         /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
291         /// cut in half.
292         ///
293         /// Successfully routing through a channel will immediately cut the penalty in half as well.
294         ///
295         /// Default value: 1 hour
296         ///
297         /// # Note
298         ///
299         /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
300         /// never decay.
301         ///
302         /// [`failure_penalty_msat`]: Self::failure_penalty_msat
303         pub failure_penalty_half_life: Duration,
304 }
305
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),
312 });
313
314 /// Accounting for penalties against a channel for failing to relay any payments.
315 ///
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,
320
321         /// Last time the channel either failed to route or successfully routed a payment. Used to decay
322         /// `undecayed_penalty_msat`.
323         last_updated: T,
324 }
325
326 impl<T: Time> ScorerUsingTime<T> {
327         /// Creates a new scorer using the given scoring parameters.
328         pub fn new(params: ScoringParameters) -> Self {
329                 Self {
330                         params,
331                         channel_failures: HashMap::new(),
332                 }
333         }
334 }
335
336 impl<T: Time> ChannelFailure<T> {
337         fn new(failure_penalty_msat: u64) -> Self {
338                 Self {
339                         undecayed_penalty_msat: failure_penalty_msat,
340                         last_updated: T::now(),
341                 }
342         }
343
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();
347         }
348
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();
352         }
353
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))
358                         .unwrap_or(0)
359         }
360 }
361
362 impl<T: Time> Default for ScorerUsingTime<T> {
363         fn default() -> Self {
364                 Self::new(ScoringParameters::default())
365         }
366 }
367
368 impl Default for ScoringParameters {
369         fn default() -> Self {
370                 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,
376                 }
377         }
378 }
379
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
383         ) -> u64 {
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));
387
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());
395                 }
396
397                 penalty_msat
398         }
399
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));
407         }
408
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));
415                 }
416         }
417 }
418
419 impl<T: Time> Writeable for ScorerUsingTime<T> {
420         #[inline]
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, {});
425                 Ok(())
426         }
427 }
428
429 impl<T: Time> Readable for ScorerUsingTime<T> {
430         #[inline]
431         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
432                 let res = Ok(Self {
433                         params: Readable::read(r)?,
434                         channel_failures: Readable::read(r)?,
435                 });
436                 read_tlv_fields!(r, {});
437                 res
438         }
439 }
440
441 impl<T: Time> Writeable for ChannelFailure<T> {
442         #[inline]
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),
448                 });
449                 Ok(())
450         }
451 }
452
453 impl<T: Time> Readable for ChannelFailure<T> {
454         #[inline]
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),
461                 });
462                 Ok(Self {
463                         undecayed_penalty_msat,
464                         last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
465                 })
466         }
467 }
468
469 /// [`Score`] implementation using channel success probability distributions.
470 ///
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.
476 ///
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.
480 ///
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.
484 ///
485 /// # Note
486 ///
487 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
488 /// behavior.
489 ///
490 /// [1]: https://arxiv.org/abs/2107.05322
491 pub type ProbabilisticScorer<G> = ProbabilisticScorerUsingTime::<G, ConfiguredTime>;
492
493 /// Probabilistic [`Score`] implementation.
494 ///
495 /// (C-not exported) generally all users should use the [`ProbabilisticScorer`] type alias.
496 #[doc(hidden)]
497 pub struct ProbabilisticScorerUsingTime<G: Deref<Target = NetworkGraph>, T: Time> {
498         params: ProbabilisticScoringParameters,
499         network_graph: G,
500         // TODO: Remove entries of closed channels.
501         channel_liquidities: HashMap<u64, ChannelLiquidity<T>>,
502 }
503
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.
510         ///
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`].
516         ///
517         /// Default value: 10,000 msat
518         ///
519         /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
520         pub liquidity_penalty_multiplier_msat: u64,
521
522         /// The time required to elapse before any knowledge learned about channel liquidity balances is
523         /// cut in half.
524         ///
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.
528         ///
529         /// Default value: 1 hour
530         ///
531         /// # Note
532         ///
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,
536 }
537
538 impl_writeable_tlv_based!(ProbabilisticScoringParameters, {
539         (0, liquidity_penalty_multiplier_msat, required),
540         (2, liquidity_offset_half_life, required),
541 });
542
543 /// Accounting for channel liquidity balance uncertainty.
544 ///
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,
551
552         /// Upper channel liquidity bound in terms of an offset from the effective capacity.
553         max_liquidity_offset_msat: u64,
554
555         /// Time when the liquidity bounds were last modified.
556         last_updated: T,
557 }
558
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,
564         capacity_msat: u64,
565         last_updated: U,
566         now: T,
567         half_life: Duration,
568 }
569
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 {
574                 Self {
575                         params,
576                         network_graph,
577                         channel_liquidities: HashMap::new(),
578                 }
579         }
580
581         #[cfg(test)]
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());
584                 self
585         }
586 }
587
588 impl Default for ProbabilisticScoringParameters {
589         fn default() -> Self {
590                 Self {
591                         liquidity_penalty_multiplier_msat: 10_000,
592                         liquidity_offset_half_life: Duration::from_secs(3600),
593                 }
594         }
595 }
596
597 impl<T: Time> ChannelLiquidity<T> {
598         #[inline]
599         fn new() -> Self {
600                 Self {
601                         min_liquidity_offset_msat: 0,
602                         max_liquidity_offset_msat: 0,
603                         last_updated: T::now(),
604                 }
605         }
606
607         /// Returns a view of the channel liquidity directed from `source` to `target` assuming
608         /// `capacity_msat`.
609         fn as_directed(
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)
614                 } else {
615                         (&self.max_liquidity_offset_msat, &self.min_liquidity_offset_msat)
616                 };
617
618                 DirectedChannelLiquidity {
619                         min_liquidity_offset_msat,
620                         max_liquidity_offset_msat,
621                         capacity_msat,
622                         last_updated: &self.last_updated,
623                         now: T::now(),
624                         half_life,
625                 }
626         }
627
628         /// Returns a mutable view of the channel liquidity directed from `source` to `target` assuming
629         /// `capacity_msat`.
630         fn as_directed_mut(
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)
635                 } else {
636                         (&mut self.max_liquidity_offset_msat, &mut self.min_liquidity_offset_msat)
637                 };
638
639                 DirectedChannelLiquidity {
640                         min_liquidity_offset_msat,
641                         max_liquidity_offset_msat,
642                         capacity_msat,
643                         last_updated: &mut self.last_updated,
644                         now: T::now(),
645                         half_life,
646                 }
647         }
648 }
649
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 {
657                         0.0
658                 } else if amount_msat <= min_liquidity_msat {
659                         1.0
660                 } else {
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.
665         }
666
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)
670         }
671
672         /// Returns the upper bound of the channel liquidity balance in this direction.
673         fn max_liquidity_msat(&self) -> u64 {
674                 self.capacity_msat
675                         .checked_sub(self.decayed_offset_msat(*self.max_liquidity_offset_msat))
676                         .unwrap_or(0)
677         }
678
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))
683                         .unwrap_or(0)
684         }
685 }
686
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);
692                 }
693         }
694
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);
699                 }
700         }
701
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);
706         }
707
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() {
712                         0
713                 } else {
714                         self.decayed_offset_msat(*self.max_liquidity_offset_msat)
715                 };
716                 *self.last_updated = self.now;
717         }
718
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() {
723                         0
724                 } else {
725                         self.decayed_offset_msat(*self.min_liquidity_offset_msat)
726                 };
727                 *self.last_updated = self.now;
728         }
729 }
730
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,
734                 target: &NodeId
735         ) -> u64 {
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
747         }
748
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();
753                 for hop in path {
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));
758
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);
768                                         break;
769                                 }
770
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);
776                         }
777                 }
778         }
779
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();
784                 for hop in path {
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));
789
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);
798                         }
799                 }
800         }
801 }
802
803 impl<G: Deref<Target = NetworkGraph>, T: Time> Writeable for ProbabilisticScorerUsingTime<G, T> {
804         #[inline]
805         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
806                 write_tlv_fields!(w, {
807                         (0, self.channel_liquidities, required)
808                 });
809                 Ok(())
810         }
811 }
812
813 impl<G, T> ReadableArgs<(ProbabilisticScoringParameters, G)> for ProbabilisticScorerUsingTime<G, T>
814 where
815         G: Deref<Target = NetworkGraph>,
816         T: Time,
817 {
818         #[inline]
819         fn read<R: Read>(
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)
826                 });
827                 Ok(Self {
828                         params,
829                         network_graph,
830                         channel_liquidities,
831                 })
832         }
833 }
834
835 impl<T: Time> Writeable for ChannelLiquidity<T> {
836         #[inline]
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),
843                 });
844                 Ok(())
845         }
846 }
847
848 impl<T: Time> Readable for ChannelLiquidity<T> {
849         #[inline]
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),
858                 });
859                 Ok(Self {
860                         min_liquidity_offset_msat,
861                         max_liquidity_offset_msat,
862                         last_updated: T::now() - (T::duration_since_epoch() - duration_since_epoch),
863                 })
864         }
865 }
866
867 pub(crate) mod time {
868         use core::ops::Sub;
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.
873                 fn now() -> Self;
874
875                 /// Returns the amount of time elapsed since `self` was created.
876                 fn elapsed(&self) -> Duration;
877
878                 /// Returns the amount of time passed between `earlier` and `self`.
879                 fn duration_since(&self, earlier: Self) -> Duration;
880
881                 /// Returns the amount of time passed since the beginning of [`Time`].
882                 ///
883                 /// Used during (de-)serialization.
884                 fn duration_since_epoch() -> Duration;
885         }
886
887         /// A state in which time has no meaning.
888         #[derive(Clone, Copy, Debug, PartialEq, Eq)]
889         pub struct Eternity;
890
891         #[cfg(not(feature = "no-std"))]
892         impl Time for std::time::Instant {
893                 fn now() -> Self {
894                         std::time::Instant::now()
895                 }
896
897                 fn duration_since(&self, earlier: Self) -> Duration {
898                         self.duration_since(earlier)
899                 }
900
901                 fn duration_since_epoch() -> Duration {
902                         use std::time::SystemTime;
903                         SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
904                 }
905
906                 fn elapsed(&self) -> Duration {
907                         std::time::Instant::elapsed(self)
908                 }
909         }
910
911         impl Time for Eternity {
912                 fn now() -> Self {
913                         Self
914                 }
915
916                 fn duration_since(&self, _earlier: Self) -> Duration {
917                         Duration::from_secs(0)
918                 }
919
920                 fn duration_since_epoch() -> Duration {
921                         Duration::from_secs(0)
922                 }
923
924                 fn elapsed(&self) -> Duration {
925                         Duration::from_secs(0)
926                 }
927         }
928
929         impl Sub<Duration> for Eternity {
930                 type Output = Self;
931
932                 fn sub(self, _other: Duration) -> Self {
933                         self
934                 }
935         }
936 }
937
938 pub(crate) use self::time::Time;
939
940 #[cfg(test)]
941 mod tests {
942         use super::{ChannelLiquidity, ProbabilisticScoringParameters, ProbabilisticScorerUsingTime, ScoringParameters, ScorerUsingTime, Time};
943         use super::time::Eternity;
944
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};
951
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;
958         use core::ops::Sub;
959         use core::time::Duration;
960         use io;
961
962         // `Time` tests
963
964         /// Time that can be advanced manually in tests.
965         #[derive(Clone, Copy, Debug, PartialEq, Eq)]
966         struct SinceEpoch(Duration);
967
968         impl SinceEpoch {
969                 thread_local! {
970                         static ELAPSED: Cell<Duration> = core::cell::Cell::new(Duration::from_secs(0));
971                 }
972
973                 fn advance(duration: Duration) {
974                         Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
975                 }
976         }
977
978         impl Time for SinceEpoch {
979                 fn now() -> Self {
980                         Self(Self::duration_since_epoch())
981                 }
982
983                 fn duration_since(&self, earlier: Self) -> Duration {
984                         self.0 - earlier.0
985                 }
986
987                 fn duration_since_epoch() -> Duration {
988                         Self::ELAPSED.with(|elapsed| elapsed.get())
989                 }
990
991                 fn elapsed(&self) -> Duration {
992                         Self::duration_since_epoch() - self.0
993                 }
994         }
995
996         impl Sub<Duration> for SinceEpoch {
997                 type Output = Self;
998
999                 fn sub(self, other: Duration) -> Self {
1000                         Self(self.0 - other)
1001                 }
1002         }
1003
1004         #[test]
1005         fn time_passes_when_advanced() {
1006                 let now = SinceEpoch::now();
1007                 assert_eq!(now.elapsed(), Duration::from_secs(0));
1008
1009                 SinceEpoch::advance(Duration::from_secs(1));
1010                 SinceEpoch::advance(Duration::from_secs(1));
1011
1012                 let elapsed = now.elapsed();
1013                 let later = SinceEpoch::now();
1014
1015                 assert_eq!(elapsed, Duration::from_secs(2));
1016                 assert_eq!(later - elapsed, now);
1017         }
1018
1019         #[test]
1020         fn time_never_passes_in_an_eternity() {
1021                 let now = Eternity::now();
1022                 let elapsed = now.elapsed();
1023                 let later = Eternity::now();
1024
1025                 assert_eq!(now.elapsed(), Duration::from_secs(0));
1026                 assert_eq!(later - elapsed, now);
1027         }
1028
1029         // `Scorer` tests
1030
1031         /// A scorer for testing with time that can be manually advanced.
1032         type Scorer = ScorerUsingTime::<SinceEpoch>;
1033
1034         fn source_privkey() -> SecretKey {
1035                 SecretKey::from_slice(&[42; 32]).unwrap()
1036         }
1037
1038         fn target_privkey() -> SecretKey {
1039                 SecretKey::from_slice(&[43; 32]).unwrap()
1040         }
1041
1042         fn source_pubkey() -> PublicKey {
1043                 let secp_ctx = Secp256k1::new();
1044                 PublicKey::from_secret_key(&secp_ctx, &source_privkey())
1045         }
1046
1047         fn target_pubkey() -> PublicKey {
1048                 let secp_ctx = Secp256k1::new();
1049                 PublicKey::from_secret_key(&secp_ctx, &target_privkey())
1050         }
1051
1052         fn source_node_id() -> NodeId {
1053                 NodeId::from_pubkey(&source_pubkey())
1054         }
1055
1056         fn target_node_id() -> NodeId {
1057                 NodeId::from_pubkey(&target_pubkey())
1058         }
1059
1060         #[test]
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,
1068                 });
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);
1072
1073                 SinceEpoch::advance(Duration::from_secs(1));
1074                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1075         }
1076
1077         #[test]
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,
1085                 });
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);
1089
1090                 scorer.payment_path_failed(&[], 42);
1091                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1092
1093                 scorer.payment_path_failed(&[], 42);
1094                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1095
1096                 scorer.payment_path_failed(&[], 42);
1097                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_192);
1098         }
1099
1100         #[test]
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,
1108                 });
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);
1112
1113                 scorer.payment_path_failed(&[], 42);
1114                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1115
1116                 SinceEpoch::advance(Duration::from_secs(9));
1117                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1118
1119                 SinceEpoch::advance(Duration::from_secs(1));
1120                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1121
1122                 SinceEpoch::advance(Duration::from_secs(10 * 8));
1123                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_001);
1124
1125                 SinceEpoch::advance(Duration::from_secs(10));
1126                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1127
1128                 SinceEpoch::advance(Duration::from_secs(10));
1129                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1130         }
1131
1132         #[test]
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,
1140                 });
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);
1144
1145                 scorer.payment_path_failed(&[], 42);
1146                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1147
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);
1152
1153                 SinceEpoch::advance(Duration::from_secs(10));
1154                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_000);
1155         }
1156
1157         #[test]
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,
1165                 });
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);
1169
1170                 scorer.payment_path_failed(&[], 42);
1171                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1172
1173                 SinceEpoch::advance(Duration::from_secs(10));
1174                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1175
1176                 scorer.payment_path_failed(&[], 42);
1177                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_768);
1178
1179                 SinceEpoch::advance(Duration::from_secs(10));
1180                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_384);
1181         }
1182
1183         #[test]
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,
1191                 });
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);
1195
1196                 scorer.payment_path_failed(&[], 42);
1197                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1198
1199                 SinceEpoch::advance(Duration::from_secs(10));
1200                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1201
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(),
1207                         fee_msat: 1,
1208                         cltv_expiry_delta: 18,
1209                 };
1210                 scorer.payment_path_successful(&[&hop]);
1211                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1212
1213                 SinceEpoch::advance(Duration::from_secs(10));
1214                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_064);
1215         }
1216
1217         #[test]
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,
1225                 });
1226                 let source = source_node_id();
1227                 let target = target_node_id();
1228
1229                 scorer.payment_path_failed(&[], 42);
1230                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1231
1232                 SinceEpoch::advance(Duration::from_secs(10));
1233                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_256);
1234
1235                 scorer.payment_path_failed(&[], 43);
1236                 assert_eq!(scorer.channel_penalty_msat(43, 1, 1, &source, &target), 1_512);
1237
1238                 let mut serialized_scorer = Vec::new();
1239                 scorer.write(&mut serialized_scorer).unwrap();
1240
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);
1244         }
1245
1246         #[test]
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,
1254                 });
1255                 let source = source_node_id();
1256                 let target = target_node_id();
1257
1258                 scorer.payment_path_failed(&[], 42);
1259                 assert_eq!(scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_512);
1260
1261                 let mut serialized_scorer = Vec::new();
1262                 scorer.write(&mut serialized_scorer).unwrap();
1263
1264                 SinceEpoch::advance(Duration::from_secs(10));
1265
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);
1268
1269                 SinceEpoch::advance(Duration::from_secs(10));
1270                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 1, 1, &source, &target), 1_128);
1271         }
1272
1273         #[test]
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,
1281                 });
1282                 let source = source_node_id();
1283                 let target = target_node_id();
1284
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);
1290         }
1291
1292         // `ProbabilisticScorer` tests
1293
1294         /// A probabilistic scorer for testing with time that can be manually advanced.
1295         type ProbabilisticScorer<'a> = ProbabilisticScorerUsingTime::<&'a NetworkGraph, SinceEpoch>;
1296
1297         fn sender_privkey() -> SecretKey {
1298                 SecretKey::from_slice(&[41; 32]).unwrap()
1299         }
1300
1301         fn recipient_privkey() -> SecretKey {
1302                 SecretKey::from_slice(&[45; 32]).unwrap()
1303         }
1304
1305         fn sender_pubkey() -> PublicKey {
1306                 let secp_ctx = Secp256k1::new();
1307                 PublicKey::from_secret_key(&secp_ctx, &sender_privkey())
1308         }
1309
1310         fn recipient_pubkey() -> PublicKey {
1311                 let secp_ctx = Secp256k1::new();
1312                 PublicKey::from_secret_key(&secp_ctx, &recipient_privkey())
1313         }
1314
1315         fn sender_node_id() -> NodeId {
1316                 NodeId::from_pubkey(&sender_pubkey())
1317         }
1318
1319         fn recipient_node_id() -> NodeId {
1320                 NodeId::from_pubkey(&recipient_pubkey())
1321         }
1322
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());
1328
1329                 network_graph
1330         }
1331
1332         fn add_channel(
1333                 network_graph: &mut NetworkGraph, short_channel_id: u64, node_1_key: SecretKey,
1334                 node_2_key: SecretKey
1335         ) {
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,
1343                         short_channel_id,
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(),
1349                 };
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,
1357                 };
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);
1363         }
1364
1365         fn update_channel(
1366                 network_graph: &mut NetworkGraph, short_channel_id: u64, node_key: SecretKey, flags: u8
1367         ) {
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,
1372                         short_channel_id,
1373                         timestamp: 100,
1374                         flags,
1375                         cltv_expiry_delta: 18,
1376                         htlc_minimum_msat: 0,
1377                         htlc_maximum_msat: OptionalField::Present(1_000),
1378                         fee_base_msat: 1,
1379                         fee_proportional_millionths: 0,
1380                         excess_data: Vec::new(),
1381                 };
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,
1386                 };
1387                 network_graph.update_channel(&signed_update, &secp_ctx).unwrap();
1388         }
1389
1390         fn payment_path_for_amount(amount_msat: u64) -> Vec<RouteHop> {
1391                 vec![
1392                         RouteHop {
1393                                 pubkey: source_pubkey(),
1394                                 node_features: NodeFeatures::known(),
1395                                 short_channel_id: 41,
1396                                 channel_features: ChannelFeatures::known(),
1397                                 fee_msat: 1,
1398                                 cltv_expiry_delta: 18,
1399                         },
1400                         RouteHop {
1401                                 pubkey: target_pubkey(),
1402                                 node_features: NodeFeatures::known(),
1403                                 short_channel_id: 42,
1404                                 channel_features: ChannelFeatures::known(),
1405                                 fee_msat: 2,
1406                                 cltv_expiry_delta: 18,
1407                         },
1408                         RouteHop {
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,
1415                         },
1416                 ]
1417         }
1418
1419         #[test]
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)
1425                         .with_channel(42,
1426                                 ChannelLiquidity {
1427                                         min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1428                                 })
1429                         .with_channel(43,
1430                                 ChannelLiquidity {
1431                                         min_liquidity_offset_msat: 700, max_liquidity_offset_msat: 100, last_updated
1432                                 });
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);
1438
1439                 // Update minimum liquidity.
1440
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);
1446
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);
1451
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);
1455
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);
1460
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);
1465
1466                 // Update maximum liquidity.
1467
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);
1472
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);
1477
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);
1481
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);
1486
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);
1491         }
1492
1493         #[test]
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)
1499                         .with_channel(42,
1500                                 ChannelLiquidity {
1501                                         min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1502                                 });
1503                 let source = source_node_id();
1504                 let target = target_node_id();
1505                 assert!(source > target);
1506
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);
1513
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);
1518
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);
1523
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);
1528
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);
1533
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);
1538
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);
1543
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);
1548         }
1549
1550         #[test]
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)
1556                         .with_channel(42,
1557                                 ChannelLiquidity {
1558                                         min_liquidity_offset_msat: 200, max_liquidity_offset_msat: 400, last_updated
1559                                 });
1560                 let source = source_node_id();
1561                 let target = target_node_id();
1562                 assert!(source > target);
1563
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);
1570
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);
1575
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);
1580
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);
1585
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);
1590
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);
1595
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);
1600
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);
1605         }
1606
1607         #[test]
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()
1612                 };
1613                 let scorer = ProbabilisticScorer::new(params, &network_graph);
1614                 let source = source_node_id();
1615                 let target = target_node_id();
1616
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);
1621
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);
1629         }
1630
1631         #[test]
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()
1637                 };
1638                 let scorer = ProbabilisticScorer::new(params, &network_graph)
1639                         .with_channel(42,
1640                                 ChannelLiquidity {
1641                                         min_liquidity_offset_msat: 40, max_liquidity_offset_msat: 40, last_updated
1642                                 });
1643                 let source = source_node_id();
1644                 let target = target_node_id();
1645
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);
1650         }
1651
1652         #[test]
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()
1657                 };
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);
1663
1664                 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1665
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);
1668
1669                 scorer.payment_path_successful(&successful_path.iter().collect::<Vec<_>>());
1670                 assert_eq!(scorer.channel_penalty_msat(41, 500, 1_000, &sender, &source), 300);
1671         }
1672
1673         #[test]
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()
1678                 };
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);
1683
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);
1687
1688                 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 43);
1689
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);
1693         }
1694
1695         #[test]
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()
1700                 };
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);
1705
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);
1709
1710                 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), 42);
1711
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);
1715         }
1716
1717         #[test]
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()
1722                 };
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);
1729
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);
1733
1734                 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
1735
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);
1739         }
1740
1741         #[test]
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),
1747                 };
1748                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1749                 let source = source_node_id();
1750                 let target = target_node_id();
1751
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);
1754
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);
1757
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);
1762
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);
1768
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);
1774
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);
1781
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);
1786
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);
1790         }
1791
1792         #[test]
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),
1798                 };
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);
1803
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);
1806
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);
1811
1812                 SinceEpoch::advance(Duration::from_secs(10));
1813                 assert_eq!(scorer.channel_penalty_msat(42, 256, 1_024, &source, &target), 124);
1814         }
1815
1816         #[test]
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),
1822                 };
1823                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1824                 let source = source_node_id();
1825                 let target = target_node_id();
1826
1827                 assert_eq!(scorer.channel_penalty_msat(42, 512, 1_024, &source, &target), 300);
1828
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);
1833
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);
1837
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);
1842
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);
1847
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);
1851         }
1852
1853         #[test]
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),
1859                 };
1860                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1861                 let source = source_node_id();
1862                 let target = target_node_id();
1863
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);
1866
1867                 SinceEpoch::advance(Duration::from_secs(10));
1868                 assert_eq!(scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 475);
1869
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);
1872
1873                 let mut serialized_scorer = Vec::new();
1874                 scorer.write(&mut serialized_scorer).unwrap();
1875
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);
1880         }
1881
1882         #[test]
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),
1888                 };
1889                 let mut scorer = ProbabilisticScorer::new(params, &network_graph);
1890                 let source = source_node_id();
1891                 let target = target_node_id();
1892
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);
1895
1896                 let mut serialized_scorer = Vec::new();
1897                 scorer.write(&mut serialized_scorer).unwrap();
1898
1899                 SinceEpoch::advance(Duration::from_secs(10));
1900
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);
1905
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);
1908
1909                 SinceEpoch::advance(Duration::from_secs(10));
1910                 assert_eq!(deserialized_scorer.channel_penalty_msat(42, 500, 1_000, &source, &target), 367);
1911         }
1912 }