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