Merge pull request #123 from TheBlueMatt/2018-08-secp-0.10
[rust-lightning] / src / ln / router.rs
1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1,Message};
3 use secp256k1;
4
5 use bitcoin::util::hash::Sha256dHash;
6
7 use ln::channelmanager;
8 use ln::msgs::{ErrorAction,HandleError,RoutingMessageHandler,MsgEncodable,NetAddress,GlobalFeatures};
9 use ln::msgs;
10 use util::logger::Logger;
11
12 use std::cmp;
13 use std::sync::{RwLock,Arc};
14 use std::collections::{HashMap,BinaryHeap};
15 use std::collections::hash_map::Entry;
16 use std;
17
18 /// A hop in a route
19 #[derive(Clone)]
20 pub struct RouteHop {
21         pub pubkey: PublicKey,
22         /// The channel that should be used from the previous hop to reach this node.
23         pub short_channel_id: u64,
24         /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
25         pub fee_msat: u64,
26         /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
27         /// expected at the destination, in excess of the current block height.
28         pub cltv_expiry_delta: u32,
29 }
30
31 /// A route from us through the network to a destination
32 #[derive(Clone)]
33 pub struct Route {
34         /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
35         /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
36         /// length.
37         pub hops: Vec<RouteHop>,
38 }
39
40 struct DirectionalChannelInfo {
41         src_node_id: PublicKey,
42         last_update: u32,
43         enabled: bool,
44         cltv_expiry_delta: u16,
45         htlc_minimum_msat: u64,
46         fee_base_msat: u32,
47         fee_proportional_millionths: u32,
48 }
49
50 impl std::fmt::Display for DirectionalChannelInfo {
51         fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
52                 write!(f, "src_node_id {}, last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fee_base_msat {}, fee_proportional_millionths {}", log_pubkey!(self.src_node_id), self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fee_base_msat, self.fee_proportional_millionths)?;
53                 Ok(())
54         }
55 }
56
57 struct ChannelInfo {
58         features: GlobalFeatures,
59         one_to_two: DirectionalChannelInfo,
60         two_to_one: DirectionalChannelInfo,
61 }
62
63 impl std::fmt::Display for ChannelInfo {
64         fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
65                 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
66                 Ok(())
67         }
68 }
69
70 struct NodeInfo {
71         #[cfg(feature = "non_bitcoin_chain_hash_routing")]
72         channels: Vec<(u64, Sha256dHash)>,
73         #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
74         channels: Vec<u64>,
75
76         lowest_inbound_channel_fee_base_msat: u32,
77         lowest_inbound_channel_fee_proportional_millionths: u32,
78
79         features: GlobalFeatures,
80         last_update: u32,
81         rgb: [u8; 3],
82         alias: [u8; 32],
83         addresses: Vec<NetAddress>,
84 }
85
86 impl std::fmt::Display for NodeInfo {
87         fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
88                 write!(f, "features: {}, last_update: {}, lowest_inbound_channel_fee_base_msat: {}, lowest_inbound_channel_fee_proportional_millionths: {}, channels: {:?}", log_bytes!(self.features.encode()), self.last_update, self.lowest_inbound_channel_fee_base_msat, self.lowest_inbound_channel_fee_proportional_millionths, &self.channels[..])?;
89                 Ok(())
90         }
91 }
92
93 struct NetworkMap {
94         #[cfg(feature = "non_bitcoin_chain_hash_routing")]
95         channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
96         #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
97         channels: HashMap<u64, ChannelInfo>,
98
99         our_node_id: PublicKey,
100         nodes: HashMap<PublicKey, NodeInfo>,
101 }
102
103 impl std::fmt::Display for NetworkMap {
104         fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
105                 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
106                 for (key, val) in self.channels.iter() {
107                         write!(f, " {}: {}\n", key, val)?;
108                 }
109                 write!(f, "[Nodes]\n")?;
110                 for (key, val) in self.nodes.iter() {
111                         write!(f, " {}: {}\n", log_pubkey!(key), val)?;
112                 }
113                 Ok(())
114         }
115 }
116
117 impl NetworkMap {
118         #[cfg(feature = "non_bitcoin_chain_hash_routing")]
119         #[inline]
120         fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
121                 (short_channel_id, chain_hash)
122         }
123
124         #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
125         #[inline]
126         fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
127                 short_channel_id
128         }
129
130         #[cfg(feature = "non_bitcoin_chain_hash_routing")]
131         #[inline]
132         fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
133                 &id.0
134         }
135
136         #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
137         #[inline]
138         fn get_short_id(id: &u64) -> &u64 {
139                 id
140         }
141 }
142
143 /// A channel descriptor which provides a last-hop route to get_route
144 pub struct RouteHint {
145         pub src_node_id: PublicKey,
146         pub short_channel_id: u64,
147         pub fee_base_msat: u32,
148         pub fee_proportional_millionths: u32,
149         pub cltv_expiry_delta: u16,
150         pub htlc_minimum_msat: u64,
151 }
152
153 /// Tracks a view of the network, receiving updates from peers and generating Routes to
154 /// payment destinations.
155 pub struct Router {
156         secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
157         network_map: RwLock<NetworkMap>,
158         logger: Arc<Logger>,
159 }
160
161 macro_rules! secp_verify_sig {
162         ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
163                 match $secp_ctx.verify($msg, $sig, $pubkey) {
164                         Ok(_) => {},
165                         Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
166                 }
167         };
168 }
169
170 impl RoutingMessageHandler for Router {
171         fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), HandleError> {
172                 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
173                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
174
175                 let mut network = self.network_map.write().unwrap();
176                 match network.nodes.get_mut(&msg.contents.node_id) {
177                         None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
178                         Some(node) => {
179                                 if node.last_update >= msg.contents.timestamp {
180                                         return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
181                                 }
182
183                                 node.features = msg.contents.features.clone();
184                                 node.last_update = msg.contents.timestamp;
185                                 node.rgb = msg.contents.rgb;
186                                 node.alias = msg.contents.alias;
187                                 node.addresses = msg.contents.addresses.clone();
188                                 Ok(())
189                         }
190                 }
191         }
192
193         fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
194                 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
195                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
196                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
197                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
198                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
199
200                 //TODO: Call blockchain thing to ask if the short_channel_id is valid
201                 //TODO: Only allow bitcoin chain_hash
202
203                 if msg.contents.features.requires_unknown_bits() {
204                         return Err(HandleError{err: "Channel announcement required unknown feature flags", action: None});
205                 }
206
207                 let mut network = self.network_map.write().unwrap();
208
209                 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
210                         Entry::Occupied(_) => {
211                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
212                                 //in the blockchain API, we need to handle it smartly here, though its unclear
213                                 //exactly how...
214                                 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
215                         },
216                         Entry::Vacant(entry) => {
217                                 entry.insert(ChannelInfo {
218                                         features: msg.contents.features.clone(),
219                                         one_to_two: DirectionalChannelInfo {
220                                                 src_node_id: msg.contents.node_id_1.clone(),
221                                                 last_update: 0,
222                                                 enabled: false,
223                                                 cltv_expiry_delta: u16::max_value(),
224                                                 htlc_minimum_msat: u64::max_value(),
225                                                 fee_base_msat: u32::max_value(),
226                                                 fee_proportional_millionths: u32::max_value(),
227                                         },
228                                         two_to_one: DirectionalChannelInfo {
229                                                 src_node_id: msg.contents.node_id_2.clone(),
230                                                 last_update: 0,
231                                                 enabled: false,
232                                                 cltv_expiry_delta: u16::max_value(),
233                                                 htlc_minimum_msat: u64::max_value(),
234                                                 fee_base_msat: u32::max_value(),
235                                                 fee_proportional_millionths: u32::max_value(),
236                                         }
237                                 });
238                         }
239                 };
240
241                 macro_rules! add_channel_to_node {
242                         ( $node_id: expr ) => {
243                                 match network.nodes.entry($node_id) {
244                                         Entry::Occupied(node_entry) => {
245                                                 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
246                                         },
247                                         Entry::Vacant(node_entry) => {
248                                                 node_entry.insert(NodeInfo {
249                                                         channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
250                                                         lowest_inbound_channel_fee_base_msat: u32::max_value(),
251                                                         lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
252                                                         features: GlobalFeatures::new(),
253                                                         last_update: 0,
254                                                         rgb: [0; 3],
255                                                         alias: [0; 32],
256                                                         addresses: Vec::new(),
257                                                 });
258                                         }
259                                 }
260                         };
261                 }
262
263                 add_channel_to_node!(msg.contents.node_id_1);
264                 add_channel_to_node!(msg.contents.node_id_2);
265
266                 Ok(!msg.contents.features.supports_unknown_bits())
267         }
268
269         fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
270                 match update {
271                         &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
272                                 let _ = self.handle_channel_update(msg);
273                         },
274                         &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
275                                 let mut network = self.network_map.write().unwrap();
276                                 if let Some(chan) = network.channels.remove(short_channel_id) {
277                                         network.nodes.get_mut(&chan.one_to_two.src_node_id).unwrap().channels.retain(|chan_id| {
278                                                 chan_id != NetworkMap::get_short_id(chan_id)
279                                         });
280                                         network.nodes.get_mut(&chan.two_to_one.src_node_id).unwrap().channels.retain(|chan_id| {
281                                                 chan_id != NetworkMap::get_short_id(chan_id)
282                                         });
283                                 }
284                         },
285                 }
286         }
287
288         fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), HandleError> {
289                 let mut network = self.network_map.write().unwrap();
290                 let dest_node_id;
291                 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
292                 let chan_was_enabled;
293
294                 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
295                         None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
296                         Some(channel) => {
297                                 macro_rules! maybe_update_channel_info {
298                                         ( $target: expr) => {
299                                                 if $target.last_update >= msg.contents.timestamp {
300                                                         return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
301                                                 }
302                                                 chan_was_enabled = $target.enabled;
303                                                 $target.last_update = msg.contents.timestamp;
304                                                 $target.enabled = chan_enabled;
305                                                 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
306                                                 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
307                                                 $target.fee_base_msat = msg.contents.fee_base_msat;
308                                                 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
309                                         }
310                                 }
311
312                                 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
313                                 if msg.contents.flags & 1 == 1 {
314                                         dest_node_id = channel.one_to_two.src_node_id.clone();
315                                         secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
316                                         maybe_update_channel_info!(channel.two_to_one);
317                                 } else {
318                                         dest_node_id = channel.two_to_one.src_node_id.clone();
319                                         secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
320                                         maybe_update_channel_info!(channel.one_to_two);
321                                 }
322                         }
323                 }
324
325                 if chan_enabled {
326                         let node = network.nodes.get_mut(&dest_node_id).unwrap();
327                         node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
328                         node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
329                 } else if chan_was_enabled {
330                         let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
331                         let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
332
333                         {
334                                 let node = network.nodes.get(&dest_node_id).unwrap();
335
336                                 for chan_id in node.channels.iter() {
337                                         let chan = network.channels.get(chan_id).unwrap();
338                                         if chan.one_to_two.src_node_id == dest_node_id {
339                                                 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
340                                                 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
341                                         } else {
342                                                 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
343                                                 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
344                                         }
345                                 }
346                         }
347
348                         //TODO: satisfy the borrow-checker without a double-map-lookup :(
349                         let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
350                         mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
351                         mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
352                 }
353
354                 Ok(())
355         }
356 }
357
358 #[derive(Eq, PartialEq)]
359 struct RouteGraphNode {
360         pubkey: PublicKey,
361         lowest_fee_to_peer_through_node: u64,
362         lowest_fee_to_node: u64,
363 }
364
365 impl cmp::Ord for RouteGraphNode {
366         fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
367                 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
368                         .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
369         }
370 }
371
372 impl cmp::PartialOrd for RouteGraphNode {
373         fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
374                 Some(self.cmp(other))
375         }
376 }
377
378 struct DummyDirectionalChannelInfo {
379         src_node_id: PublicKey,
380         cltv_expiry_delta: u32,
381         htlc_minimum_msat: u64,
382         fee_base_msat: u32,
383         fee_proportional_millionths: u32,
384 }
385
386 impl Router {
387         pub fn new(our_pubkey: PublicKey, logger: Arc<Logger>) -> Router {
388                 let mut nodes = HashMap::new();
389                 nodes.insert(our_pubkey.clone(), NodeInfo {
390                         channels: Vec::new(),
391                         lowest_inbound_channel_fee_base_msat: u32::max_value(),
392                         lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
393                         features: GlobalFeatures::new(),
394                         last_update: 0,
395                         rgb: [0; 3],
396                         alias: [0; 32],
397                         addresses: Vec::new(),
398                 });
399                 Router {
400                         secp_ctx: Secp256k1::verification_only(),
401                         network_map: RwLock::new(NetworkMap {
402                                 channels: HashMap::new(),
403                                 our_node_id: our_pubkey,
404                                 nodes: nodes,
405                         }),
406                         logger,
407                 }
408         }
409
410         /// Dumps the entire network view of this Router to the logger provided in the constructor at
411         /// level Trace
412         pub fn trace_state(&self) {
413                 log_trace!(self, "{}", self.network_map.read().unwrap());
414         }
415
416         /// Get network addresses by node id
417         pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
418                 let network = self.network_map.read().unwrap();
419                 network.nodes.get(pubkey).map(|n| n.addresses.clone())
420         }
421
422         /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
423         /// with an expotnential decay in node "badness". Note that there is deliberately no
424         /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
425         /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
426         /// boolean will reduce the penalty, returning the node to usability faster. If the node is
427         /// behaving correctly, it will disable the failing channel and we will use it again next time.
428         pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
429                 unimplemented!();
430         }
431
432         /// Gets a route from us to the given target node.
433         /// Extra routing hops between known nodes and the target will be used if they are included in
434         /// last_hops.
435         /// If some channels aren't announced, it may be useful to fill in a first_hops with the
436         /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
437         /// (this Router's) view of our local channels will be ignored, and only those in first_hops
438         /// will be used. Panics if first_hops contains channels without short_channel_ids
439         /// (ChannelManager::list_usable_channels will never include such channels).
440         /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
441         /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
442         /// *is* checked as they may change based on the receiving node.
443         pub fn get_route(&self, target: &PublicKey, first_hops: Option<&[channelmanager::ChannelDetails]>, last_hops: &[RouteHint], final_value_msat: u64, final_cltv: u32) -> Result<Route, HandleError> {
444                 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
445                 // uptime/success in using a node in the past.
446                 let network = self.network_map.read().unwrap();
447
448                 if *target == network.our_node_id {
449                         return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
450                 }
451
452                 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
453                         return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
454                 }
455
456                 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
457                 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
458                 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
459                 // to use as the A* heuristic beyond just the cost to get one node further than the current
460                 // one.
461
462                 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
463                         src_node_id: network.our_node_id.clone(),
464                         cltv_expiry_delta: 0,
465                         htlc_minimum_msat: 0,
466                         fee_base_msat: 0,
467                         fee_proportional_millionths: 0,
468                 };
469
470                 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
471                 let mut dist = HashMap::with_capacity(network.nodes.len());
472
473                 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
474                 if let Some(hops) = first_hops {
475                         for chan in hops {
476                                 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
477                                 if chan.remote_network_id == *target {
478                                         return Ok(Route {
479                                                 hops: vec![RouteHop {
480                                                         pubkey: chan.remote_network_id,
481                                                         short_channel_id,
482                                                         fee_msat: final_value_msat,
483                                                         cltv_expiry_delta: final_cltv,
484                                                 }],
485                                         });
486                                 }
487                                 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
488                         }
489                         if first_hop_targets.is_empty() {
490                                 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
491                         }
492                 }
493
494                 macro_rules! add_entry {
495                         // Adds entry which goes from the node pointed to by $directional_info to
496                         // $dest_node_id over the channel with id $chan_id with fees described in
497                         // $directional_info.
498                         ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
499                                 //TODO: Explore simply adding fee to hit htlc_minimum_msat
500                                 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
501                                         let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
502                                         if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
503                                                         ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
504                                         {
505                                                 let mut total_fee = $starting_fee_msat as u64;
506                                                 let hm_entry = dist.entry(&$directional_info.src_node_id);
507                                                 let old_entry = hm_entry.or_insert_with(|| {
508                                                         let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
509                                                         (u64::max_value(),
510                                                                 node.lowest_inbound_channel_fee_base_msat,
511                                                                 node.lowest_inbound_channel_fee_proportional_millionths,
512                                                                 RouteHop {
513                                                                         pubkey: $dest_node_id.clone(),
514                                                                         short_channel_id: 0,
515                                                                         fee_msat: 0,
516                                                                         cltv_expiry_delta: 0,
517                                                         })
518                                                 });
519                                                 if $directional_info.src_node_id != network.our_node_id {
520                                                         // Ignore new_fee for channel-from-us as we assume all channels-from-us
521                                                         // will have the same effective-fee
522                                                         total_fee += new_fee;
523                                                         if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
524                                                                 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
525                                                         } else {
526                                                                 // max_value means we'll always fail the old_entry.0 > total_fee check
527                                                                 total_fee = u64::max_value();
528                                                         }
529                                                 }
530                                                 let new_graph_node = RouteGraphNode {
531                                                         pubkey: $directional_info.src_node_id,
532                                                         lowest_fee_to_peer_through_node: total_fee,
533                                                         lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
534                                                 };
535                                                 if old_entry.0 > total_fee {
536                                                         targets.push(new_graph_node);
537                                                         old_entry.0 = total_fee;
538                                                         old_entry.3 = RouteHop {
539                                                                 pubkey: $dest_node_id.clone(),
540                                                                 short_channel_id: $chan_id.clone(),
541                                                                 fee_msat: new_fee, // This field is ignored on the last-hop anyway
542                                                                 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
543                                                         }
544                                                 }
545                                         }
546                                 }
547                         };
548                 }
549
550                 macro_rules! add_entries_to_cheapest_to_target_node {
551                         ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
552                                 if first_hops.is_some() {
553                                         if let Some(first_hop) = first_hop_targets.get(&$node_id) {
554                                                 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
555                                         }
556                                 }
557
558                                 for chan_id in $node.channels.iter() {
559                                         let chan = network.channels.get(chan_id).unwrap();
560                                         if chan.one_to_two.src_node_id == *$node_id {
561                                                 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
562                                                 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
563                                                         if chan.two_to_one.enabled {
564                                                                 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
565                                                         }
566                                                 }
567                                         } else {
568                                                 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
569                                                         if chan.one_to_two.enabled {
570                                                                 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
571                                                         }
572                                                 }
573                                         }
574                                 }
575                         };
576                 }
577
578                 match network.nodes.get(target) {
579                         None => {},
580                         Some(node) => {
581                                 add_entries_to_cheapest_to_target_node!(node, target, 0);
582                         },
583                 }
584
585                 for hop in last_hops.iter() {
586                         if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
587                                 if network.nodes.get(&hop.src_node_id).is_some() {
588                                         if first_hops.is_some() {
589                                                 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
590                                                         add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
591                                                 }
592                                         }
593                                         add_entry!(hop.short_channel_id, target, hop, 0);
594                                 }
595                         }
596                 }
597
598                 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
599                         if pubkey == network.our_node_id {
600                                 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
601                                 while res.last().unwrap().pubkey != *target {
602                                         let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
603                                                 Some(hop) => hop.3,
604                                                 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
605                                         };
606                                         res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
607                                         res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
608                                         res.push(new_entry);
609                                 }
610                                 res.last_mut().unwrap().fee_msat = final_value_msat;
611                                 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
612                                 let route = Route { hops: res };
613                                 log_trace!(self, "Got route: {}", log_route!(route));
614                                 return Ok(route);
615                         }
616
617                         match network.nodes.get(&pubkey) {
618                                 None => {},
619                                 Some(node) => {
620                                         add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
621                                 },
622                         }
623                 }
624
625                 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
626         }
627 }
628
629 #[cfg(test)]
630 mod tests {
631         use ln::channelmanager;
632         use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
633         use ln::msgs::GlobalFeatures;
634         use util::test_utils;
635         use util::logger::Logger;
636
637         use bitcoin::util::hash::Sha256dHash;
638
639         use hex;
640
641         use secp256k1::key::{PublicKey,SecretKey};
642         use secp256k1::Secp256k1;
643
644         use std::sync::Arc;
645
646         #[test]
647         fn route_test() {
648                 let secp_ctx = Secp256k1::new();
649                 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
650                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
651                 let router = Router::new(our_id, Arc::clone(&logger));
652
653                 // Build network from our_id to node8:
654                 //
655                 //        -1(1)2-  node1  -1(3)2-
656                 //       /                       \
657                 // our_id -1(12)2- node8 -1(13)2--- node3
658                 //       \                       /
659                 //        -1(2)2-  node2  -1(4)2-
660                 //
661                 //
662                 // chan1  1-to-2: disabled
663                 // chan1  2-to-1: enabled, 0 fee
664                 //
665                 // chan2  1-to-2: enabled, ignored fee
666                 // chan2  2-to-1: enabled, 0 fee
667                 //
668                 // chan3  1-to-2: enabled, 0 fee
669                 // chan3  2-to-1: enabled, 100 msat fee
670                 //
671                 // chan4  1-to-2: enabled, 100% fee
672                 // chan4  2-to-1: enabled, 0 fee
673                 //
674                 // chan12 1-to-2: enabled, ignored fee
675                 // chan12 2-to-1: enabled, 0 fee
676                 //
677                 // chan13 1-to-2: enabled, 200% fee
678                 // chan13 2-to-1: enabled, 0 fee
679                 //
680                 //
681                 //       -1(5)2- node4 -1(8)2--
682                 //       |         2          |
683                 //       |       (11)         |
684                 //      /          1           \
685                 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
686                 //      \                      /
687                 //       -1(7)2- node6 -1(10)2-
688                 //
689                 // chan5  1-to-2: enabled, 100 msat fee
690                 // chan5  2-to-1: enabled, 0 fee
691                 //
692                 // chan6  1-to-2: enabled, 0 fee
693                 // chan6  2-to-1: enabled, 0 fee
694                 //
695                 // chan7  1-to-2: enabled, 100% fee
696                 // chan7  2-to-1: enabled, 0 fee
697                 //
698                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
699                 // chan8  2-to-1: enabled, 0 fee
700                 //
701                 // chan9  1-to-2: enabled, 1001 msat fee
702                 // chan9  2-to-1: enabled, 0 fee
703                 //
704                 // chan10 1-to-2: enabled, 0 fee
705                 // chan10 2-to-1: enabled, 0 fee
706                 //
707                 // chan11 1-to-2: enabled, 0 fee
708                 // chan11 2-to-1: enabled, 0 fee
709
710                 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
711                 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
712                 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
713                 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
714                 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
715                 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
716                 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
717                 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
718
719                 let zero_hash = Sha256dHash::from_data(&[0; 32]);
720
721                 {
722                         let mut network = router.network_map.write().unwrap();
723
724                         network.nodes.insert(node1.clone(), NodeInfo {
725                                 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
726                                 lowest_inbound_channel_fee_base_msat: 100,
727                                 lowest_inbound_channel_fee_proportional_millionths: 0,
728                                 features: GlobalFeatures::new(),
729                                 last_update: 1,
730                                 rgb: [0; 3],
731                                 alias: [0; 32],
732                                 addresses: Vec::new(),
733                         });
734                         network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
735                                 features: GlobalFeatures::new(),
736                                 one_to_two: DirectionalChannelInfo {
737                                         src_node_id: our_id.clone(),
738                                         last_update: 0,
739                                         enabled: false,
740                                         cltv_expiry_delta: u16::max_value(), // This value should be ignored
741                                         htlc_minimum_msat: 0,
742                                         fee_base_msat: u32::max_value(), // This value should be ignored
743                                         fee_proportional_millionths: u32::max_value(), // This value should be ignored
744                                 }, two_to_one: DirectionalChannelInfo {
745                                         src_node_id: node1.clone(),
746                                         last_update: 0,
747                                         enabled: true,
748                                         cltv_expiry_delta: 0,
749                                         htlc_minimum_msat: 0,
750                                         fee_base_msat: 0,
751                                         fee_proportional_millionths: 0,
752                                 },
753                         });
754                         network.nodes.insert(node2.clone(), NodeInfo {
755                                 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
756                                 lowest_inbound_channel_fee_base_msat: 0,
757                                 lowest_inbound_channel_fee_proportional_millionths: 0,
758                                 features: GlobalFeatures::new(),
759                                 last_update: 1,
760                                 rgb: [0; 3],
761                                 alias: [0; 32],
762                                 addresses: Vec::new(),
763                         });
764                         network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
765                                 features: GlobalFeatures::new(),
766                                 one_to_two: DirectionalChannelInfo {
767                                         src_node_id: our_id.clone(),
768                                         last_update: 0,
769                                         enabled: true,
770                                         cltv_expiry_delta: u16::max_value(), // This value should be ignored
771                                         htlc_minimum_msat: 0,
772                                         fee_base_msat: u32::max_value(), // This value should be ignored
773                                         fee_proportional_millionths: u32::max_value(), // This value should be ignored
774                                 }, two_to_one: DirectionalChannelInfo {
775                                         src_node_id: node2.clone(),
776                                         last_update: 0,
777                                         enabled: true,
778                                         cltv_expiry_delta: 0,
779                                         htlc_minimum_msat: 0,
780                                         fee_base_msat: 0,
781                                         fee_proportional_millionths: 0,
782                                 },
783                         });
784                         network.nodes.insert(node8.clone(), NodeInfo {
785                                 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
786                                 lowest_inbound_channel_fee_base_msat: 0,
787                                 lowest_inbound_channel_fee_proportional_millionths: 0,
788                                 features: GlobalFeatures::new(),
789                                 last_update: 1,
790                                 rgb: [0; 3],
791                                 alias: [0; 32],
792                                 addresses: Vec::new(),
793                         });
794                         network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
795                                 features: GlobalFeatures::new(),
796                                 one_to_two: DirectionalChannelInfo {
797                                         src_node_id: our_id.clone(),
798                                         last_update: 0,
799                                         enabled: true,
800                                         cltv_expiry_delta: u16::max_value(), // This value should be ignored
801                                         htlc_minimum_msat: 0,
802                                         fee_base_msat: u32::max_value(), // This value should be ignored
803                                         fee_proportional_millionths: u32::max_value(), // This value should be ignored
804                                 }, two_to_one: DirectionalChannelInfo {
805                                         src_node_id: node8.clone(),
806                                         last_update: 0,
807                                         enabled: true,
808                                         cltv_expiry_delta: 0,
809                                         htlc_minimum_msat: 0,
810                                         fee_base_msat: 0,
811                                         fee_proportional_millionths: 0,
812                                 },
813                         });
814                         network.nodes.insert(node3.clone(), NodeInfo {
815                                 channels: vec!(
816                                         NetworkMap::get_key(3, zero_hash.clone()),
817                                         NetworkMap::get_key(4, zero_hash.clone()),
818                                         NetworkMap::get_key(13, zero_hash.clone()),
819                                         NetworkMap::get_key(5, zero_hash.clone()),
820                                         NetworkMap::get_key(6, zero_hash.clone()),
821                                         NetworkMap::get_key(7, zero_hash.clone())),
822                                 lowest_inbound_channel_fee_base_msat: 0,
823                                 lowest_inbound_channel_fee_proportional_millionths: 0,
824                                 features: GlobalFeatures::new(),
825                                 last_update: 1,
826                                 rgb: [0; 3],
827                                 alias: [0; 32],
828                                 addresses: Vec::new(),
829                         });
830                         network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
831                                 features: GlobalFeatures::new(),
832                                 one_to_two: DirectionalChannelInfo {
833                                         src_node_id: node1.clone(),
834                                         last_update: 0,
835                                         enabled: true,
836                                         cltv_expiry_delta: (3 << 8) | 1,
837                                         htlc_minimum_msat: 0,
838                                         fee_base_msat: 0,
839                                         fee_proportional_millionths: 0,
840                                 }, two_to_one: DirectionalChannelInfo {
841                                         src_node_id: node3.clone(),
842                                         last_update: 0,
843                                         enabled: true,
844                                         cltv_expiry_delta: (3 << 8) | 2,
845                                         htlc_minimum_msat: 0,
846                                         fee_base_msat: 100,
847                                         fee_proportional_millionths: 0,
848                                 },
849                         });
850                         network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
851                                 features: GlobalFeatures::new(),
852                                 one_to_two: DirectionalChannelInfo {
853                                         src_node_id: node2.clone(),
854                                         last_update: 0,
855                                         enabled: true,
856                                         cltv_expiry_delta: (4 << 8) | 1,
857                                         htlc_minimum_msat: 0,
858                                         fee_base_msat: 0,
859                                         fee_proportional_millionths: 1000000,
860                                 }, two_to_one: DirectionalChannelInfo {
861                                         src_node_id: node3.clone(),
862                                         last_update: 0,
863                                         enabled: true,
864                                         cltv_expiry_delta: (4 << 8) | 2,
865                                         htlc_minimum_msat: 0,
866                                         fee_base_msat: 0,
867                                         fee_proportional_millionths: 0,
868                                 },
869                         });
870                         network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
871                                 features: GlobalFeatures::new(),
872                                 one_to_two: DirectionalChannelInfo {
873                                         src_node_id: node8.clone(),
874                                         last_update: 0,
875                                         enabled: true,
876                                         cltv_expiry_delta: (13 << 8) | 1,
877                                         htlc_minimum_msat: 0,
878                                         fee_base_msat: 0,
879                                         fee_proportional_millionths: 2000000,
880                                 }, two_to_one: DirectionalChannelInfo {
881                                         src_node_id: node3.clone(),
882                                         last_update: 0,
883                                         enabled: true,
884                                         cltv_expiry_delta: (13 << 8) | 2,
885                                         htlc_minimum_msat: 0,
886                                         fee_base_msat: 0,
887                                         fee_proportional_millionths: 0,
888                                 },
889                         });
890                         network.nodes.insert(node4.clone(), NodeInfo {
891                                 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
892                                 lowest_inbound_channel_fee_base_msat: 0,
893                                 lowest_inbound_channel_fee_proportional_millionths: 0,
894                                 features: GlobalFeatures::new(),
895                                 last_update: 1,
896                                 rgb: [0; 3],
897                                 alias: [0; 32],
898                                 addresses: Vec::new(),
899                         });
900                         network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
901                                 features: GlobalFeatures::new(),
902                                 one_to_two: DirectionalChannelInfo {
903                                         src_node_id: node3.clone(),
904                                         last_update: 0,
905                                         enabled: true,
906                                         cltv_expiry_delta: (5 << 8) | 1,
907                                         htlc_minimum_msat: 0,
908                                         fee_base_msat: 100,
909                                         fee_proportional_millionths: 0,
910                                 }, two_to_one: DirectionalChannelInfo {
911                                         src_node_id: node4.clone(),
912                                         last_update: 0,
913                                         enabled: true,
914                                         cltv_expiry_delta: (5 << 8) | 2,
915                                         htlc_minimum_msat: 0,
916                                         fee_base_msat: 0,
917                                         fee_proportional_millionths: 0,
918                                 },
919                         });
920                         network.nodes.insert(node5.clone(), NodeInfo {
921                                 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
922                                 lowest_inbound_channel_fee_base_msat: 0,
923                                 lowest_inbound_channel_fee_proportional_millionths: 0,
924                                 features: GlobalFeatures::new(),
925                                 last_update: 1,
926                                 rgb: [0; 3],
927                                 alias: [0; 32],
928                                 addresses: Vec::new(),
929                         });
930                         network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
931                                 features: GlobalFeatures::new(),
932                                 one_to_two: DirectionalChannelInfo {
933                                         src_node_id: node3.clone(),
934                                         last_update: 0,
935                                         enabled: true,
936                                         cltv_expiry_delta: (6 << 8) | 1,
937                                         htlc_minimum_msat: 0,
938                                         fee_base_msat: 0,
939                                         fee_proportional_millionths: 0,
940                                 }, two_to_one: DirectionalChannelInfo {
941                                         src_node_id: node5.clone(),
942                                         last_update: 0,
943                                         enabled: true,
944                                         cltv_expiry_delta: (6 << 8) | 2,
945                                         htlc_minimum_msat: 0,
946                                         fee_base_msat: 0,
947                                         fee_proportional_millionths: 0,
948                                 },
949                         });
950                         network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
951                                 features: GlobalFeatures::new(),
952                                 one_to_two: DirectionalChannelInfo {
953                                         src_node_id: node5.clone(),
954                                         last_update: 0,
955                                         enabled: true,
956                                         cltv_expiry_delta: (11 << 8) | 1,
957                                         htlc_minimum_msat: 0,
958                                         fee_base_msat: 0,
959                                         fee_proportional_millionths: 0,
960                                 }, two_to_one: DirectionalChannelInfo {
961                                         src_node_id: node4.clone(),
962                                         last_update: 0,
963                                         enabled: true,
964                                         cltv_expiry_delta: (11 << 8) | 2,
965                                         htlc_minimum_msat: 0,
966                                         fee_base_msat: 0,
967                                         fee_proportional_millionths: 0,
968                                 },
969                         });
970                         network.nodes.insert(node6.clone(), NodeInfo {
971                                 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
972                                 lowest_inbound_channel_fee_base_msat: 0,
973                                 lowest_inbound_channel_fee_proportional_millionths: 0,
974                                 features: GlobalFeatures::new(),
975                                 last_update: 1,
976                                 rgb: [0; 3],
977                                 alias: [0; 32],
978                                 addresses: Vec::new(),
979                         });
980                         network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
981                                 features: GlobalFeatures::new(),
982                                 one_to_two: DirectionalChannelInfo {
983                                         src_node_id: node3.clone(),
984                                         last_update: 0,
985                                         enabled: true,
986                                         cltv_expiry_delta: (7 << 8) | 1,
987                                         htlc_minimum_msat: 0,
988                                         fee_base_msat: 0,
989                                         fee_proportional_millionths: 1000000,
990                                 }, two_to_one: DirectionalChannelInfo {
991                                         src_node_id: node6.clone(),
992                                         last_update: 0,
993                                         enabled: true,
994                                         cltv_expiry_delta: (7 << 8) | 2,
995                                         htlc_minimum_msat: 0,
996                                         fee_base_msat: 0,
997                                         fee_proportional_millionths: 0,
998                                 },
999                         });
1000                 }
1001
1002                 { // Simple route to 3 via 2
1003                         let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1004                         assert_eq!(route.hops.len(), 2);
1005
1006                         assert_eq!(route.hops[0].pubkey, node2);
1007                         assert_eq!(route.hops[0].short_channel_id, 2);
1008                         assert_eq!(route.hops[0].fee_msat, 100);
1009                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1010
1011                         assert_eq!(route.hops[1].pubkey, node3);
1012                         assert_eq!(route.hops[1].short_channel_id, 4);
1013                         assert_eq!(route.hops[1].fee_msat, 100);
1014                         assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1015                 }
1016
1017                 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1018                         let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1019                         assert_eq!(route.hops.len(), 3);
1020
1021                         assert_eq!(route.hops[0].pubkey, node2);
1022                         assert_eq!(route.hops[0].short_channel_id, 2);
1023                         assert_eq!(route.hops[0].fee_msat, 200);
1024                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1025
1026                         assert_eq!(route.hops[1].pubkey, node3);
1027                         assert_eq!(route.hops[1].short_channel_id, 4);
1028                         assert_eq!(route.hops[1].fee_msat, 100);
1029                         assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1030
1031                         assert_eq!(route.hops[2].pubkey, node1);
1032                         assert_eq!(route.hops[2].short_channel_id, 3);
1033                         assert_eq!(route.hops[2].fee_msat, 100);
1034                         assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1035                 }
1036
1037                 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1038                         let our_chans = vec![channelmanager::ChannelDetails {
1039                                 channel_id: [0; 32],
1040                                 short_channel_id: Some(42),
1041                                 remote_network_id: node8.clone(),
1042                                 channel_value_satoshis: 0,
1043                                 user_id: 0,
1044                         }];
1045                         let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1046                         assert_eq!(route.hops.len(), 2);
1047
1048                         assert_eq!(route.hops[0].pubkey, node8);
1049                         assert_eq!(route.hops[0].short_channel_id, 42);
1050                         assert_eq!(route.hops[0].fee_msat, 200);
1051                         assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1052
1053                         assert_eq!(route.hops[1].pubkey, node3);
1054                         assert_eq!(route.hops[1].short_channel_id, 13);
1055                         assert_eq!(route.hops[1].fee_msat, 100);
1056                         assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1057                 }
1058
1059                 let mut last_hops = vec!(RouteHint {
1060                                 src_node_id: node4.clone(),
1061                                 short_channel_id: 8,
1062                                 fee_base_msat: 0,
1063                                 fee_proportional_millionths: 0,
1064                                 cltv_expiry_delta: (8 << 8) | 1,
1065                                 htlc_minimum_msat: 0,
1066                         }, RouteHint {
1067                                 src_node_id: node5.clone(),
1068                                 short_channel_id: 9,
1069                                 fee_base_msat: 1001,
1070                                 fee_proportional_millionths: 0,
1071                                 cltv_expiry_delta: (9 << 8) | 1,
1072                                 htlc_minimum_msat: 0,
1073                         }, RouteHint {
1074                                 src_node_id: node6.clone(),
1075                                 short_channel_id: 10,
1076                                 fee_base_msat: 0,
1077                                 fee_proportional_millionths: 0,
1078                                 cltv_expiry_delta: (10 << 8) | 1,
1079                                 htlc_minimum_msat: 0,
1080                         });
1081
1082                 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1083                         let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1084                         assert_eq!(route.hops.len(), 5);
1085
1086                         assert_eq!(route.hops[0].pubkey, node2);
1087                         assert_eq!(route.hops[0].short_channel_id, 2);
1088                         assert_eq!(route.hops[0].fee_msat, 100);
1089                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1090
1091                         assert_eq!(route.hops[1].pubkey, node3);
1092                         assert_eq!(route.hops[1].short_channel_id, 4);
1093                         assert_eq!(route.hops[1].fee_msat, 0);
1094                         assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1095
1096                         assert_eq!(route.hops[2].pubkey, node5);
1097                         assert_eq!(route.hops[2].short_channel_id, 6);
1098                         assert_eq!(route.hops[2].fee_msat, 0);
1099                         assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1100
1101                         assert_eq!(route.hops[3].pubkey, node4);
1102                         assert_eq!(route.hops[3].short_channel_id, 11);
1103                         assert_eq!(route.hops[3].fee_msat, 0);
1104                         assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1105
1106                         assert_eq!(route.hops[4].pubkey, node7);
1107                         assert_eq!(route.hops[4].short_channel_id, 8);
1108                         assert_eq!(route.hops[4].fee_msat, 100);
1109                         assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1110                 }
1111
1112                 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1113                         let our_chans = vec![channelmanager::ChannelDetails {
1114                                 channel_id: [0; 32],
1115                                 short_channel_id: Some(42),
1116                                 remote_network_id: node4.clone(),
1117                                 channel_value_satoshis: 0,
1118                                 user_id: 0,
1119                         }];
1120                         let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1121                         assert_eq!(route.hops.len(), 2);
1122
1123                         assert_eq!(route.hops[0].pubkey, node4);
1124                         assert_eq!(route.hops[0].short_channel_id, 42);
1125                         assert_eq!(route.hops[0].fee_msat, 0);
1126                         assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1127
1128                         assert_eq!(route.hops[1].pubkey, node7);
1129                         assert_eq!(route.hops[1].short_channel_id, 8);
1130                         assert_eq!(route.hops[1].fee_msat, 100);
1131                         assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1132                 }
1133
1134                 last_hops[0].fee_base_msat = 1000;
1135
1136                 { // Revert to via 6 as the fee on 8 goes up
1137                         let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1138                         assert_eq!(route.hops.len(), 4);
1139
1140                         assert_eq!(route.hops[0].pubkey, node2);
1141                         assert_eq!(route.hops[0].short_channel_id, 2);
1142                         assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1143                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1144
1145                         assert_eq!(route.hops[1].pubkey, node3);
1146                         assert_eq!(route.hops[1].short_channel_id, 4);
1147                         assert_eq!(route.hops[1].fee_msat, 100);
1148                         assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1149
1150                         assert_eq!(route.hops[2].pubkey, node6);
1151                         assert_eq!(route.hops[2].short_channel_id, 7);
1152                         assert_eq!(route.hops[2].fee_msat, 0);
1153                         assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1154
1155                         assert_eq!(route.hops[3].pubkey, node7);
1156                         assert_eq!(route.hops[3].short_channel_id, 10);
1157                         assert_eq!(route.hops[3].fee_msat, 100);
1158                         assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1159                 }
1160
1161                 { // ...but still use 8 for larger payments as 6 has a variable feerate
1162                         let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1163                         assert_eq!(route.hops.len(), 5);
1164
1165                         assert_eq!(route.hops[0].pubkey, node2);
1166                         assert_eq!(route.hops[0].short_channel_id, 2);
1167                         assert_eq!(route.hops[0].fee_msat, 3000);
1168                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1169
1170                         assert_eq!(route.hops[1].pubkey, node3);
1171                         assert_eq!(route.hops[1].short_channel_id, 4);
1172                         assert_eq!(route.hops[1].fee_msat, 0);
1173                         assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1174
1175                         assert_eq!(route.hops[2].pubkey, node5);
1176                         assert_eq!(route.hops[2].short_channel_id, 6);
1177                         assert_eq!(route.hops[2].fee_msat, 0);
1178                         assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1179
1180                         assert_eq!(route.hops[3].pubkey, node4);
1181                         assert_eq!(route.hops[3].short_channel_id, 11);
1182                         assert_eq!(route.hops[3].fee_msat, 1000);
1183                         assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1184
1185                         assert_eq!(route.hops[4].pubkey, node7);
1186                         assert_eq!(route.hops[4].short_channel_id, 8);
1187                         assert_eq!(route.hops[4].fee_msat, 2000);
1188                         assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1189                 }
1190         }
1191 }