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