Skip to content

Commit 8e2f176

Browse files
committed
Move Score into a scoring module instead of a top-level module
Traits in top-level modules is somewhat confusing - generally top-level modules are just organizational modules and don't contain things themselves, instead placing traits and structs in sub-modules. Further, its incredibly awkward to have a `scorer` sub-module, but only have a single struct in it, with the relevant trait it is the only implementation of somewhere else. Not having `Score` in the `scorer` sub-module is further confusing because it's the only module anywhere that references scoring at all.
1 parent dea3029 commit 8e2f176

File tree

7 files changed

+96
-104
lines changed

7 files changed

+96
-104
lines changed

fuzz/src/router.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use lightning::ln::channelmanager::{ChannelDetails, ChannelCounterparty};
1717
use lightning::ln::features::InitFeatures;
1818
use lightning::ln::msgs;
1919
use lightning::routing::router::{find_route, Payee, RouteHint, RouteHintHop, RouteParameters};
20-
use lightning::routing::scorer::Scorer;
20+
use lightning::routing::scoring::Scorer;
2121
use lightning::util::logger::Logger;
2222
use lightning::util::ser::Readable;
2323
use lightning::routing::network_graph::{NetworkGraph, RoutingFees};

lightning-invoice/src/payment.rs

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
//! # use lightning::ln::{PaymentHash, PaymentSecret};
3131
//! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
3232
//! # use lightning::ln::msgs::LightningError;
33-
//! # use lightning::routing;
33+
//! # use lightning::routing::scoring::Score;
3434
//! # use lightning::routing::network_graph::NodeId;
3535
//! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
3636
//! # use lightning::util::events::{Event, EventHandler, EventsProvider};
@@ -59,15 +59,15 @@
5959
//! # }
6060
//! #
6161
//! # struct FakeRouter {};
62-
//! # impl<S: routing::Score> Router<S> for FakeRouter {
62+
//! # impl<S: Score> Router<S> for FakeRouter {
6363
//! # fn find_route(
6464
//! # &self, payer: &PublicKey, params: &RouteParameters,
6565
//! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
6666
//! # ) -> Result<Route, LightningError> { unimplemented!() }
6767
//! # }
6868
//! #
6969
//! # struct FakeScorer {};
70-
//! # impl routing::Score for FakeScorer {
70+
//! # impl Score for FakeScorer {
7171
//! # fn channel_penalty_msat(
7272
//! # &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId
7373
//! # ) -> u64 { 0 }
@@ -117,8 +117,7 @@ use bitcoin_hashes::Hash;
117117
use lightning::ln::{PaymentHash, PaymentSecret};
118118
use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
119119
use lightning::ln::msgs::LightningError;
120-
use lightning::routing;
121-
use lightning::routing::{LockableScore, Score};
120+
use lightning::routing::scoring::{LockableScore, Score};
122121
use lightning::routing::router::{Payee, Route, RouteParameters};
123122
use lightning::util::events::{Event, EventHandler};
124123
use lightning::util::logger::Logger;
@@ -134,8 +133,8 @@ use std::time::{Duration, SystemTime};
134133
pub struct InvoicePayer<P: Deref, R, S: Deref, L: Deref, E>
135134
where
136135
P::Target: Payer,
137-
R: for <'a> Router<<<S as Deref>::Target as routing::LockableScore<'a>>::Locked>,
138-
S::Target: for <'a> routing::LockableScore<'a>,
136+
R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
137+
S::Target: for <'a> LockableScore<'a>,
139138
L::Target: Logger,
140139
E: EventHandler,
141140
{
@@ -166,7 +165,7 @@ pub trait Payer {
166165
}
167166

168167
/// A trait defining behavior for routing an [`Invoice`] payment.
169-
pub trait Router<S: routing::Score> {
168+
pub trait Router<S: Score> {
170169
/// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
171170
fn find_route(
172171
&self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
@@ -196,8 +195,8 @@ pub enum PaymentError {
196195
impl<P: Deref, R, S: Deref, L: Deref, E> InvoicePayer<P, R, S, L, E>
197196
where
198197
P::Target: Payer,
199-
R: for <'a> Router<<<S as Deref>::Target as routing::LockableScore<'a>>::Locked>,
200-
S::Target: for <'a> routing::LockableScore<'a>,
198+
R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
199+
S::Target: for <'a> LockableScore<'a>,
201200
L::Target: Logger,
202201
E: EventHandler,
203202
{
@@ -404,8 +403,8 @@ fn has_expired(params: &RouteParameters) -> bool {
404403
impl<P: Deref, R, S: Deref, L: Deref, E> EventHandler for InvoicePayer<P, R, S, L, E>
405404
where
406405
P::Target: Payer,
407-
R: for <'a> Router<<<S as Deref>::Target as routing::LockableScore<'a>>::Locked>,
408-
S::Target: for <'a> routing::LockableScore<'a>,
406+
R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
407+
S::Target: for <'a> LockableScore<'a>,
409408
L::Target: Logger,
410409
E: EventHandler,
411410
{
@@ -1050,7 +1049,7 @@ mod tests {
10501049
}
10511050
}
10521051

1053-
impl<S: routing::Score> Router<S> for TestRouter {
1052+
impl<S: Score> Router<S> for TestRouter {
10541053
fn find_route(
10551054
&self,
10561055
_payer: &PublicKey,
@@ -1066,7 +1065,7 @@ mod tests {
10661065

10671066
struct FailingRouter;
10681067

1069-
impl<S: routing::Score> Router<S> for FailingRouter {
1068+
impl<S: Score> Router<S> for FailingRouter {
10701069
fn find_route(
10711070
&self,
10721071
_payer: &PublicKey,
@@ -1095,7 +1094,7 @@ mod tests {
10951094
}
10961095
}
10971096

1098-
impl routing::Score for TestScorer {
1097+
impl Score for TestScorer {
10991098
fn channel_penalty_msat(
11001099
&self, _short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId
11011100
) -> u64 { 0 }
@@ -1217,7 +1216,7 @@ mod tests {
12171216
// *** Full Featured Functional Tests with a Real ChannelManager ***
12181217
struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
12191218

1220-
impl<S: routing::Score> Router<S> for ManualRouter {
1219+
impl<S: Score> Router<S> for ManualRouter {
12211220
fn find_route(&self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>, _scorer: &S)
12221221
-> Result<Route, LightningError> {
12231222
self.0.borrow_mut().pop_front().unwrap()

lightning-invoice/src/utils.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use lightning::chain::keysinterface::{Sign, KeysInterface};
1111
use lightning::ln::{PaymentHash, PaymentSecret};
1212
use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY};
1313
use lightning::ln::msgs::LightningError;
14-
use lightning::routing;
14+
use lightning::routing::scoring::Score;
1515
use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
1616
use lightning::routing::router::{Route, RouteHint, RouteHintHop, RouteParameters, find_route};
1717
use lightning::util::logger::Logger;
@@ -109,7 +109,7 @@ impl<G, L: Deref> DefaultRouter<G, L> where G: Deref<Target = NetworkGraph>, L::
109109
}
110110
}
111111

112-
impl<G, L: Deref, S: routing::Score> Router<S> for DefaultRouter<G, L>
112+
impl<G, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
113113
where G: Deref<Target = NetworkGraph>, L::Target: Logger {
114114
fn find_route(
115115
&self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,

lightning/src/routing/mod.rs

Lines changed: 1 addition & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -11,72 +11,4 @@
1111
1212
pub mod network_graph;
1313
pub mod router;
14-
pub mod scorer;
15-
16-
use routing::network_graph::NodeId;
17-
use routing::router::RouteHop;
18-
19-
use core::cell::{RefCell, RefMut};
20-
use core::ops::DerefMut;
21-
use sync::{Mutex, MutexGuard};
22-
23-
/// An interface used to score payment channels for path finding.
24-
///
25-
/// Scoring is in terms of fees willing to be paid in order to avoid routing through a channel.
26-
pub trait Score {
27-
/// Returns the fee in msats willing to be paid to avoid routing through the given channel
28-
/// in the direction from `source` to `target`.
29-
///
30-
/// The maximum amount which may be in the HTLC at the given channel is given by
31-
/// `send_amt_sat`.
32-
///
33-
/// The channel's capacity in satoshis (given other HTLCs to be sent) is given by
34-
/// `channel_capacity_sats`. It may be guessed from various sources or assumed from no data.
35-
/// Your code should be overflow-safe through a `channel_capacity_sats` of 21 million BTC.
36-
fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, channel_capacity_sat: u64, source: &NodeId, target: &NodeId) -> u64;
37-
38-
/// Handles updating channel penalties after failing to route through a channel.
39-
fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64);
40-
}
41-
42-
/// A scorer that is accessed under a lock.
43-
///
44-
/// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
45-
/// having shared ownership of a scorer but without requiring internal locking in [`Score`]
46-
/// implementations. Internal locking would be detrimental to route finding performance and could
47-
/// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
48-
///
49-
/// [`find_route`]: crate::routing::router::find_route
50-
pub trait LockableScore<'a> {
51-
/// The locked [`Score`] type.
52-
type Locked: 'a + Score;
53-
54-
/// Returns the locked scorer.
55-
fn lock(&'a self) -> Self::Locked;
56-
}
57-
58-
impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
59-
type Locked = MutexGuard<'a, T>;
60-
61-
fn lock(&'a self) -> MutexGuard<'a, T> {
62-
Mutex::lock(self).unwrap()
63-
}
64-
}
65-
66-
impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
67-
type Locked = RefMut<'a, T>;
68-
69-
fn lock(&'a self) -> RefMut<'a, T> {
70-
self.borrow_mut()
71-
}
72-
}
73-
74-
impl<S: Score, T: DerefMut<Target=S>> Score for T {
75-
fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, channel_capacity_sat: u64, source: &NodeId, target: &NodeId) -> u64 {
76-
self.deref().channel_penalty_msat(short_channel_id, send_amt_msat, channel_capacity_sat, source, target)
77-
}
78-
79-
fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
80-
self.deref_mut().payment_path_failed(path, short_channel_id)
81-
}
82-
}
14+
pub mod scoring;

lightning/src/routing/router.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use bitcoin::secp256k1::key::PublicKey;
1717
use ln::channelmanager::ChannelDetails;
1818
use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
1919
use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20-
use routing;
20+
use routing::scoring::Score;
2121
use routing::network_graph::{NetworkGraph, NodeId, RoutingFees};
2222
use util::ser::{Writeable, Readable};
2323
use util::logger::{Level, Logger};
@@ -529,7 +529,7 @@ fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
529529
///
530530
/// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
531531
/// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
532-
pub fn find_route<L: Deref, S: routing::Score>(
532+
pub fn find_route<L: Deref, S: Score>(
533533
our_node_pubkey: &PublicKey, params: &RouteParameters, network: &NetworkGraph,
534534
first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
535535
) -> Result<Route, LightningError>
@@ -540,7 +540,7 @@ where L::Target: Logger {
540540
)
541541
}
542542

543-
pub(crate) fn get_route<L: Deref, S: routing::Score>(
543+
pub(crate) fn get_route<L: Deref, S: Score>(
544544
our_node_pubkey: &PublicKey, payee: &Payee, network: &NetworkGraph,
545545
first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
546546
logger: L, scorer: &S
@@ -1472,7 +1472,7 @@ where L::Target: Logger {
14721472

14731473
#[cfg(test)]
14741474
mod tests {
1475-
use routing;
1475+
use routing::scoring::Score;
14761476
use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
14771477
use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
14781478
use chain::transaction::OutPoint;
@@ -4549,7 +4549,7 @@ mod tests {
45494549
short_channel_id: u64,
45504550
}
45514551

4552-
impl routing::Score for BadChannelScorer {
4552+
impl Score for BadChannelScorer {
45534553
fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId) -> u64 {
45544554
if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
45554555
}
@@ -4561,7 +4561,7 @@ mod tests {
45614561
node_id: NodeId,
45624562
}
45634563

4564-
impl routing::Score for BadNodeScorer {
4564+
impl Score for BadNodeScorer {
45654565
fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, target: &NodeId) -> u64 {
45664566
if *target == self.node_id { u64::max_value() } else { 0 }
45674567
}

lightning/src/routing/scorer.rs renamed to lightning/src/routing/scoring.rs

Lines changed: 70 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
//! Utilities for scoring payment channels.
1111
//!
1212
//! [`Scorer`] may be given to [`find_route`] to score payment channels during path finding when a
13-
//! custom [`routing::Score`] implementation is not needed.
13+
//! custom [`Score`] implementation is not needed.
1414
//!
1515
//! # Example
1616
//!
@@ -19,7 +19,7 @@
1919
//! #
2020
//! # use lightning::routing::network_graph::NetworkGraph;
2121
//! # use lightning::routing::router::{RouteParameters, find_route};
22-
//! # use lightning::routing::scorer::{Scorer, ScoringParameters};
22+
//! # use lightning::routing::scoring::{Scorer, ScoringParameters};
2323
//! # use lightning::util::logger::{Logger, Record};
2424
//! # use secp256k1::key::PublicKey;
2525
//! #
@@ -52,19 +52,80 @@
5252
//!
5353
//! [`find_route`]: crate::routing::router::find_route
5454
55-
use routing;
56-
5755
use ln::msgs::DecodeError;
5856
use routing::network_graph::NodeId;
5957
use routing::router::RouteHop;
6058
use util::ser::{Readable, Writeable, Writer};
6159

6260
use prelude::*;
63-
use core::ops::Sub;
61+
use core::cell::{RefCell, RefMut};
62+
use core::ops::{DerefMut, Sub};
6463
use core::time::Duration;
6564
use io::{self, Read};
65+
use sync::{Mutex, MutexGuard};
66+
67+
/// An interface used to score payment channels for path finding.
68+
///
69+
/// Scoring is in terms of fees willing to be paid in order to avoid routing through a channel.
70+
pub trait Score {
71+
/// Returns the fee in msats willing to be paid to avoid routing through the given channel
72+
/// in the direction from `source` to `target`.
73+
///
74+
/// The maximum amount which may be in the HTLC at the given channel is given by
75+
/// `send_amt_sat`.
76+
///
77+
/// The channel's capacity in satoshis (given other HTLCs to be sent) is given by
78+
/// `channel_capacity_sats`. It may be guessed from various sources or assumed from no data.
79+
/// Your code should be overflow-safe through a `channel_capacity_sats` of 21 million BTC.
80+
fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, channel_capacity_sat: u64, source: &NodeId, target: &NodeId) -> u64;
81+
82+
/// Handles updating channel penalties after failing to route through a channel.
83+
fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64);
84+
}
85+
86+
/// A scorer that is accessed under a lock.
87+
///
88+
/// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
89+
/// having shared ownership of a scorer but without requiring internal locking in [`Score`]
90+
/// implementations. Internal locking would be detrimental to route finding performance and could
91+
/// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
92+
///
93+
/// [`find_route`]: crate::routing::router::find_route
94+
pub trait LockableScore<'a> {
95+
/// The locked [`Score`] type.
96+
type Locked: 'a + Score;
97+
98+
/// Returns the locked scorer.
99+
fn lock(&'a self) -> Self::Locked;
100+
}
101+
102+
impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
103+
type Locked = MutexGuard<'a, T>;
104+
105+
fn lock(&'a self) -> MutexGuard<'a, T> {
106+
Mutex::lock(self).unwrap()
107+
}
108+
}
109+
110+
impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
111+
type Locked = RefMut<'a, T>;
112+
113+
fn lock(&'a self) -> RefMut<'a, T> {
114+
self.borrow_mut()
115+
}
116+
}
117+
118+
impl<S: Score, T: DerefMut<Target=S>> Score for T {
119+
fn channel_penalty_msat(&self, short_channel_id: u64, send_amt_msat: u64, channel_capacity_sat: u64, source: &NodeId, target: &NodeId) -> u64 {
120+
self.deref().channel_penalty_msat(short_channel_id, send_amt_msat, channel_capacity_sat, source, target)
121+
}
122+
123+
fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
124+
self.deref_mut().payment_path_failed(path, short_channel_id)
125+
}
126+
}
66127

67-
/// [`routing::Score`] implementation that provides reasonable default behavior.
128+
/// [`Score`] implementation that provides reasonable default behavior.
68129
///
69130
/// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
70131
/// slightly higher fees are available. Will further penalize channels that fail to relay payments.
@@ -82,7 +143,7 @@ pub type DefaultTime = std::time::Instant;
82143
#[cfg(feature = "no-std")]
83144
pub type DefaultTime = Eternity;
84145

85-
/// [`routing::Score`] implementation parameterized by [`Time`].
146+
/// [`Score`] implementation parameterized by [`Time`].
86147
///
87148
/// See [`Scorer`] for details.
88149
///
@@ -236,7 +297,7 @@ impl Default for ScoringParameters {
236297
}
237298
}
238299

239-
impl<T: Time> routing::Score for ScorerUsingTime<T> {
300+
impl<T: Time> Score for ScorerUsingTime<T> {
240301
fn channel_penalty_msat(
241302
&self, short_channel_id: u64, send_amt_msat: u64, chan_capacity_sat: u64, _source: &NodeId, _target: &NodeId
242303
) -> u64 {
@@ -361,7 +422,7 @@ impl<T: Time> Readable for ChannelFailure<T> {
361422
mod tests {
362423
use super::{Eternity, ScoringParameters, ScorerUsingTime, Time};
363424

364-
use routing::Score;
425+
use routing::scoring::Score;
365426
use routing::network_graph::NodeId;
366427
use util::ser::{Readable, Writeable};
367428

0 commit comments

Comments
 (0)