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