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