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