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