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