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