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