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