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