1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Utilities for scoring payment channels.
12 //! [`Scorer`] may be given to [`find_route`] to score payment channels during path finding when a
13 //! custom [`routing::Score`] implementation is not needed.
18 //! # extern crate secp256k1;
20 //! # use lightning::routing::network_graph::NetworkGraph;
21 //! # use lightning::routing::router::{RouteParameters, find_route};
22 //! # use lightning::routing::scorer::{Scorer, ScoringParameters};
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use secp256k1::key::PublicKey;
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! # fn log(&self, record: &Record) { unimplemented!() }
30 //! # fn find_scored_route(payer: PublicKey, params: RouteParameters, network_graph: NetworkGraph) {
31 //! # let logger = FakeLogger {};
33 //! // Use the default channel penalties.
34 //! let scorer = Scorer::default();
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()
43 //! let route = find_route(&payer, ¶ms, &network_graph, None, &logger, &scorer);
47 //! [`find_route`]: crate::routing::router::find_route
51 use routing::network_graph::NodeId;
52 use routing::router::RouteHop;
55 use core::time::Duration;
57 /// [`routing::Score`] implementation that provides reasonable default behavior.
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.
62 /// See [module-level documentation] for usage.
64 /// [module-level documentation]: crate::routing::scorer
65 pub type Scorer = ScorerUsingTime::<DefaultTime>;
67 /// Time used by [`Scorer`].
68 #[cfg(not(feature = "no-std"))]
69 pub type DefaultTime = std::time::Instant;
71 /// Time used by [`Scorer`].
72 #[cfg(feature = "no-std")]
73 pub type DefaultTime = Eternity;
75 /// [`routing::Score`] implementation parameterized by [`Time`].
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>>,
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,
89 /// A penalty in msats to apply to a channel upon failing to relay a payment.
91 /// This accumulates for each failure but may be reduced over time based on
92 /// [`failure_penalty_half_life`].
94 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
95 pub failure_penalty_msat: u64,
97 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
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.
105 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
106 pub failure_penalty_half_life: Duration,
109 /// Accounting for penalties against a channel for failing to relay any payments.
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,
116 /// Last time the channel failed. Used to decay `undecayed_penalty_msat`.
120 /// A measurement of time.
122 /// Returns an instance corresponding to the current moment.
125 /// Returns the amount of time elapsed since `self` was created.
126 fn elapsed(&self) -> Duration;
129 impl<T: Time> ScorerUsingTime<T> {
130 /// Creates a new scorer using the given scoring parameters.
131 pub fn new(params: ScoringParameters) -> Self {
134 channel_failures: HashMap::new(),
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),
149 impl<T: Time> ChannelFailure<T> {
150 fn new(failure_penalty_msat: u64) -> Self {
152 undecayed_penalty_msat: failure_penalty_msat,
153 last_failed: T::now(),
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();
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());
165 Some(decays) => self.undecayed_penalty_msat >> decays,
171 impl<T: Time> Default for ScorerUsingTime<T> {
172 fn default() -> Self {
173 Self::new(ScoringParameters::default())
177 impl Default for ScoringParameters {
178 fn default() -> Self {
180 base_penalty_msat: 500,
181 failure_penalty_msat: 1024 * 1000,
182 failure_penalty_half_life: Duration::from_secs(3600),
187 impl<T: Time> routing::Score for ScorerUsingTime<T> {
188 fn channel_penalty_msat(
189 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId
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));
195 self.params.base_penalty_msat + failure_penalty_msat
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));
208 #[cfg(not(feature = "no-std"))]
209 impl Time for std::time::Instant {
211 std::time::Instant::now()
214 fn elapsed(&self) -> Duration {
215 std::time::Instant::elapsed(self)
219 /// A state in which time has no meaning.
222 impl Time for Eternity {
227 fn elapsed(&self) -> Duration {
228 Duration::from_secs(0)