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;
56 #[cfg(not(feature = "no-std"))]
57 use std::time::Instant;
59 /// [`routing::Score`] implementation that provides reasonable default behavior.
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.
64 /// See [module-level documentation] for usage.
66 /// [module-level documentation]: crate::routing::scorer
68 params: ScoringParameters,
69 // TODO: Remove entries of closed channels.
70 channel_failures: HashMap<u64, ChannelFailure>,
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,
78 /// A penalty in msats to apply to a channel upon failing to relay a payment.
80 /// This accumulates for each failure but may be reduced over time based on
81 /// [`failure_penalty_half_life`].
83 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
84 pub failure_penalty_msat: u64,
86 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
89 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
90 pub failure_penalty_half_life: Duration,
93 /// Accounting for penalties against a channel for failing to relay any payments.
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,
100 /// Last time the channel failed. Used to decay `undecayed_penalty_msat`.
101 #[cfg(not(feature = "no-std"))]
102 last_failed: Instant,
106 /// Creates a new scorer using the given scoring parameters.
107 pub fn new(params: ScoringParameters) -> Self {
110 channel_failures: HashMap::new(),
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),
125 impl ChannelFailure {
126 fn new(failure_penalty_msat: u64) -> Self {
128 undecayed_penalty_msat: failure_penalty_msat,
129 #[cfg(not(feature = "no-std"))]
130 last_failed: Instant::now(),
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"))]
138 self.last_failed = Instant::now();
142 fn decayed_penalty_msat(&self, half_life: Duration) -> u64 {
143 let decays = self.elapsed().as_secs().checked_div(half_life.as_secs());
145 Some(decays) => self.undecayed_penalty_msat >> decays,
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);
158 impl Default for Scorer {
159 fn default() -> Self {
160 Scorer::new(ScoringParameters::default())
164 impl Default for ScoringParameters {
165 fn default() -> Self {
167 base_penalty_msat: 500,
168 failure_penalty_msat: 1024 * 1000,
169 failure_penalty_half_life: Duration::from_secs(3600),
174 impl routing::Score for Scorer {
175 fn channel_penalty_msat(
176 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId
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));
182 self.params.base_penalty_msat + failure_penalty_msat
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));