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