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