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