Handle only-path-overflows-fee in get_route and avoid PubKey::new()
[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: u32,
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         lowest_fee_to_node: u64,
307 }
308
309 impl cmp::Ord for RouteGraphNode {
310         fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
311                 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
312                         .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
313         }
314 }
315
316 impl cmp::PartialOrd for RouteGraphNode {
317         fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
318                 Some(self.cmp(other))
319         }
320 }
321
322 struct DummyDirectionalChannelInfo {
323         src_node_id: PublicKey,
324         cltv_expiry_delta: u32,
325         htlc_minimum_msat: u64,
326         fee_base_msat: u32,
327         fee_proportional_millionths: u32,
328 }
329
330 impl Router {
331         pub fn new(our_pubkey: PublicKey, logger: Arc<Logger>) -> Router {
332                 let mut nodes = HashMap::new();
333                 nodes.insert(our_pubkey.clone(), NodeInfo {
334                         channels: Vec::new(),
335                         lowest_inbound_channel_fee_base_msat: u32::max_value(),
336                         lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
337                         features: GlobalFeatures::new(),
338                         last_update: 0,
339                         rgb: [0; 3],
340                         alias: [0; 32],
341                         addresses: Vec::new(),
342                 });
343                 Router {
344                         secp_ctx: Secp256k1::new(),
345                         network_map: RwLock::new(NetworkMap {
346                                 channels: HashMap::new(),
347                                 our_node_id: our_pubkey,
348                                 nodes: nodes,
349                         }),
350                         logger,
351                 }
352         }
353
354         /// Get network addresses by node id
355         pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
356                 let network = self.network_map.read().unwrap();
357                 network.nodes.get(pubkey).map(|n| n.addresses.clone())
358         }
359
360         /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
361         /// with an expotnential decay in node "badness". Note that there is deliberately no
362         /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
363         /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
364         /// boolean will reduce the penalty, returning the node to usability faster. If the node is
365         /// behaving correctly, it will disable the failing channel and we will use it again next time.
366         pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
367                 unimplemented!();
368         }
369
370         /// Gets a route from us to the given target node.
371         /// Extra routing hops between known nodes and the target will be used if they are included in
372         /// last_hops.
373         /// If some channels aren't announced, it may be useful to fill in a first_hops with the
374         /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
375         /// (this Router's) view of our local channels will be ignored, and only those in first_hops
376         /// will be used. Panics if first_hops contains channels without short_channel_ids
377         /// (ChannelManager::list_usable_channels will never include such channels).
378         /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
379         /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
380         /// *is* checked as they may change based on the receiving node.
381         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> {
382                 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
383                 // uptime/success in using a node in the past.
384                 let network = self.network_map.read().unwrap();
385
386                 if *target == network.our_node_id {
387                         return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
388                 }
389
390                 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
391                         return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
392                 }
393
394                 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
395                 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
396                 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
397                 // to use as the A* heuristic beyond just the cost to get one node further than the current
398                 // one.
399
400                 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
401                         src_node_id: network.our_node_id.clone(),
402                         cltv_expiry_delta: 0,
403                         htlc_minimum_msat: 0,
404                         fee_base_msat: 0,
405                         fee_proportional_millionths: 0,
406                 };
407
408                 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
409                 let mut dist = HashMap::with_capacity(network.nodes.len());
410
411                 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
412                 if let Some(hops) = first_hops {
413                         for chan in hops {
414                                 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
415                                 if chan.remote_network_id == *target {
416                                         return Ok(Route {
417                                                 hops: vec![RouteHop {
418                                                         pubkey: chan.remote_network_id,
419                                                         short_channel_id,
420                                                         fee_msat: final_value_msat,
421                                                         cltv_expiry_delta: final_cltv,
422                                                 }],
423                                         });
424                                 }
425                                 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
426                         }
427                         if first_hop_targets.is_empty() {
428                                 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
429                         }
430                 }
431
432                 macro_rules! add_entry {
433                         // Adds entry which goes from the node pointed to by $directional_info to
434                         // $dest_node_id over the channel with id $chan_id with fees described in
435                         // $directional_info.
436                         ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
437                                 //TODO: Explore simply adding fee to hit htlc_minimum_msat
438                                 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
439                                         let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
440                                         if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
441                                                         ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
442                                         {
443                                                 let mut total_fee = $starting_fee_msat as u64;
444                                                 let hm_entry = dist.entry(&$directional_info.src_node_id);
445                                                 let old_entry = hm_entry.or_insert_with(|| {
446                                                         let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
447                                                         (u64::max_value(),
448                                                                 node.lowest_inbound_channel_fee_base_msat,
449                                                                 node.lowest_inbound_channel_fee_proportional_millionths,
450                                                                 RouteHop {
451                                                                         pubkey: $dest_node_id.clone(),
452                                                                         short_channel_id: 0,
453                                                                         fee_msat: 0,
454                                                                         cltv_expiry_delta: 0,
455                                                         })
456                                                 });
457                                                 if $directional_info.src_node_id != network.our_node_id {
458                                                         // Ignore new_fee for channel-from-us as we assume all channels-from-us
459                                                         // will have the same effective-fee
460                                                         total_fee += new_fee;
461                                                         if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
462                                                                 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
463                                                         } else {
464                                                                 // max_value means we'll always fail the old_entry.0 > total_fee check
465                                                                 total_fee = u64::max_value();
466                                                         }
467                                                 }
468                                                 let new_graph_node = RouteGraphNode {
469                                                         pubkey: $directional_info.src_node_id,
470                                                         lowest_fee_to_peer_through_node: total_fee,
471                                                         lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
472                                                 };
473                                                 if old_entry.0 > total_fee {
474                                                         targets.push(new_graph_node);
475                                                         old_entry.0 = total_fee;
476                                                         old_entry.3 = RouteHop {
477                                                                 pubkey: $dest_node_id.clone(),
478                                                                 short_channel_id: $chan_id.clone(),
479                                                                 fee_msat: new_fee, // This field is ignored on the last-hop anyway
480                                                                 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
481                                                         }
482                                                 }
483                                         }
484                                 }
485                         };
486                 }
487
488                 macro_rules! add_entries_to_cheapest_to_target_node {
489                         ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
490                                 if first_hops.is_some() {
491                                         if let Some(first_hop) = first_hop_targets.get(&$node_id) {
492                                                 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
493                                         }
494                                 }
495
496                                 for chan_id in $node.channels.iter() {
497                                         let chan = network.channels.get(chan_id).unwrap();
498                                         if chan.one_to_two.src_node_id == *$node_id {
499                                                 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
500                                                 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
501                                                         if chan.two_to_one.enabled {
502                                                                 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
503                                                         }
504                                                 }
505                                         } else {
506                                                 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
507                                                         if chan.one_to_two.enabled {
508                                                                 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
509                                                         }
510                                                 }
511                                         }
512                                 }
513                         };
514                 }
515
516                 match network.nodes.get(target) {
517                         None => {},
518                         Some(node) => {
519                                 add_entries_to_cheapest_to_target_node!(node, target, 0);
520                         },
521                 }
522
523                 for hop in last_hops.iter() {
524                         if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
525                                 if network.nodes.get(&hop.src_node_id).is_some() {
526                                         if first_hops.is_some() {
527                                                 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
528                                                         add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
529                                                 }
530                                         }
531                                         add_entry!(hop.short_channel_id, target, hop, 0);
532                                 }
533                         }
534                 }
535
536                 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
537                         if pubkey == network.our_node_id {
538                                 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
539                                 while res.last().unwrap().pubkey != *target {
540                                         let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
541                                                 Some(hop) => hop.3,
542                                                 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
543                                         };
544                                         res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
545                                         res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
546                                         res.push(new_entry);
547                                 }
548                                 res.last_mut().unwrap().fee_msat = final_value_msat;
549                                 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
550                                 return Ok(Route {
551                                         hops: res
552                                 });
553                         }
554
555                         match network.nodes.get(&pubkey) {
556                                 None => {},
557                                 Some(node) => {
558                                         add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
559                                 },
560                         }
561                 }
562
563                 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
564         }
565 }
566
567 #[cfg(test)]
568 mod tests {
569         use ln::channelmanager;
570         use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
571         use ln::msgs::GlobalFeatures;
572         use util::test_utils;
573         use util::logger::Logger;
574
575         use bitcoin::util::hash::Sha256dHash;
576
577         use hex;
578
579         use secp256k1::key::{PublicKey,SecretKey};
580         use secp256k1::Secp256k1;
581
582         use std::sync::Arc;
583
584         #[test]
585         fn route_test() {
586                 let secp_ctx = Secp256k1::new();
587                 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap()).unwrap();
588                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
589                 let router = Router::new(our_id, Arc::clone(&logger));
590
591                 // Build network from our_id to node8:
592                 //
593                 //        -1(1)2-  node1  -1(3)2-
594                 //       /                       \
595                 // our_id -1(12)2- node8 -1(13)2--- node3
596                 //       \                       /
597                 //        -1(2)2-  node2  -1(4)2-
598                 //
599                 //
600                 // chan1  1-to-2: disabled
601                 // chan1  2-to-1: enabled, 0 fee
602                 //
603                 // chan2  1-to-2: enabled, ignored fee
604                 // chan2  2-to-1: enabled, 0 fee
605                 //
606                 // chan3  1-to-2: enabled, 0 fee
607                 // chan3  2-to-1: enabled, 100 msat fee
608                 //
609                 // chan4  1-to-2: enabled, 100% fee
610                 // chan4  2-to-1: enabled, 0 fee
611                 //
612                 // chan12 1-to-2: enabled, ignored fee
613                 // chan12 2-to-1: enabled, 0 fee
614                 //
615                 // chan13 1-to-2: enabled, 200% fee
616                 // chan13 2-to-1: enabled, 0 fee
617                 //
618                 //
619                 //       -1(5)2- node4 -1(8)2--
620                 //       |         2          |
621                 //       |       (11)         |
622                 //      /          1           \
623                 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
624                 //      \                      /
625                 //       -1(7)2- node6 -1(10)2-
626                 //
627                 // chan5  1-to-2: enabled, 100 msat fee
628                 // chan5  2-to-1: enabled, 0 fee
629                 //
630                 // chan6  1-to-2: enabled, 0 fee
631                 // chan6  2-to-1: enabled, 0 fee
632                 //
633                 // chan7  1-to-2: enabled, 100% fee
634                 // chan7  2-to-1: enabled, 0 fee
635                 //
636                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
637                 // chan8  2-to-1: enabled, 0 fee
638                 //
639                 // chan9  1-to-2: enabled, 1001 msat fee
640                 // chan9  2-to-1: enabled, 0 fee
641                 //
642                 // chan10 1-to-2: enabled, 0 fee
643                 // chan10 2-to-1: enabled, 0 fee
644                 //
645                 // chan11 1-to-2: enabled, 0 fee
646                 // chan11 2-to-1: enabled, 0 fee
647
648                 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap()).unwrap();
649                 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap()).unwrap();
650                 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap()).unwrap();
651                 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap()).unwrap();
652                 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap()).unwrap();
653                 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap()).unwrap();
654                 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap()).unwrap();
655                 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap()).unwrap();
656
657                 let zero_hash = Sha256dHash::from_data(&[0; 32]);
658
659                 {
660                         let mut network = router.network_map.write().unwrap();
661
662                         network.nodes.insert(node1.clone(), NodeInfo {
663                                 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
664                                 lowest_inbound_channel_fee_base_msat: 100,
665                                 lowest_inbound_channel_fee_proportional_millionths: 0,
666                                 features: GlobalFeatures::new(),
667                                 last_update: 1,
668                                 rgb: [0; 3],
669                                 alias: [0; 32],
670                                 addresses: Vec::new(),
671                         });
672                         network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
673                                 features: GlobalFeatures::new(),
674                                 one_to_two: DirectionalChannelInfo {
675                                         src_node_id: our_id.clone(),
676                                         last_update: 0,
677                                         enabled: false,
678                                         cltv_expiry_delta: u16::max_value(), // This value should be ignored
679                                         htlc_minimum_msat: 0,
680                                         fee_base_msat: u32::max_value(), // This value should be ignored
681                                         fee_proportional_millionths: u32::max_value(), // This value should be ignored
682                                 }, two_to_one: DirectionalChannelInfo {
683                                         src_node_id: node1.clone(),
684                                         last_update: 0,
685                                         enabled: true,
686                                         cltv_expiry_delta: 0,
687                                         htlc_minimum_msat: 0,
688                                         fee_base_msat: 0,
689                                         fee_proportional_millionths: 0,
690                                 },
691                         });
692                         network.nodes.insert(node2.clone(), NodeInfo {
693                                 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
694                                 lowest_inbound_channel_fee_base_msat: 0,
695                                 lowest_inbound_channel_fee_proportional_millionths: 0,
696                                 features: GlobalFeatures::new(),
697                                 last_update: 1,
698                                 rgb: [0; 3],
699                                 alias: [0; 32],
700                                 addresses: Vec::new(),
701                         });
702                         network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
703                                 features: GlobalFeatures::new(),
704                                 one_to_two: DirectionalChannelInfo {
705                                         src_node_id: our_id.clone(),
706                                         last_update: 0,
707                                         enabled: true,
708                                         cltv_expiry_delta: u16::max_value(), // This value should be ignored
709                                         htlc_minimum_msat: 0,
710                                         fee_base_msat: u32::max_value(), // This value should be ignored
711                                         fee_proportional_millionths: u32::max_value(), // This value should be ignored
712                                 }, two_to_one: DirectionalChannelInfo {
713                                         src_node_id: node2.clone(),
714                                         last_update: 0,
715                                         enabled: true,
716                                         cltv_expiry_delta: 0,
717                                         htlc_minimum_msat: 0,
718                                         fee_base_msat: 0,
719                                         fee_proportional_millionths: 0,
720                                 },
721                         });
722                         network.nodes.insert(node8.clone(), NodeInfo {
723                                 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, 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(12, zero_hash.clone()), ChannelInfo {
733                                 features: GlobalFeatures::new(),
734                                 one_to_two: DirectionalChannelInfo {
735                                         src_node_id: our_id.clone(),
736                                         last_update: 0,
737                                         enabled: true,
738                                         cltv_expiry_delta: u16::max_value(), // This value should be ignored
739                                         htlc_minimum_msat: 0,
740                                         fee_base_msat: u32::max_value(), // This value should be ignored
741                                         fee_proportional_millionths: u32::max_value(), // This value should be ignored
742                                 }, two_to_one: DirectionalChannelInfo {
743                                         src_node_id: node8.clone(),
744                                         last_update: 0,
745                                         enabled: true,
746                                         cltv_expiry_delta: 0,
747                                         htlc_minimum_msat: 0,
748                                         fee_base_msat: 0,
749                                         fee_proportional_millionths: 0,
750                                 },
751                         });
752                         network.nodes.insert(node3.clone(), NodeInfo {
753                                 channels: vec!(
754                                         NetworkMap::get_key(3, zero_hash.clone()),
755                                         NetworkMap::get_key(4, zero_hash.clone()),
756                                         NetworkMap::get_key(13, zero_hash.clone()),
757                                         NetworkMap::get_key(5, zero_hash.clone()),
758                                         NetworkMap::get_key(6, zero_hash.clone()),
759                                         NetworkMap::get_key(7, zero_hash.clone())),
760                                 lowest_inbound_channel_fee_base_msat: 0,
761                                 lowest_inbound_channel_fee_proportional_millionths: 0,
762                                 features: GlobalFeatures::new(),
763                                 last_update: 1,
764                                 rgb: [0; 3],
765                                 alias: [0; 32],
766                                 addresses: Vec::new(),
767                         });
768                         network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
769                                 features: GlobalFeatures::new(),
770                                 one_to_two: DirectionalChannelInfo {
771                                         src_node_id: node1.clone(),
772                                         last_update: 0,
773                                         enabled: true,
774                                         cltv_expiry_delta: (3 << 8) | 1,
775                                         htlc_minimum_msat: 0,
776                                         fee_base_msat: 0,
777                                         fee_proportional_millionths: 0,
778                                 }, two_to_one: DirectionalChannelInfo {
779                                         src_node_id: node3.clone(),
780                                         last_update: 0,
781                                         enabled: true,
782                                         cltv_expiry_delta: (3 << 8) | 2,
783                                         htlc_minimum_msat: 0,
784                                         fee_base_msat: 100,
785                                         fee_proportional_millionths: 0,
786                                 },
787                         });
788                         network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
789                                 features: GlobalFeatures::new(),
790                                 one_to_two: DirectionalChannelInfo {
791                                         src_node_id: node2.clone(),
792                                         last_update: 0,
793                                         enabled: true,
794                                         cltv_expiry_delta: (4 << 8) | 1,
795                                         htlc_minimum_msat: 0,
796                                         fee_base_msat: 0,
797                                         fee_proportional_millionths: 1000000,
798                                 }, two_to_one: DirectionalChannelInfo {
799                                         src_node_id: node3.clone(),
800                                         last_update: 0,
801                                         enabled: true,
802                                         cltv_expiry_delta: (4 << 8) | 2,
803                                         htlc_minimum_msat: 0,
804                                         fee_base_msat: 0,
805                                         fee_proportional_millionths: 0,
806                                 },
807                         });
808                         network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
809                                 features: GlobalFeatures::new(),
810                                 one_to_two: DirectionalChannelInfo {
811                                         src_node_id: node8.clone(),
812                                         last_update: 0,
813                                         enabled: true,
814                                         cltv_expiry_delta: (13 << 8) | 1,
815                                         htlc_minimum_msat: 0,
816                                         fee_base_msat: 0,
817                                         fee_proportional_millionths: 2000000,
818                                 }, two_to_one: DirectionalChannelInfo {
819                                         src_node_id: node3.clone(),
820                                         last_update: 0,
821                                         enabled: true,
822                                         cltv_expiry_delta: (13 << 8) | 2,
823                                         htlc_minimum_msat: 0,
824                                         fee_base_msat: 0,
825                                         fee_proportional_millionths: 0,
826                                 },
827                         });
828                         network.nodes.insert(node4.clone(), NodeInfo {
829                                 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
830                                 lowest_inbound_channel_fee_base_msat: 0,
831                                 lowest_inbound_channel_fee_proportional_millionths: 0,
832                                 features: GlobalFeatures::new(),
833                                 last_update: 1,
834                                 rgb: [0; 3],
835                                 alias: [0; 32],
836                                 addresses: Vec::new(),
837                         });
838                         network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
839                                 features: GlobalFeatures::new(),
840                                 one_to_two: DirectionalChannelInfo {
841                                         src_node_id: node3.clone(),
842                                         last_update: 0,
843                                         enabled: true,
844                                         cltv_expiry_delta: (5 << 8) | 1,
845                                         htlc_minimum_msat: 0,
846                                         fee_base_msat: 100,
847                                         fee_proportional_millionths: 0,
848                                 }, two_to_one: DirectionalChannelInfo {
849                                         src_node_id: node4.clone(),
850                                         last_update: 0,
851                                         enabled: true,
852                                         cltv_expiry_delta: (5 << 8) | 2,
853                                         htlc_minimum_msat: 0,
854                                         fee_base_msat: 0,
855                                         fee_proportional_millionths: 0,
856                                 },
857                         });
858                         network.nodes.insert(node5.clone(), NodeInfo {
859                                 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
860                                 lowest_inbound_channel_fee_base_msat: 0,
861                                 lowest_inbound_channel_fee_proportional_millionths: 0,
862                                 features: GlobalFeatures::new(),
863                                 last_update: 1,
864                                 rgb: [0; 3],
865                                 alias: [0; 32],
866                                 addresses: Vec::new(),
867                         });
868                         network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
869                                 features: GlobalFeatures::new(),
870                                 one_to_two: DirectionalChannelInfo {
871                                         src_node_id: node3.clone(),
872                                         last_update: 0,
873                                         enabled: true,
874                                         cltv_expiry_delta: (6 << 8) | 1,
875                                         htlc_minimum_msat: 0,
876                                         fee_base_msat: 0,
877                                         fee_proportional_millionths: 0,
878                                 }, two_to_one: DirectionalChannelInfo {
879                                         src_node_id: node5.clone(),
880                                         last_update: 0,
881                                         enabled: true,
882                                         cltv_expiry_delta: (6 << 8) | 2,
883                                         htlc_minimum_msat: 0,
884                                         fee_base_msat: 0,
885                                         fee_proportional_millionths: 0,
886                                 },
887                         });
888                         network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
889                                 features: GlobalFeatures::new(),
890                                 one_to_two: DirectionalChannelInfo {
891                                         src_node_id: node5.clone(),
892                                         last_update: 0,
893                                         enabled: true,
894                                         cltv_expiry_delta: (11 << 8) | 1,
895                                         htlc_minimum_msat: 0,
896                                         fee_base_msat: 0,
897                                         fee_proportional_millionths: 0,
898                                 }, two_to_one: DirectionalChannelInfo {
899                                         src_node_id: node4.clone(),
900                                         last_update: 0,
901                                         enabled: true,
902                                         cltv_expiry_delta: (11 << 8) | 2,
903                                         htlc_minimum_msat: 0,
904                                         fee_base_msat: 0,
905                                         fee_proportional_millionths: 0,
906                                 },
907                         });
908                         network.nodes.insert(node6.clone(), NodeInfo {
909                                 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
910                                 lowest_inbound_channel_fee_base_msat: 0,
911                                 lowest_inbound_channel_fee_proportional_millionths: 0,
912                                 features: GlobalFeatures::new(),
913                                 last_update: 1,
914                                 rgb: [0; 3],
915                                 alias: [0; 32],
916                                 addresses: Vec::new(),
917                         });
918                         network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
919                                 features: GlobalFeatures::new(),
920                                 one_to_two: DirectionalChannelInfo {
921                                         src_node_id: node3.clone(),
922                                         last_update: 0,
923                                         enabled: true,
924                                         cltv_expiry_delta: (7 << 8) | 1,
925                                         htlc_minimum_msat: 0,
926                                         fee_base_msat: 0,
927                                         fee_proportional_millionths: 1000000,
928                                 }, two_to_one: DirectionalChannelInfo {
929                                         src_node_id: node6.clone(),
930                                         last_update: 0,
931                                         enabled: true,
932                                         cltv_expiry_delta: (7 << 8) | 2,
933                                         htlc_minimum_msat: 0,
934                                         fee_base_msat: 0,
935                                         fee_proportional_millionths: 0,
936                                 },
937                         });
938                 }
939
940                 { // Simple route to 3 via 2
941                         let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
942                         assert_eq!(route.hops.len(), 2);
943
944                         assert_eq!(route.hops[0].pubkey, node2);
945                         assert_eq!(route.hops[0].short_channel_id, 2);
946                         assert_eq!(route.hops[0].fee_msat, 100);
947                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
948
949                         assert_eq!(route.hops[1].pubkey, node3);
950                         assert_eq!(route.hops[1].short_channel_id, 4);
951                         assert_eq!(route.hops[1].fee_msat, 100);
952                         assert_eq!(route.hops[1].cltv_expiry_delta, 42);
953                 }
954
955                 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
956                         let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
957                         assert_eq!(route.hops.len(), 3);
958
959                         assert_eq!(route.hops[0].pubkey, node2);
960                         assert_eq!(route.hops[0].short_channel_id, 2);
961                         assert_eq!(route.hops[0].fee_msat, 200);
962                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
963
964                         assert_eq!(route.hops[1].pubkey, node3);
965                         assert_eq!(route.hops[1].short_channel_id, 4);
966                         assert_eq!(route.hops[1].fee_msat, 100);
967                         assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
968
969                         assert_eq!(route.hops[2].pubkey, node1);
970                         assert_eq!(route.hops[2].short_channel_id, 3);
971                         assert_eq!(route.hops[2].fee_msat, 100);
972                         assert_eq!(route.hops[2].cltv_expiry_delta, 42);
973                 }
974
975                 { // If we specify a channel to node8, that overrides our local channel view and that gets used
976                         let our_chans = vec![channelmanager::ChannelDetails {
977                                 channel_id: [0; 32],
978                                 short_channel_id: Some(42),
979                                 remote_network_id: node8.clone(),
980                                 channel_value_satoshis: 0,
981                                 user_id: 0,
982                         }];
983                         let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
984                         assert_eq!(route.hops.len(), 2);
985
986                         assert_eq!(route.hops[0].pubkey, node8);
987                         assert_eq!(route.hops[0].short_channel_id, 42);
988                         assert_eq!(route.hops[0].fee_msat, 200);
989                         assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
990
991                         assert_eq!(route.hops[1].pubkey, node3);
992                         assert_eq!(route.hops[1].short_channel_id, 13);
993                         assert_eq!(route.hops[1].fee_msat, 100);
994                         assert_eq!(route.hops[1].cltv_expiry_delta, 42);
995                 }
996
997                 let mut last_hops = vec!(RouteHint {
998                                 src_node_id: node4.clone(),
999                                 short_channel_id: 8,
1000                                 fee_base_msat: 0,
1001                                 fee_proportional_millionths: 0,
1002                                 cltv_expiry_delta: (8 << 8) | 1,
1003                                 htlc_minimum_msat: 0,
1004                         }, RouteHint {
1005                                 src_node_id: node5.clone(),
1006                                 short_channel_id: 9,
1007                                 fee_base_msat: 1001,
1008                                 fee_proportional_millionths: 0,
1009                                 cltv_expiry_delta: (9 << 8) | 1,
1010                                 htlc_minimum_msat: 0,
1011                         }, RouteHint {
1012                                 src_node_id: node6.clone(),
1013                                 short_channel_id: 10,
1014                                 fee_base_msat: 0,
1015                                 fee_proportional_millionths: 0,
1016                                 cltv_expiry_delta: (10 << 8) | 1,
1017                                 htlc_minimum_msat: 0,
1018                         });
1019
1020                 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1021                         let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1022                         assert_eq!(route.hops.len(), 5);
1023
1024                         assert_eq!(route.hops[0].pubkey, node2);
1025                         assert_eq!(route.hops[0].short_channel_id, 2);
1026                         assert_eq!(route.hops[0].fee_msat, 100);
1027                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1028
1029                         assert_eq!(route.hops[1].pubkey, node3);
1030                         assert_eq!(route.hops[1].short_channel_id, 4);
1031                         assert_eq!(route.hops[1].fee_msat, 0);
1032                         assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1033
1034                         assert_eq!(route.hops[2].pubkey, node5);
1035                         assert_eq!(route.hops[2].short_channel_id, 6);
1036                         assert_eq!(route.hops[2].fee_msat, 0);
1037                         assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1038
1039                         assert_eq!(route.hops[3].pubkey, node4);
1040                         assert_eq!(route.hops[3].short_channel_id, 11);
1041                         assert_eq!(route.hops[3].fee_msat, 0);
1042                         assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1043
1044                         assert_eq!(route.hops[4].pubkey, node7);
1045                         assert_eq!(route.hops[4].short_channel_id, 8);
1046                         assert_eq!(route.hops[4].fee_msat, 100);
1047                         assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1048                 }
1049
1050                 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1051                         let our_chans = vec![channelmanager::ChannelDetails {
1052                                 channel_id: [0; 32],
1053                                 short_channel_id: Some(42),
1054                                 remote_network_id: node4.clone(),
1055                                 channel_value_satoshis: 0,
1056                                 user_id: 0,
1057                         }];
1058                         let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1059                         assert_eq!(route.hops.len(), 2);
1060
1061                         assert_eq!(route.hops[0].pubkey, node4);
1062                         assert_eq!(route.hops[0].short_channel_id, 42);
1063                         assert_eq!(route.hops[0].fee_msat, 0);
1064                         assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1065
1066                         assert_eq!(route.hops[1].pubkey, node7);
1067                         assert_eq!(route.hops[1].short_channel_id, 8);
1068                         assert_eq!(route.hops[1].fee_msat, 100);
1069                         assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1070                 }
1071
1072                 last_hops[0].fee_base_msat = 1000;
1073
1074                 { // Revert to via 6 as the fee on 8 goes up
1075                         let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1076                         assert_eq!(route.hops.len(), 4);
1077
1078                         assert_eq!(route.hops[0].pubkey, node2);
1079                         assert_eq!(route.hops[0].short_channel_id, 2);
1080                         assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1081                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1082
1083                         assert_eq!(route.hops[1].pubkey, node3);
1084                         assert_eq!(route.hops[1].short_channel_id, 4);
1085                         assert_eq!(route.hops[1].fee_msat, 100);
1086                         assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1087
1088                         assert_eq!(route.hops[2].pubkey, node6);
1089                         assert_eq!(route.hops[2].short_channel_id, 7);
1090                         assert_eq!(route.hops[2].fee_msat, 0);
1091                         assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1092
1093                         assert_eq!(route.hops[3].pubkey, node7);
1094                         assert_eq!(route.hops[3].short_channel_id, 10);
1095                         assert_eq!(route.hops[3].fee_msat, 100);
1096                         assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1097                 }
1098
1099                 { // ...but still use 8 for larger payments as 6 has a variable feerate
1100                         let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1101                         assert_eq!(route.hops.len(), 5);
1102
1103                         assert_eq!(route.hops[0].pubkey, node2);
1104                         assert_eq!(route.hops[0].short_channel_id, 2);
1105                         assert_eq!(route.hops[0].fee_msat, 3000);
1106                         assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1107
1108                         assert_eq!(route.hops[1].pubkey, node3);
1109                         assert_eq!(route.hops[1].short_channel_id, 4);
1110                         assert_eq!(route.hops[1].fee_msat, 0);
1111                         assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1112
1113                         assert_eq!(route.hops[2].pubkey, node5);
1114                         assert_eq!(route.hops[2].short_channel_id, 6);
1115                         assert_eq!(route.hops[2].fee_msat, 0);
1116                         assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1117
1118                         assert_eq!(route.hops[3].pubkey, node4);
1119                         assert_eq!(route.hops[3].short_channel_id, 11);
1120                         assert_eq!(route.hops[3].fee_msat, 1000);
1121                         assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1122
1123                         assert_eq!(route.hops[4].pubkey, node7);
1124                         assert_eq!(route.hops[4].short_channel_id, 8);
1125                         assert_eq!(route.hops[4].fee_msat, 2000);
1126                         assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1127                 }
1128         }
1129 }