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