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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
19#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
20pub struct LxRoute {
21 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 {
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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
77#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
78pub struct LxPath {
79 pub hops: Vec<LxRouteHop>,
81 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 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 pub fn fees(&self) -> Amount {
134 match &self.blinded_tail {
135 Some(_) => self
140 .hops
141 .iter()
142 .map(|hop| hop.fee_or_amount)
143 .sum::<Amount>(),
144 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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
158#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
159pub struct LxRouteHop {
160 pub node_pk: NodePk,
162 pub node_alias: Option<LxNodeAlias>,
164 pub scid: Scid,
166 pub fee_or_amount: Amount,
175 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#[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 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 #[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}