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