Skip to main content

lexe_common/ln/
route.rs

1use std::{fmt, ops::Deref};
2
3use lightning::{
4    routing::{
5        gossip::{NetworkGraph, NodeId},
6        router::{BlindedTail, Path, Route, RouteHop},
7    },
8    util::logger::Logger,
9};
10#[cfg(any(test, feature = "test-utils"))]
11use proptest_derive::Arbitrary;
12use serde::{Deserialize, Serialize};
13
14use super::{amount::Amount, node_alias::LxNodeAlias};
15use crate::api::user::{NodePk, Scid};
16
17/// Newtype for [`Route`].
18#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
19#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
20pub struct LxRoute {
21    /// The [`LxPath`]s taken for a single (possibly multi-path) payment.
22    ///
23    /// If no [`LxBlindedTail`]s are present, then the pubkey of the last
24    /// [`LxRouteHop`] in each path must be the same.
25    pub paths: Vec<LxPath>,
26}
27
28impl LxRoute {
29    pub fn from_ldk<L: Deref<Target: Logger>>(
30        route: Route,
31        network_graph: &NetworkGraph<L>,
32    ) -> Self {
33        let mut paths = route
34            .paths
35            .into_iter()
36            .map(LxPath::from)
37            .collect::<Vec<_>>();
38
39        // Annotate all hops with node aliases known from our network graph.
40        {
41            let locked_graph = network_graph.read_only();
42
43            let lookup_alias = |node_pk: &NodePk| -> Option<LxNodeAlias> {
44                let node_id = NodeId::from_pubkey(&node_pk.0);
45                locked_graph
46                    .node(&node_id)
47                    .and_then(|node_info| node_info.announcement_info.as_ref())
48                    .map(|ann_info| LxNodeAlias::from(*ann_info.alias()))
49            };
50
51            for path in paths.iter_mut() {
52                for hop in path.hops.iter_mut() {
53                    hop.node_alias = lookup_alias(&hop.node_pk);
54                }
55            }
56        }
57
58        Self { paths }
59    }
60}
61
62impl fmt::Display for LxRoute {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        let num_paths = self.paths.len();
65        for (i, path) in self.paths.iter().enumerate() {
66            write!(f, "{path}")?;
67            if i != num_paths - 1 {
68                write!(f, " | ")?;
69            }
70        }
71        Ok(())
72    }
73}
74
75/// Newtype for [`Path`].
76#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
77#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
78pub struct LxPath {
79    /// The unblinded hops in this [`Path`]. Must be at least length one.
80    pub hops: Vec<LxRouteHop>,
81    /// The blinded path at which this path terminates, if present.
82    pub blinded_tail: Option<LxBlindedTail>,
83}
84
85impl From<Path> for LxPath {
86    fn from(path: Path) -> Self {
87        LxPath {
88            hops: path.hops.into_iter().map(LxRouteHop::from).collect(),
89            blinded_tail: path.blinded_tail.map(LxBlindedTail::from),
90        }
91    }
92}
93
94impl fmt::Display for LxPath {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        let amount = self.amount();
97        let fees = self.fees();
98        write!(f, "[{amount} sat, {fees} fees: ")?;
99        let num_hops = self.hops.len();
100        for (i, hop) in self.hops.iter().enumerate() {
101            let hop_node_pk = hop.node_pk;
102            match hop.node_alias {
103                Some(alias) => write!(f, "({alias}) {hop_node_pk}")?,
104                None => write!(f, "{hop_node_pk}")?,
105            }
106            if i != num_hops - 1 {
107                write!(f, " -> ")?;
108            }
109        }
110        if let Some(tail) = &self.blinded_tail {
111            let num_hops = tail.num_hops;
112            write!(f, " -> blinded tail with {num_hops} hops")?;
113        }
114        write!(f, "]")?;
115        Ok(())
116    }
117}
118
119impl LxPath {
120    /// Return the amount paid on this [`LxPath`], excluding the fees.
121    pub fn amount(&self) -> Amount {
122        match self.blinded_tail.as_ref() {
123            Some(tail) => tail.final_value,
124            None => self
125                .hops
126                .last()
127                .map_or(Amount::ZERO, |hop| hop.fee_or_amount),
128        }
129    }
130
131    /// Gets the fees on this [`Path`], excluding any excess fees paid to the
132    /// recipient.
133    pub fn fees(&self) -> Amount {
134        match &self.blinded_tail {
135            // There is a blinded tail:
136            // - Non-last hops are fees
137            // - Last hop is the fee for the entire blinded path.
138            // => Sum `fee_or_amount` over all hops.
139            Some(_) => self
140                .hops
141                .iter()
142                .map(|hop| hop.fee_or_amount)
143                .sum::<Amount>(),
144            // There is no blinded tail:
145            // - Non-last hops are fees
146            // - Last hop is the amount paid, so it should be ignored
147            None => match self.hops.split_last() {
148                Some((_last, non_last)) =>
149                    non_last.iter().map(|hop| hop.fee_or_amount).sum::<Amount>(),
150                None => Amount::ZERO,
151            },
152        }
153    }
154}
155
156/// Newtype for [`RouteHop`].
157#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
158#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
159pub struct LxRouteHop {
160    /// The node_id of the node at this hop.
161    pub node_pk: NodePk,
162    /// The alias of the node at this hop, if known.
163    pub node_alias: Option<LxNodeAlias>,
164    /// The channel used from the previous hop to reach this node.
165    pub scid: Scid,
166    /// If this is NOT the last hop in [`LxPath::hops`], this is the fee taken
167    /// on this hop (for paying for the use of the *next* channel in the path).
168    ///
169    /// If this IS the last hop in [`LxPath::hops`]:
170    /// - If we're sending to a blinded payment path, this is the fee paid for
171    ///   use of the entire blinded path.
172    /// - Otherwise, this is the amount of this [`LxPath`]'s part of the
173    ///   payment.
174    pub fee_or_amount: Amount,
175    /// Whether we believe this channel is announced in the public graph.
176    pub announced: bool,
177}
178
179impl From<RouteHop> for LxRouteHop {
180    fn from(hop: RouteHop) -> Self {
181        Self {
182            node_pk: NodePk(hop.pubkey),
183            node_alias: None,
184            scid: Scid(hop.short_channel_id),
185            fee_or_amount: Amount::from_msat(hop.fee_msat),
186            announced: hop.maybe_announced_channel,
187        }
188    }
189}
190
191/// Newtype for [`BlindedTail`].
192#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
193#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
194pub struct LxBlindedTail {
195    pub num_hops: usize,
196    /// The total amount paid on this [`LxPath`], excluding the fees.
197    pub final_value: Amount,
198}
199
200impl From<BlindedTail> for LxBlindedTail {
201    fn from(tail: BlindedTail) -> Self {
202        Self {
203            num_hops: tail.hops.len(),
204            final_value: Amount::from_msat(tail.final_value_msat),
205        }
206    }
207}
208
209#[cfg(test)]
210mod test {
211    use lexe_crypto::rng::{FastRng, SysRng};
212    use proptest::prelude::any;
213
214    use super::*;
215    use crate::test_utils::arbitrary;
216
217    /// Check the [`fmt::Display`] implementation of [`LxRoute`].
218    ///
219    /// $ cargo test -p lexe-common display_route -- --ignored --nocapture
220    #[ignore]
221    #[test]
222    fn display_route() {
223        let mut rng = FastRng::from_sysrng(&mut SysRng::new());
224        let mut route = arbitrary::gen_value(&mut rng, any::<LxRoute>());
225        route.paths.truncate(3);
226        for path in route.paths.iter_mut() {
227            path.hops.truncate(3);
228        }
229        println!("Route: {route}");
230    }
231}