Skip to content

Commit a019106

Browse files
Implement pathfinding for onion messages
We *could* reuse router::get_route, but it's better to start from scratch because get_route includes a lot of payment-specific computations that impact performance.
1 parent 0245dfd commit a019106

File tree

2 files changed

+177
-0
lines changed

2 files changed

+177
-0
lines changed

lightning/src/routing/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
//! Structs and impls for receiving messages about the network and storing the topology live here.
1111
1212
pub mod gossip;
13+
pub mod onion_message;
1314
pub mod router;
1415
pub mod scoring;
1516
#[cfg(test)]
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
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+
//! Onion message pathfinding lives here.
11+
12+
use bitcoin::secp256k1::{self, PublicKey};
13+
14+
use routing::gossip::{NetworkGraph, NodeId};
15+
use util::logger::Logger;
16+
17+
use alloc::collections::BinaryHeap;
18+
use core::cmp;
19+
use core::ops::Deref;
20+
use prelude::*;
21+
22+
///
23+
pub fn find_path<L: Deref, GL: Deref>(
24+
our_node_pubkey: &PublicKey, destination: &PublicKey, network_graph: &NetworkGraph<GL>, first_hops: Option<&[&PublicKey]>, logger: L
25+
) -> Result<Vec<PublicKey>, Error> where L::Target: Logger, GL::Target: Logger
26+
{
27+
log_trace!(logger, "Searching for an onion message path from origin {} to destination {} and {} first hops {}overriding the network graph", our_node_pubkey, destination, first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
28+
let graph_lock = network_graph.read_only();
29+
let network_channels = graph_lock.channels();
30+
let network_nodes = graph_lock.nodes();
31+
let our_node_id = NodeId::from_pubkey(our_node_pubkey);
32+
let dest_node_id = NodeId::from_pubkey(destination);
33+
34+
// Add our start and first-hops to `frontier`.
35+
let start = NodeId::from_pubkey(&our_node_pubkey);
36+
let mut frontier = BinaryHeap::new();
37+
frontier.push(PathBuildingHop { cost: 0, node_id: start, parent_node_id: start });
38+
if let Some(first_hops) = first_hops {
39+
for hop in first_hops {
40+
let node_id = NodeId::from_pubkey(&hop);
41+
frontier.push(PathBuildingHop { cost: 1, node_id, parent_node_id: start });
42+
}
43+
}
44+
45+
let mut visited = HashMap::new();
46+
while !frontier.is_empty() {
47+
let PathBuildingHop { cost, node_id, parent_node_id } = frontier.pop().unwrap();
48+
if visited.contains_key(&node_id) { continue; }
49+
visited.insert(node_id, parent_node_id);
50+
if node_id == dest_node_id {
51+
return Ok(reverse_path(visited, our_node_id, dest_node_id, logger)?)
52+
}
53+
if let Some(node_info) = network_nodes.get(&node_id) {
54+
for scid in &node_info.channels {
55+
if let Some(chan_info) = network_channels.get(&scid) {
56+
if let Some((_, successor)) = chan_info.as_directed_from(&node_id) {
57+
// We may push a given successor multiple times, but the heap should sort its best entry
58+
// to the top. We do this because there is no way to adjust the priority of an existing
59+
// entry in `BinaryHeap`.
60+
frontier.push(PathBuildingHop {
61+
cost: cost + 1,
62+
node_id: *successor,
63+
parent_node_id: node_id,
64+
});
65+
}
66+
}
67+
}
68+
}
69+
}
70+
71+
Err(Error::PathNotFound)
72+
}
73+
74+
#[derive(Debug, PartialEq)]
75+
/// Errored running [`find_path`].
76+
pub enum Error {
77+
/// No path exists to the destination.
78+
PathNotFound,
79+
/// We failed to convert this node id into a [`PublicKey`].
80+
InvalidNodeId(secp256k1::Error),
81+
}
82+
83+
#[derive(Eq, PartialEq)]
84+
struct PathBuildingHop {
85+
cost: u64,
86+
node_id: NodeId,
87+
parent_node_id: NodeId,
88+
}
89+
90+
impl PartialOrd for PathBuildingHop {
91+
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
92+
// We need a min-heap, whereas `BinaryHeap`s are a max-heap, so compare the costs in reverse.
93+
other.cost.partial_cmp(&self.cost)
94+
}
95+
}
96+
97+
impl Ord for PathBuildingHop {
98+
fn cmp(&self, other: &Self) -> cmp::Ordering {
99+
self.partial_cmp(other).unwrap()
100+
}
101+
}
102+
103+
fn reverse_path<L: Deref>(
104+
parents: HashMap<NodeId, NodeId>, our_node_id: NodeId, destination: NodeId, logger: L
105+
)-> Result<Vec<PublicKey>, Error> where L::Target: Logger
106+
{
107+
let mut path = Vec::new();
108+
let mut curr = destination;
109+
loop {
110+
match PublicKey::from_slice(curr.as_slice()) {
111+
Ok(pk) => path.push(pk),
112+
Err(e) => return Err(Error::InvalidNodeId(e))
113+
}
114+
match parents.get(&curr) {
115+
None => return Err(Error::PathNotFound),
116+
Some(parent) => {
117+
if *parent == our_node_id { break; }
118+
curr = *parent;
119+
}
120+
}
121+
}
122+
123+
path.reverse();
124+
log_info!(logger, "Got route to {:?}: {:?}", destination, path);
125+
Ok(path)
126+
}
127+
128+
#[cfg(test)]
129+
mod tests {
130+
use routing::test_utils;
131+
132+
use sync::Arc;
133+
134+
#[test]
135+
fn one_hop() {
136+
let (secp_ctx, network_graph, _, _, logger) = test_utils::build_graph();
137+
let (_, our_id, _, node_pks) = test_utils::get_nodes(&secp_ctx);
138+
139+
let path = super::find_path(&our_id, &node_pks[0], &network_graph, None, Arc::clone(&logger)).unwrap();
140+
assert_eq!(path.len(), 1);
141+
assert!(path[0] == node_pks[0]);
142+
}
143+
144+
#[test]
145+
fn two_hops() {
146+
let (secp_ctx, network_graph, _, _, logger) = test_utils::build_graph();
147+
let (_, our_id, _, node_pks) = test_utils::get_nodes(&secp_ctx);
148+
149+
let path = super::find_path(&our_id, &node_pks[2], &network_graph, None, Arc::clone(&logger)).unwrap();
150+
assert_eq!(path.len(), 2);
151+
// See test_utils::build_graph ASCII graph, the first hop can be any of these
152+
assert!(path[0] == node_pks[1] || path[0] == node_pks[7] || path[0] == node_pks[0]);
153+
assert_eq!(path[1], node_pks[2]);
154+
}
155+
156+
#[test]
157+
fn three_hops() {
158+
let (secp_ctx, network_graph, _, _, logger) = test_utils::build_graph();
159+
let (_, our_id, _, node_pks) = test_utils::get_nodes(&secp_ctx);
160+
161+
let mut path = super::find_path(&our_id, &node_pks[5], &network_graph, None, Arc::clone(&logger)).unwrap();
162+
assert_eq!(path.len(), 3);
163+
assert!(path[0] == node_pks[1] || path[0] == node_pks[7] || path[0] == node_pks[0]);
164+
path.remove(0);
165+
assert_eq!(path, vec![node_pks[2], node_pks[5]]);
166+
}
167+
168+
#[test]
169+
fn long_path() {
170+
let (secp_ctx, network_graph, _, _, logger) = test_utils::build_line_graph();
171+
let (_, our_id, _, node_pks) = test_utils::get_nodes(&secp_ctx);
172+
173+
let path = super::find_path(&our_id, &node_pks[18], &network_graph, None, Arc::clone(&logger)).unwrap();
174+
assert_eq!(path.len(), 19);
175+
}
176+
}

0 commit comments

Comments
 (0)