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 #[cfg(not(feature = "no-std"))]
56 use core::time::Duration;
57 #[cfg(not(feature = "no-std"))]
58 use std::time::Instant;
60 /// [`routing::Score`] implementation that provides reasonable default behavior.
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.
65 /// See [module-level documentation] for usage.
67 /// [module-level documentation]: crate::routing::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>,
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,
81 /// A penalty in msats to apply to a channel upon failure.
83 /// This may be reduced over time based on [`failure_penalty_half_life`].
85 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
86 pub failure_penalty_msat: u64,
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,
94 /// Creates a new scorer using the given scoring parameters.
95 pub fn new(params: ScoringParameters) -> Self {
98 channel_failures: HashMap::new(),
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),
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)
119 impl Default for Scorer {
120 fn default() -> Self {
121 Scorer::new(ScoringParameters::default())
125 impl Default for ScoringParameters {
126 fn default() -> 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),
136 impl routing::Score for Scorer {
137 fn channel_penalty_msat(
138 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId
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),
145 #[cfg(feature = "no-std")]
146 let failure_penalty_msat =
147 self.channel_failures.get(&short_channel_id).copied().unwrap_or(0);
149 self.params.base_penalty_msat + failure_penalty_msat
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"))]
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();
164 .or_insert_with(|| (failure_penalty_msat, Instant::now()));
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);
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());
178 Some(decays) => penalty_msat >> decays,