Parameterize Scorer by a Time trait
[rust-lightning] / lightning / src / routing / scorer.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 //! [`Scorer`] may be given to [`find_route`] to score payment channels during path finding when a
13 //! custom [`routing::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::scorer::{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, params: RouteParameters, network_graph: NetworkGraph) {
31 //! # let logger = FakeLogger {};
32 //! #
33 //! // Use the default channel penalties.
34 //! let scorer = Scorer::default();
35 //!
36 //! // Or use custom channel penalties.
37 //! let scorer = Scorer::new(ScoringParameters {
38 //!     base_penalty_msat: 1000,
39 //!     failure_penalty_msat: 2 * 1024 * 1000,
40 //!     ..ScoringParameters::default()
41 //! });
42 //!
43 //! let route = find_route(&payer, &params, &network_graph, None, &logger, &scorer);
44 //! # }
45 //! ```
46 //!
47 //! [`find_route`]: crate::routing::router::find_route
48
49 use routing;
50
51 use routing::network_graph::NodeId;
52 use routing::router::RouteHop;
53
54 use prelude::*;
55 use core::time::Duration;
56
57 /// [`routing::Score`] implementation that provides reasonable default behavior.
58 ///
59 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
60 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
61 ///
62 /// See [module-level documentation] for usage.
63 ///
64 /// [module-level documentation]: crate::routing::scorer
65 pub type Scorer = ScorerUsingTime::<DefaultTime>;
66
67 /// Time used by [`Scorer`].
68 #[cfg(not(feature = "no-std"))]
69 pub type DefaultTime = std::time::Instant;
70
71 /// Time used by [`Scorer`].
72 #[cfg(feature = "no-std")]
73 pub type DefaultTime = Eternity;
74
75 /// [`routing::Score`] implementation parameterized by [`Time`].
76 ///
77 /// See [`Scorer`] for details.
78 pub struct ScorerUsingTime<T: Time> {
79         params: ScoringParameters,
80         // TODO: Remove entries of closed channels.
81         channel_failures: HashMap<u64, ChannelFailure<T>>,
82 }
83
84 /// Parameters for configuring [`Scorer`].
85 pub struct ScoringParameters {
86         /// A fixed penalty in msats to apply to each channel.
87         pub base_penalty_msat: u64,
88
89         /// A penalty in msats to apply to a channel upon failing to relay a payment.
90         ///
91         /// This accumulates for each failure but may be reduced over time based on
92         /// [`failure_penalty_half_life`].
93         ///
94         /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
95         pub failure_penalty_msat: u64,
96
97         /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
98         /// cut in half.
99         ///
100         /// # Note
101         ///
102         /// When time is an [`Eternity`], as is default when enabling feature `no-std`, it will never
103         /// elapse. Therefore, this penalty will never decay.
104         ///
105         /// [`failure_penalty_msat`]: Self::failure_penalty_msat
106         pub failure_penalty_half_life: Duration,
107 }
108
109 /// Accounting for penalties against a channel for failing to relay any payments.
110 ///
111 /// Penalties decay over time, though accumulate as more failures occur.
112 struct ChannelFailure<T: Time> {
113         /// Accumulated penalty in msats for the channel as of `last_failed`.
114         undecayed_penalty_msat: u64,
115
116         /// Last time the channel failed. Used to decay `undecayed_penalty_msat`.
117         last_failed: T,
118 }
119
120 /// A measurement of time.
121 pub trait Time {
122         /// Returns an instance corresponding to the current moment.
123         fn now() -> Self;
124
125         /// Returns the amount of time elapsed since `self` was created.
126         fn elapsed(&self) -> Duration;
127 }
128
129 impl<T: Time> ScorerUsingTime<T> {
130         /// Creates a new scorer using the given scoring parameters.
131         pub fn new(params: ScoringParameters) -> Self {
132                 Self {
133                         params,
134                         channel_failures: HashMap::new(),
135                 }
136         }
137
138         /// Creates a new scorer using `penalty_msat` as a fixed channel penalty.
139         #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
140         pub fn with_fixed_penalty(penalty_msat: u64) -> Self {
141                 Self::new(ScoringParameters {
142                         base_penalty_msat: penalty_msat,
143                         failure_penalty_msat: 0,
144                         failure_penalty_half_life: Duration::from_secs(0),
145                 })
146         }
147 }
148
149 impl<T: Time> ChannelFailure<T> {
150         fn new(failure_penalty_msat: u64) -> Self {
151                 Self {
152                         undecayed_penalty_msat: failure_penalty_msat,
153                         last_failed: T::now(),
154                 }
155         }
156
157         fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
158                 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
159                 self.last_failed = T::now();
160         }
161
162         fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
163                 let decays = self.last_failed.elapsed().as_secs().checked_div(half_life.as_secs());
164                 match decays {
165                         Some(decays) => self.undecayed_penalty_msat >> decays,
166                         None => 0,
167                 }
168         }
169 }
170
171 impl<T: Time> Default for ScorerUsingTime<T> {
172         fn default() -> Self {
173                 Self::new(ScoringParameters::default())
174         }
175 }
176
177 impl Default for ScoringParameters {
178         fn default() -> Self {
179                 Self {
180                         base_penalty_msat: 500,
181                         failure_penalty_msat: 1024 * 1000,
182                         failure_penalty_half_life: Duration::from_secs(3600),
183                 }
184         }
185 }
186
187 impl<T: Time> routing::Score for ScorerUsingTime<T> {
188         fn channel_penalty_msat(
189                 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId
190         ) -> u64 {
191                 let failure_penalty_msat = self.channel_failures
192                         .get(&short_channel_id)
193                         .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
194
195                 self.params.base_penalty_msat + failure_penalty_msat
196         }
197
198         fn payment_path_failed(&mut self, _path: &Vec<RouteHop>, short_channel_id: u64) {
199                 let failure_penalty_msat = self.params.failure_penalty_msat;
200                 let half_life = self.params.failure_penalty_half_life;
201                 self.channel_failures
202                         .entry(short_channel_id)
203                         .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
204                         .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
205         }
206 }
207
208 #[cfg(not(feature = "no-std"))]
209 impl Time for std::time::Instant {
210         fn now() -> Self {
211                 std::time::Instant::now()
212         }
213
214         fn elapsed(&self) -> Duration {
215                 std::time::Instant::elapsed(self)
216         }
217 }
218
219 /// A state in which time has no meaning.
220 pub struct Eternity;
221
222 impl Time for Eternity {
223         fn now() -> Self {
224                 Self
225         }
226
227         fn elapsed(&self) -> Duration {
228                 Duration::from_secs(0)
229         }
230 }