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