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