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