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