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