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