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);
49 //! If persisting [`Scorer`], it must be restored using the same [`Time`] parameterization. Using a
50 //! different type results in undefined behavior. Specifically, persisting when built with feature
51 //! `no-std` and restoring without it, or vice versa, uses different types and thus is undefined.
53 //! [`find_route`]: crate::routing::router::find_route
57 use ln::msgs::DecodeError;
58 use routing::network_graph::NodeId;
59 use routing::router::RouteHop;
60 use util::ser::{Readable, Writeable, Writer};
64 use core::time::Duration;
67 /// [`routing::Score`] implementation that provides reasonable default behavior.
69 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
70 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
72 /// See [module-level documentation] for usage.
74 /// [module-level documentation]: crate::routing::scorer
75 pub type Scorer = ScorerUsingTime::<DefaultTime>;
77 /// Time used by [`Scorer`].
78 #[cfg(not(feature = "no-std"))]
79 pub type DefaultTime = std::time::Instant;
81 /// Time used by [`Scorer`].
82 #[cfg(feature = "no-std")]
83 pub type DefaultTime = Eternity;
85 /// [`routing::Score`] implementation parameterized by [`Time`].
87 /// See [`Scorer`] for details.
91 /// Mixing [`Time`] types between serialization and deserialization results in undefined behavior.
92 pub struct ScorerUsingTime<T: Time> {
93 params: ScoringParameters,
94 // TODO: Remove entries of closed channels.
95 channel_failures: HashMap<u64, ChannelFailure<T>>,
98 /// Parameters for configuring [`Scorer`].
99 pub struct ScoringParameters {
100 /// A fixed penalty in msats to apply to each channel.
101 pub base_penalty_msat: u64,
103 /// A penalty in msats to apply to a channel upon failing to relay a payment.
105 /// This accumulates for each failure but may be reduced over time based on
106 /// [`failure_penalty_half_life`].
108 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
109 pub failure_penalty_msat: u64,
111 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
116 /// When time is an [`Eternity`], as is default when enabling feature `no-std`, it will never
117 /// elapse. Therefore, this penalty will never decay.
119 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
120 pub failure_penalty_half_life: Duration,
123 impl_writeable_tlv_based!(ScoringParameters, {
124 (0, base_penalty_msat, required),
125 (2, failure_penalty_msat, required),
126 (4, failure_penalty_half_life, required),
129 /// Accounting for penalties against a channel for failing to relay any payments.
131 /// Penalties decay over time, though accumulate as more failures occur.
132 struct ChannelFailure<T: Time> {
133 /// Accumulated penalty in msats for the channel as of `last_failed`.
134 undecayed_penalty_msat: u64,
136 /// Last time the channel failed. Used to decay `undecayed_penalty_msat`.
140 /// A measurement of time.
141 pub trait Time: Sub<Duration, Output = Self> where Self: Sized {
142 /// Returns an instance corresponding to the current moment.
145 /// Returns the amount of time elapsed since `self` was created.
146 fn elapsed(&self) -> Duration;
148 /// Returns the amount of time passed since the beginning of [`Time`].
150 /// Used during (de-)serialization.
151 fn duration_since_epoch() -> Duration;
154 impl<T: Time> ScorerUsingTime<T> {
155 /// Creates a new scorer using the given scoring parameters.
156 pub fn new(params: ScoringParameters) -> Self {
159 channel_failures: HashMap::new(),
163 /// Creates a new scorer using `penalty_msat` as a fixed channel penalty.
164 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
165 pub fn with_fixed_penalty(penalty_msat: u64) -> Self {
166 Self::new(ScoringParameters {
167 base_penalty_msat: penalty_msat,
168 failure_penalty_msat: 0,
169 failure_penalty_half_life: Duration::from_secs(0),
174 impl<T: Time> ChannelFailure<T> {
175 fn new(failure_penalty_msat: u64) -> Self {
177 undecayed_penalty_msat: failure_penalty_msat,
178 last_failed: T::now(),
182 fn add_penalty(&mut self, failure_penalty_msat: u64, half_life: Duration) {
183 self.undecayed_penalty_msat = self.decayed_penalty_msat(half_life) + failure_penalty_msat;
184 self.last_failed = T::now();
187 fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
188 let decays = self.last_failed.elapsed().as_secs().checked_div(half_life.as_secs());
190 Some(decays) => self.undecayed_penalty_msat >> decays,
196 impl<T: Time> Default for ScorerUsingTime<T> {
197 fn default() -> Self {
198 Self::new(ScoringParameters::default())
202 impl Default for ScoringParameters {
203 fn default() -> Self {
205 base_penalty_msat: 500,
206 failure_penalty_msat: 1024 * 1000,
207 failure_penalty_half_life: Duration::from_secs(3600),
212 impl<T: Time> routing::Score for ScorerUsingTime<T> {
213 fn channel_penalty_msat(
214 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId
216 let failure_penalty_msat = self.channel_failures
217 .get(&short_channel_id)
218 .map_or(0, |value| value.decayed_penalty_msat(self.params.failure_penalty_half_life));
220 self.params.base_penalty_msat + failure_penalty_msat
223 fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
224 let failure_penalty_msat = self.params.failure_penalty_msat;
225 let half_life = self.params.failure_penalty_half_life;
226 self.channel_failures
227 .entry(short_channel_id)
228 .and_modify(|failure| failure.add_penalty(failure_penalty_msat, half_life))
229 .or_insert_with(|| ChannelFailure::new(failure_penalty_msat));
233 #[cfg(not(feature = "no-std"))]
234 impl Time for std::time::Instant {
236 std::time::Instant::now()
239 fn duration_since_epoch() -> Duration {
240 use std::time::SystemTime;
241 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
244 fn elapsed(&self) -> Duration {
245 std::time::Instant::elapsed(self)
249 /// A state in which time has no meaning.
252 impl Time for Eternity {
257 fn duration_since_epoch() -> Duration {
258 Duration::from_secs(0)
261 fn elapsed(&self) -> Duration {
262 Duration::from_secs(0)
266 impl Sub<Duration> for Eternity {
269 fn sub(self, _other: Duration) -> Self {
274 impl<T: Time> Writeable for ScorerUsingTime<T> {
276 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
277 self.params.write(w)?;
278 self.channel_failures.write(w)
282 impl<T: Time> Readable for ScorerUsingTime<T> {
284 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
286 params: Readable::read(r)?,
287 channel_failures: Readable::read(r)?,
292 impl<T: Time> Writeable for ChannelFailure<T> {
294 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
295 self.undecayed_penalty_msat.write(w)?;
296 (T::duration_since_epoch() - self.last_failed.elapsed()).write(w)
300 impl<T: Time> Readable for ChannelFailure<T> {
302 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
304 undecayed_penalty_msat: Readable::read(r)?,
305 last_failed: T::now() - (T::duration_since_epoch() - Readable::read(r)?),