Require Writeable for all `Score` and impl `Writeable` for `LockedScore`
[rust-lightning] / lightning / src / routing / mod.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Structs and impls for receiving messages about the network and storing the topology live here.
11
12 pub mod network_graph;
13 pub mod router;
14 pub mod scorer;
15
16 use routing::network_graph::NodeId;
17 use routing::router::RouteHop;
18
19 use sync::{Mutex, MutexGuard};
20
21 use util::ser::{Writeable, Writer};
22 use io;
23
24 /// An interface used to score payment channels for path finding.
25 ///
26 ///     Scoring is in terms of fees willing to be paid in order to avoid routing through a channel.
27 pub trait Score : Writeable {
28         /// Returns the fee in msats willing to be paid to avoid routing through the given channel
29         /// in the direction from `source` to `target`.
30         fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId) -> u64;
31
32         /// Handles updating channel penalties after failing to route through a channel.
33         fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64);
34 }
35
36 /// A scorer that is accessed under a lock.
37 ///
38 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
39 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
40 /// implementations. Internal locking would be detrimental to route finding performance and could
41 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
42 ///
43 /// [`find_route`]: crate::routing::router::find_route
44 pub struct LockableScore<S: Score> {
45         scorer: Mutex<S>,
46 }
47
48 impl<S: Score> LockableScore<S> {
49         /// Constructs a new LockableScore from a Score
50         pub fn new(score: S) -> Self {
51                 Self { scorer: Mutex::new(score) }
52         }
53         /// Returns the locked scorer.
54         /// (C-not exported)
55         pub fn lock<'a>(&'a self) -> MutexGuard<'a, S> {
56                 self.scorer.lock().unwrap()
57         }
58 }
59
60 impl<S: Score> Writeable for LockableScore<S> {
61         #[inline]
62         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
63                 self.scorer.lock().unwrap().write(w)
64         }
65 }