Clarify Scorer docs around penalizing channels
[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 #[cfg(not(feature = "no-std"))]
56 use core::time::Duration;
57 #[cfg(not(feature = "no-std"))]
58 use std::time::Instant;
59
60 /// [`routing::Score`] implementation that provides reasonable default behavior.
61 ///
62 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
63 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
64 ///
65 /// See [module-level documentation] for usage.
66 ///
67 /// [module-level documentation]: crate::routing::scorer
68 pub struct Scorer {
69         params: ScoringParameters,
70         #[cfg(not(feature = "no-std"))]
71         channel_failures: HashMap<u64, (u64, Instant)>,
72         #[cfg(feature = "no-std")]
73         channel_failures: HashMap<u64, u64>,
74 }
75
76 /// Parameters for configuring [`Scorer`].
77 pub struct ScoringParameters {
78         /// A fixed penalty in msats to apply to each channel.
79         pub base_penalty_msat: u64,
80
81         /// A penalty in msats to apply to a channel upon failure.
82         ///
83         /// This may be reduced over time based on [`failure_penalty_half_life`].
84         ///
85         /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
86         pub failure_penalty_msat: u64,
87
88         /// The time needed before any accumulated channel failure penalties are cut in half.
89         #[cfg(not(feature = "no-std"))]
90         pub failure_penalty_half_life: Duration,
91 }
92
93 impl Scorer {
94         /// Creates a new scorer using the given scoring parameters.
95         pub fn new(params: ScoringParameters) -> Self {
96                 Self {
97                         params,
98                         channel_failures: HashMap::new(),
99                 }
100         }
101
102         /// Creates a new scorer using `penalty_msat` as a fixed channel penalty.
103         #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
104         pub fn with_fixed_penalty(penalty_msat: u64) -> Self {
105                 Self::new(ScoringParameters {
106                         base_penalty_msat: penalty_msat,
107                         failure_penalty_msat: 0,
108                         #[cfg(not(feature = "no-std"))]
109                         failure_penalty_half_life: Duration::from_secs(0),
110                 })
111         }
112
113         #[cfg(not(feature = "no-std"))]
114         fn decay_from(&self, penalty_msat: u64, last_failure: &Instant) -> u64 {
115                 decay_from(penalty_msat, last_failure, self.params.failure_penalty_half_life)
116         }
117 }
118
119 impl Default for Scorer {
120         fn default() -> Self {
121                 Scorer::new(ScoringParameters::default())
122         }
123 }
124
125 impl Default for ScoringParameters {
126         fn default() -> Self {
127                 Self {
128                         base_penalty_msat: 500,
129                         failure_penalty_msat: 1024 * 1000,
130                         #[cfg(not(feature = "no-std"))]
131                         failure_penalty_half_life: Duration::from_secs(3600),
132                 }
133         }
134 }
135
136 impl routing::Score for Scorer {
137         fn channel_penalty_msat(
138                 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId
139         ) -> u64 {
140                 #[cfg(not(feature = "no-std"))]
141                 let failure_penalty_msat = match self.channel_failures.get(&short_channel_id) {
142                         Some((penalty_msat, last_failure)) => self.decay_from(*penalty_msat, last_failure),
143                         None => 0,
144                 };
145                 #[cfg(feature = "no-std")]
146                 let failure_penalty_msat =
147                         self.channel_failures.get(&short_channel_id).copied().unwrap_or(0);
148
149                 self.params.base_penalty_msat + failure_penalty_msat
150         }
151
152         fn payment_path_failed(&mut self, _path: &Vec<RouteHop>, short_channel_id: u64) {
153                 let failure_penalty_msat = self.params.failure_penalty_msat;
154                 #[cfg(not(feature = "no-std"))]
155                 {
156                         let half_life = self.params.failure_penalty_half_life;
157                         self.channel_failures
158                                 .entry(short_channel_id)
159                                 .and_modify(|(penalty_msat, last_failure)| {
160                                         let decayed_penalty = decay_from(*penalty_msat, last_failure, half_life);
161                                         *penalty_msat = decayed_penalty + failure_penalty_msat;
162                                         *last_failure = Instant::now();
163                                 })
164                                 .or_insert_with(|| (failure_penalty_msat, Instant::now()));
165                 }
166                 #[cfg(feature = "no-std")]
167                 self.channel_failures
168                         .entry(short_channel_id)
169                         .and_modify(|penalty_msat| *penalty_msat += failure_penalty_msat)
170                         .or_insert(failure_penalty_msat);
171         }
172 }
173
174 #[cfg(not(feature = "no-std"))]
175 fn decay_from(penalty_msat: u64, last_failure: &Instant, half_life: Duration) -> u64 {
176         let decays = last_failure.elapsed().as_secs().checked_div(half_life.as_secs());
177         match decays {
178                 Some(decays) => penalty_msat >> decays,
179                 None => 0,
180         }
181 }