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