Generalize with_known_relevant_init_flags
[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 impl Writeable for Vec<RouteHop> {
51         fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
52                 (self.len() as u8).write(writer)?;
53                 for hop in self.iter() {
54                         hop.pubkey.write(writer)?;
55                         hop.node_features.write(writer)?;
56                         hop.short_channel_id.write(writer)?;
57                         hop.channel_features.write(writer)?;
58                         hop.fee_msat.write(writer)?;
59                         hop.cltv_expiry_delta.write(writer)?;
60                 }
61                 Ok(())
62         }
63 }
64
65 impl Readable for Vec<RouteHop> {
66         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
67                 let hops_count: u8 = Readable::read(reader)?;
68                 let mut hops = Vec::with_capacity(hops_count as usize);
69                 for _ in 0..hops_count {
70                         hops.push(RouteHop {
71                                 pubkey: Readable::read(reader)?,
72                                 node_features: Readable::read(reader)?,
73                                 short_channel_id: Readable::read(reader)?,
74                                 channel_features: Readable::read(reader)?,
75                                 fee_msat: Readable::read(reader)?,
76                                 cltv_expiry_delta: Readable::read(reader)?,
77                         });
78                 }
79                 Ok(hops)
80         }
81 }
82
83 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
84 /// it can take multiple paths. Each path is composed of one or more hops through the network.
85 #[derive(Clone, PartialEq)]
86 pub struct Route {
87         /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
88         /// last RouteHop in each path must be the same.
89         /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
90         /// destination. Thus, this must always be at least length one. While the maximum length of any
91         /// given path is variable, keeping the length of any path to less than 20 should currently
92         /// ensure it is viable.
93         pub paths: Vec<Vec<RouteHop>>,
94 }
95
96 impl Writeable for Route {
97         fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
98                 (self.paths.len() as u64).write(writer)?;
99                 for hops in self.paths.iter() {
100                         hops.write(writer)?;
101                 }
102                 Ok(())
103         }
104 }
105
106 impl Readable for Route {
107         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
108                 let path_count: u64 = Readable::read(reader)?;
109                 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
110                 for _ in 0..path_count {
111                         paths.push(Readable::read(reader)?);
112                 }
113                 Ok(Route { paths })
114         }
115 }
116
117 #[derive(PartialEq)]
118 struct DirectionalChannelInfo {
119         src_node_id: PublicKey,
120         last_update: u32,
121         enabled: bool,
122         cltv_expiry_delta: u16,
123         htlc_minimum_msat: u64,
124         fee_base_msat: u32,
125         fee_proportional_millionths: u32,
126         last_update_message: Option<msgs::ChannelUpdate>,
127 }
128
129 impl std::fmt::Display for DirectionalChannelInfo {
130         fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
131                 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)?;
132                 Ok(())
133         }
134 }
135
136 impl_writeable!(DirectionalChannelInfo, 0, {
137         src_node_id,
138         last_update,
139         enabled,
140         cltv_expiry_delta,
141         htlc_minimum_msat,
142         fee_base_msat,
143         fee_proportional_millionths,
144         last_update_message
145 });
146
147 #[derive(PartialEq)]
148 struct ChannelInfo {
149         features: ChannelFeatures,
150         one_to_two: DirectionalChannelInfo,
151         two_to_one: DirectionalChannelInfo,
152         //this is cached here so we can send out it later if required by route_init_sync
153         //keep an eye on this to see if the extra memory is a problem
154         announcement_message: Option<msgs::ChannelAnnouncement>,
155 }
156
157 impl std::fmt::Display for ChannelInfo {
158         fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
159                 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
160                 Ok(())
161         }
162 }
163
164 impl_writeable!(ChannelInfo, 0, {
165         features,
166         one_to_two,
167         two_to_one,
168         announcement_message
169 });
170
171 #[derive(PartialEq)]
172 struct NodeInfo {
173         #[cfg(feature = "non_bitcoin_chain_hash_routing")]
174         channels: Vec<(u64, Sha256dHash)>,
175         #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
176         channels: Vec<u64>,
177
178         lowest_inbound_channel_fee_base_msat: u32,
179         lowest_inbound_channel_fee_proportional_millionths: u32,
180
181         features: NodeFeatures,
182         /// Unlike for channels, we may have a NodeInfo entry before having received a node_update.
183         /// Thus, we have to be able to capture "no update has been received", which we do with an
184         /// Option here.
185         last_update: Option<u32>,
186         rgb: [u8; 3],
187         alias: [u8; 32],
188         addresses: Vec<NetAddress>,
189         //this is cached here so we can send out it later if required by route_init_sync
190         //keep an eye on this to see if the extra memory is a problem
191         announcement_message: Option<msgs::NodeAnnouncement>,
192 }
193
194 impl std::fmt::Display for NodeInfo {
195         fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
196                 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[..])?;
197                 Ok(())
198         }
199 }
200
201 impl Writeable for NodeInfo {
202         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
203                 (self.channels.len() as u64).write(writer)?;
204                 for ref chan in self.channels.iter() {
205                         chan.write(writer)?;
206                 }
207                 self.lowest_inbound_channel_fee_base_msat.write(writer)?;
208                 self.lowest_inbound_channel_fee_proportional_millionths.write(writer)?;
209                 self.features.write(writer)?;
210                 self.last_update.write(writer)?;
211                 self.rgb.write(writer)?;
212                 self.alias.write(writer)?;
213                 (self.addresses.len() as u64).write(writer)?;
214                 for ref addr in &self.addresses {
215                         addr.write(writer)?;
216                 }
217                 self.announcement_message.write(writer)?;
218                 Ok(())
219         }
220 }
221
222 const MAX_ALLOC_SIZE: u64 = 64*1024;
223
224 impl Readable for NodeInfo {
225         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
226                 let channels_count: u64 = Readable::read(reader)?;
227                 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
228                 for _ in 0..channels_count {
229                         channels.push(Readable::read(reader)?);
230                 }
231                 let lowest_inbound_channel_fee_base_msat = Readable::read(reader)?;
232                 let lowest_inbound_channel_fee_proportional_millionths = Readable::read(reader)?;
233                 let features = Readable::read(reader)?;
234                 let last_update = Readable::read(reader)?;
235                 let rgb = Readable::read(reader)?;
236                 let alias = Readable::read(reader)?;
237                 let addresses_count: u64 = Readable::read(reader)?;
238                 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
239                 for _ in 0..addresses_count {
240                         match Readable::read(reader) {
241                                 Ok(Ok(addr)) => { addresses.push(addr); },
242                                 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
243                                 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
244                                 _ => unreachable!(),
245                         }
246                 }
247                 let announcement_message = Readable::read(reader)?;
248                 Ok(NodeInfo {
249                         channels,
250                         lowest_inbound_channel_fee_base_msat,
251                         lowest_inbound_channel_fee_proportional_millionths,
252                         features,
253                         last_update,
254                         rgb,
255                         alias,
256                         addresses,
257                         announcement_message
258                 })
259         }
260 }
261
262 #[derive(PartialEq)]
263 struct NetworkMap {
264         #[cfg(feature = "non_bitcoin_chain_hash_routing")]
265         channels: BTreeMap<(u64, Sha256dHash), ChannelInfo>,
266         #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
267         channels: BTreeMap<u64, ChannelInfo>,
268
269         our_node_id: PublicKey,
270         nodes: BTreeMap<PublicKey, NodeInfo>,
271 }
272
273 impl Writeable for NetworkMap {
274         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
275                 (self.channels.len() as u64).write(writer)?;
276                 for (ref chan_id, ref chan_info) in self.channels.iter() {
277                         (*chan_id).write(writer)?;
278                         chan_info.write(writer)?;
279                 }
280                 self.our_node_id.write(writer)?;
281                 (self.nodes.len() as u64).write(writer)?;
282                 for (ref node_id, ref node_info) in self.nodes.iter() {
283                         node_id.write(writer)?;
284                         node_info.write(writer)?;
285                 }
286                 Ok(())
287         }
288 }
289
290 impl Readable for NetworkMap {
291         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkMap, DecodeError> {
292                 let channels_count: u64 = Readable::read(reader)?;
293                 let mut channels = BTreeMap::new();
294                 for _ in 0..channels_count {
295                         let chan_id: u64 = Readable::read(reader)?;
296                         let chan_info = Readable::read(reader)?;
297                         channels.insert(chan_id, chan_info);
298                 }
299                 let our_node_id = Readable::read(reader)?;
300                 let nodes_count: u64 = Readable::read(reader)?;
301                 let mut nodes = BTreeMap::new();
302                 for _ in 0..nodes_count {
303                         let node_id = Readable::read(reader)?;
304                         let node_info = Readable::read(reader)?;
305                         nodes.insert(node_id, node_info);
306                 }
307                 Ok(NetworkMap {
308                         channels,
309                         our_node_id,
310                         nodes,
311                 })
312         }
313 }
314
315 impl std::fmt::Display for NetworkMap {
316         fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
317                 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
318                 for (key, val) in self.channels.iter() {
319                         write!(f, " {}: {}\n", key, val)?;
320                 }
321                 write!(f, "[Nodes]\n")?;
322                 for (key, val) in self.nodes.iter() {
323                         write!(f, " {}: {}\n", log_pubkey!(key), val)?;
324                 }
325                 Ok(())
326         }
327 }
328
329 impl NetworkMap {
330         #[cfg(feature = "non_bitcoin_chain_hash_routing")]
331         #[inline]
332         fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
333                 (short_channel_id, chain_hash)
334         }
335
336         #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
337         #[inline]
338         fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
339                 short_channel_id
340         }
341
342         #[cfg(feature = "non_bitcoin_chain_hash_routing")]
343         #[inline]
344         fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
345                 &id.0
346         }
347
348         #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
349         #[inline]
350         fn get_short_id(id: &u64) -> &u64 {
351                 id
352         }
353 }
354
355 /// A channel descriptor which provides a last-hop route to get_route
356 pub struct RouteHint {
357         /// The node_id of the non-target end of the route
358         pub src_node_id: PublicKey,
359         /// The short_channel_id of this channel
360         pub short_channel_id: u64,
361         /// The static msat-denominated fee which must be paid to use this channel
362         pub fee_base_msat: u32,
363         /// The dynamic proportional fee which must be paid to use this channel, denominated in
364         /// millionths of the value being forwarded to the next hop.
365         pub fee_proportional_millionths: u32,
366         /// The difference in CLTV values between this node and the next node.
367         pub cltv_expiry_delta: u16,
368         /// The minimum value, in msat, which must be relayed to the next hop.
369         pub htlc_minimum_msat: u64,
370 }
371
372 /// Tracks a view of the network, receiving updates from peers and generating Routes to
373 /// payment destinations.
374 pub struct Router {
375         secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
376         network_map: RwLock<NetworkMap>,
377         full_syncs_requested: AtomicUsize,
378         chain_monitor: Arc<ChainWatchInterface>,
379         logger: Arc<Logger>,
380 }
381
382 const SERIALIZATION_VERSION: u8 = 1;
383 const MIN_SERIALIZATION_VERSION: u8 = 1;
384
385 impl Writeable for Router {
386         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
387                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
388                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
389
390                 let network = self.network_map.read().unwrap();
391                 network.write(writer)?;
392                 Ok(())
393         }
394 }
395
396 /// Arguments for the creation of a Router that are not deserialized.
397 /// At a high-level, the process for deserializing a Router and resuming normal operation is:
398 /// 1) Deserialize the Router by filling in this struct and calling <Router>::read(reaser, args).
399 /// 2) Register the new Router with your ChainWatchInterface
400 pub struct RouterReadArgs {
401         /// The ChainWatchInterface for use in the Router in the future.
402         ///
403         /// No calls to the ChainWatchInterface will be made during deserialization.
404         pub chain_monitor: Arc<ChainWatchInterface>,
405         /// The Logger for use in the ChannelManager and which may be used to log information during
406         /// deserialization.
407         pub logger: Arc<Logger>,
408 }
409
410 impl ReadableArgs<RouterReadArgs> for Router {
411         fn read<R: ::std::io::Read>(reader: &mut R, args: RouterReadArgs) -> Result<Router, DecodeError> {
412                 let _ver: u8 = Readable::read(reader)?;
413                 let min_ver: u8 = Readable::read(reader)?;
414                 if min_ver > SERIALIZATION_VERSION {
415                         return Err(DecodeError::UnknownVersion);
416                 }
417                 let network_map = Readable::read(reader)?;
418                 Ok(Router {
419                         secp_ctx: Secp256k1::verification_only(),
420                         network_map: RwLock::new(network_map),
421                         full_syncs_requested: AtomicUsize::new(0),
422                         chain_monitor: args.chain_monitor,
423                         logger: args.logger,
424                 })
425         }
426 }
427
428 macro_rules! secp_verify_sig {
429         ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
430                 match $secp_ctx.verify($msg, $sig, $pubkey) {
431                         Ok(_) => {},
432                         Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
433                 }
434         };
435 }
436
437 impl RoutingMessageHandler for Router {
438
439         fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
440                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
441                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
442
443                 let mut network = self.network_map.write().unwrap();
444                 match network.nodes.get_mut(&msg.contents.node_id) {
445                         None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
446                         Some(node) => {
447                                 match node.last_update {
448                                         Some(last_update) => if last_update >= msg.contents.timestamp {
449                                                 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
450                                         },
451                                         None => {},
452                                 }
453
454                                 node.features = msg.contents.features.clone();
455                                 node.last_update = Some(msg.contents.timestamp);
456                                 node.rgb = msg.contents.rgb;
457                                 node.alias = msg.contents.alias;
458                                 node.addresses = msg.contents.addresses.clone();
459
460                                 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
461                                 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
462                                 Ok(should_relay)
463                         }
464                 }
465         }
466
467         fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
468                 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
469                         return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
470                 }
471
472                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
473                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
474                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
475                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
476                 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
477
478                 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
479                         Ok((script_pubkey, _value)) => {
480                                 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
481                                                                     .push_slice(&msg.contents.bitcoin_key_1.serialize())
482                                                                     .push_slice(&msg.contents.bitcoin_key_2.serialize())
483                                                                     .push_opcode(opcodes::all::OP_PUSHNUM_2)
484                                                                     .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
485                                 if script_pubkey != expected_script {
486                                         return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
487                                 }
488                                 //TODO: Check if value is worth storing, use it to inform routing, and compare it
489                                 //to the new HTLC max field in channel_update
490                                 true
491                         },
492                         Err(ChainError::NotSupported) => {
493                                 // Tentatively accept, potentially exposing us to DoS attacks
494                                 false
495                         },
496                         Err(ChainError::NotWatched) => {
497                                 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
498                         },
499                         Err(ChainError::UnknownTx) => {
500                                 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
501                         },
502                 };
503
504                 let mut network_lock = self.network_map.write().unwrap();
505                 let network = &mut *network_lock;
506
507                 let should_relay = msg.contents.excess_data.is_empty();
508
509                 let chan_info = ChannelInfo {
510                                 features: msg.contents.features.clone(),
511                                 one_to_two: DirectionalChannelInfo {
512                                         src_node_id: msg.contents.node_id_1.clone(),
513                                         last_update: 0,
514                                         enabled: false,
515                                         cltv_expiry_delta: u16::max_value(),
516                                         htlc_minimum_msat: u64::max_value(),
517                                         fee_base_msat: u32::max_value(),
518                                         fee_proportional_millionths: u32::max_value(),
519                                         last_update_message: None,
520                                 },
521                                 two_to_one: DirectionalChannelInfo {
522                                         src_node_id: msg.contents.node_id_2.clone(),
523                                         last_update: 0,
524                                         enabled: false,
525                                         cltv_expiry_delta: u16::max_value(),
526                                         htlc_minimum_msat: u64::max_value(),
527                                         fee_base_msat: u32::max_value(),
528                                         fee_proportional_millionths: u32::max_value(),
529                                         last_update_message: None,
530                                 },
531                                 announcement_message: if should_relay { Some(msg.clone()) } else { None },
532                         };
533
534                 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
535                         BtreeEntry::Occupied(mut entry) => {
536                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
537                                 //in the blockchain API, we need to handle it smartly here, though it's unclear
538                                 //exactly how...
539                                 if checked_utxo {
540                                         // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
541                                         // only sometimes returns results. In any case remove the previous entry. Note
542                                         // that the spec expects us to "blacklist" the node_ids involved, but we can't
543                                         // do that because
544                                         // a) we don't *require* a UTXO provider that always returns results.
545                                         // b) we don't track UTXOs of channels we know about and remove them if they
546                                         //    get reorg'd out.
547                                         // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
548                                         Self::remove_channel_in_nodes(&mut network.nodes, &entry.get(), msg.contents.short_channel_id);
549                                         *entry.get_mut() = chan_info;
550                                 } else {
551                                         return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
552                                 }
553                         },
554                         BtreeEntry::Vacant(entry) => {
555                                 entry.insert(chan_info);
556                         }
557                 };
558
559                 macro_rules! add_channel_to_node {
560                         ( $node_id: expr ) => {
561                                 match network.nodes.entry($node_id) {
562                                         BtreeEntry::Occupied(node_entry) => {
563                                                 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
564                                         },
565                                         BtreeEntry::Vacant(node_entry) => {
566                                                 node_entry.insert(NodeInfo {
567                                                         channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
568                                                         lowest_inbound_channel_fee_base_msat: u32::max_value(),
569                                                         lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
570                                                         features: NodeFeatures::empty(),
571                                                         last_update: None,
572                                                         rgb: [0; 3],
573                                                         alias: [0; 32],
574                                                         addresses: Vec::new(),
575                                                         announcement_message: None,
576                                                 });
577                                         }
578                                 }
579                         };
580                 }
581
582                 add_channel_to_node!(msg.contents.node_id_1);
583                 add_channel_to_node!(msg.contents.node_id_2);
584
585                 log_trace!(self, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !should_relay { " with excess uninterpreted data!" } else { "" });
586                 Ok(should_relay)
587         }
588
589         fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
590                 match update {
591                         &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
592                                 let _ = self.handle_channel_update(msg);
593                         },
594                         &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
595                                 let mut network = self.network_map.write().unwrap();
596                                 if *is_permanent {
597                                         if let Some(chan) = network.channels.remove(short_channel_id) {
598                                                 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
599                                         }
600                                 } else {
601                                         if let Some(chan) = network.channels.get_mut(short_channel_id) {
602                                                 chan.one_to_two.enabled = false;
603                                                 chan.two_to_one.enabled = false;
604                                         }
605                                 }
606                         },
607                         &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
608                                 if *is_permanent {
609                                         //TODO: Wholly remove the node
610                                 } else {
611                                         self.mark_node_bad(node_id, false);
612                                 }
613                         },
614                 }
615         }
616
617         fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
618                 let mut network = self.network_map.write().unwrap();
619                 let dest_node_id;
620                 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
621                 let chan_was_enabled;
622
623                 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
624                         None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
625                         Some(channel) => {
626                                 macro_rules! maybe_update_channel_info {
627                                         ( $target: expr) => {
628                                                 if $target.last_update >= msg.contents.timestamp {
629                                                         return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
630                                                 }
631                                                 chan_was_enabled = $target.enabled;
632                                                 $target.last_update = msg.contents.timestamp;
633                                                 $target.enabled = chan_enabled;
634                                                 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
635                                                 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
636                                                 $target.fee_base_msat = msg.contents.fee_base_msat;
637                                                 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
638                                                 $target.last_update_message = if msg.contents.excess_data.is_empty() {
639                                                         Some(msg.clone())
640                                                 } else {
641                                                         None
642                                                 };
643                                         }
644                                 }
645                                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
646                                 if msg.contents.flags & 1 == 1 {
647                                         dest_node_id = channel.one_to_two.src_node_id.clone();
648                                         secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
649                                         maybe_update_channel_info!(channel.two_to_one);
650                                 } else {
651                                         dest_node_id = channel.two_to_one.src_node_id.clone();
652                                         secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
653                                         maybe_update_channel_info!(channel.one_to_two);
654                                 }
655                         }
656                 }
657
658                 if chan_enabled {
659                         let node = network.nodes.get_mut(&dest_node_id).unwrap();
660                         node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
661                         node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
662                 } else if chan_was_enabled {
663                         let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
664                         let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
665
666                         {
667                                 let node = network.nodes.get(&dest_node_id).unwrap();
668
669                                 for chan_id in node.channels.iter() {
670                                         let chan = network.channels.get(chan_id).unwrap();
671                                         if chan.one_to_two.src_node_id == dest_node_id {
672                                                 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
673                                                 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
674                                         } else {
675                                                 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
676                                                 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
677                                         }
678                                 }
679                         }
680
681                         //TODO: satisfy the borrow-checker without a double-map-lookup :(
682                         let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
683                         mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
684                         mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
685                 }
686
687                 Ok(msg.contents.excess_data.is_empty())
688         }
689
690         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
691                 let mut result = Vec::with_capacity(batch_amount as usize);
692                 let network = self.network_map.read().unwrap();
693                 let mut iter = network.channels.range(starting_point..);
694                 while result.len() < batch_amount as usize {
695                         if let Some((_, ref chan)) = iter.next() {
696                                 if chan.announcement_message.is_some() {
697                                         result.push((chan.announcement_message.clone().unwrap(),
698                                                 chan.one_to_two.last_update_message.clone(),
699                                                 chan.two_to_one.last_update_message.clone()));
700                                 } else {
701                                         // TODO: We may end up sending un-announced channel_updates if we are sending
702                                         // initial sync data while receiving announce/updates for this channel.
703                                 }
704                         } else {
705                                 return result;
706                         }
707                 }
708                 result
709         }
710
711         fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
712                 let mut result = Vec::with_capacity(batch_amount as usize);
713                 let network = self.network_map.read().unwrap();
714                 let mut iter = if let Some(pubkey) = starting_point {
715                                 let mut iter = network.nodes.range((*pubkey)..);
716                                 iter.next();
717                                 iter
718                         } else {
719                                 network.nodes.range(..)
720                         };
721                 while result.len() < batch_amount as usize {
722                         if let Some((_, ref node)) = iter.next() {
723                                 if node.announcement_message.is_some() {
724                                         result.push(node.announcement_message.clone().unwrap());
725                                 }
726                         } else {
727                                 return result;
728                         }
729                 }
730                 result
731         }
732
733         fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
734                 //TODO: Determine whether to request a full sync based on the network map.
735                 const FULL_SYNCS_TO_REQUEST: usize = 5;
736                 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
737                         self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
738                         true
739                 } else {
740                         false
741                 }
742         }
743 }
744
745 #[derive(Eq, PartialEq)]
746 struct RouteGraphNode {
747         pubkey: PublicKey,
748         lowest_fee_to_peer_through_node: u64,
749         lowest_fee_to_node: u64,
750 }
751
752 impl cmp::Ord for RouteGraphNode {
753         fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
754                 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
755                         .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
756         }
757 }
758
759 impl cmp::PartialOrd for RouteGraphNode {
760         fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
761                 Some(self.cmp(other))
762         }
763 }
764
765 struct DummyDirectionalChannelInfo {
766         src_node_id: PublicKey,
767         cltv_expiry_delta: u32,
768         htlc_minimum_msat: u64,
769         fee_base_msat: u32,
770         fee_proportional_millionths: u32,
771 }
772
773 impl Router {
774         /// Creates a new router with the given node_id to be used as the source for get_route()
775         pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
776                 let mut nodes = BTreeMap::new();
777                 nodes.insert(our_pubkey.clone(), NodeInfo {
778                         channels: Vec::new(),
779                         lowest_inbound_channel_fee_base_msat: u32::max_value(),
780                         lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
781                         features: NodeFeatures::empty(),
782                         last_update: None,
783                         rgb: [0; 3],
784                         alias: [0; 32],
785                         addresses: Vec::new(),
786                         announcement_message: None,
787                 });
788                 Router {
789                         secp_ctx: Secp256k1::verification_only(),
790                         network_map: RwLock::new(NetworkMap {
791                                 channels: BTreeMap::new(),
792                                 our_node_id: our_pubkey,
793                                 nodes: nodes,
794                         }),
795                         full_syncs_requested: AtomicUsize::new(0),
796                         chain_monitor,
797                         logger,
798                 }
799         }
800
801         /// Dumps the entire network view of this Router to the logger provided in the constructor at
802         /// level Trace
803         pub fn trace_state(&self) {
804                 log_trace!(self, "{}", self.network_map.read().unwrap());
805         }
806
807         /// Get network addresses by node id
808         pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
809                 let network = self.network_map.read().unwrap();
810                 network.nodes.get(pubkey).map(|n| n.addresses.clone())
811         }
812
813         /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
814         /// with an exponential decay in node "badness". Note that there is deliberately no
815         /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
816         /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
817         /// boolean will reduce the penalty, returning the node to usability faster. If the node is
818         /// behaving correctly, it will disable the failing channel and we will use it again next time.
819         pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
820                 unimplemented!();
821         }
822
823         fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
824                 macro_rules! remove_from_node {
825                         ($node_id: expr) => {
826                                 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
827                                         entry.get_mut().channels.retain(|chan_id| {
828                                                 short_channel_id != *NetworkMap::get_short_id(chan_id)
829                                         });
830                                         if entry.get().channels.is_empty() {
831                                                 entry.remove_entry();
832                                         }
833                                 } else {
834                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
835                                 }
836                         }
837                 }
838                 remove_from_node!(chan.one_to_two.src_node_id);
839                 remove_from_node!(chan.two_to_one.src_node_id);
840         }
841
842         /// Gets a route from us to the given target node.
843         ///
844         /// Extra routing hops between known nodes and the target will be used if they are included in
845         /// last_hops.
846         ///
847         /// If some channels aren't announced, it may be useful to fill in a first_hops with the
848         /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
849         /// (this Router's) view of our local channels will be ignored, and only those in first_hops
850         /// will be used.
851         ///
852         /// Panics if first_hops contains channels without short_channel_ids
853         /// (ChannelManager::list_usable_channels will never include such channels).
854         ///
855         /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
856         /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
857         /// *is* checked as they may change based on the receiving node.
858         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> {
859                 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
860                 // uptime/success in using a node in the past.
861                 let network = self.network_map.read().unwrap();
862
863                 if *target == network.our_node_id {
864                         return Err(LightningError{err: "Cannot generate a route to ourselves", action: ErrorAction::IgnoreError});
865                 }
866
867                 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
868                         return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis", action: ErrorAction::IgnoreError});
869                 }
870
871                 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
872                 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
873                 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
874                 // to use as the A* heuristic beyond just the cost to get one node further than the current
875                 // one.
876
877                 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
878                         src_node_id: network.our_node_id.clone(),
879                         cltv_expiry_delta: 0,
880                         htlc_minimum_msat: 0,
881                         fee_base_msat: 0,
882                         fee_proportional_millionths: 0,
883                 };
884
885                 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
886                 let mut dist = HashMap::with_capacity(network.nodes.len());
887
888                 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
889                 if let Some(hops) = first_hops {
890                         for chan in hops {
891                                 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
892                                 if chan.remote_network_id == *target {
893                                         return Ok(Route {
894                                                 paths: vec![vec![RouteHop {
895                                                         pubkey: chan.remote_network_id,
896                                                         node_features: chan.counterparty_features.to_context(),
897                                                         short_channel_id,
898                                                         channel_features: chan.counterparty_features.to_context(),
899                                                         fee_msat: final_value_msat,
900                                                         cltv_expiry_delta: final_cltv,
901                                                 }]],
902                                         });
903                                 }
904                                 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone()));
905                         }
906                         if first_hop_targets.is_empty() {
907                                 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us", action: ErrorAction::IgnoreError});
908                         }
909                 }
910
911                 macro_rules! add_entry {
912                         // Adds entry which goes from the node pointed to by $directional_info to
913                         // $dest_node_id over the channel with id $chan_id with fees described in
914                         // $directional_info.
915                         ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $chan_features: expr, $starting_fee_msat: expr ) => {
916                                 //TODO: Explore simply adding fee to hit htlc_minimum_msat
917                                 if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
918                                         let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
919                                         if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
920                                                         ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
921                                         {
922                                                 let mut total_fee = $starting_fee_msat as u64;
923                                                 let hm_entry = dist.entry(&$directional_info.src_node_id);
924                                                 let old_entry = hm_entry.or_insert_with(|| {
925                                                         let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
926                                                         (u64::max_value(),
927                                                                 node.lowest_inbound_channel_fee_base_msat,
928                                                                 node.lowest_inbound_channel_fee_proportional_millionths,
929                                                                 RouteHop {
930                                                                         pubkey: $dest_node_id.clone(),
931                                                                         node_features: NodeFeatures::empty(),
932                                                                         short_channel_id: 0,
933                                                                         channel_features: $chan_features.clone(),
934                                                                         fee_msat: 0,
935                                                                         cltv_expiry_delta: 0,
936                                                         })
937                                                 });
938                                                 if $directional_info.src_node_id != network.our_node_id {
939                                                         // Ignore new_fee for channel-from-us as we assume all channels-from-us
940                                                         // will have the same effective-fee
941                                                         total_fee += new_fee;
942                                                         if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
943                                                                 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
944                                                         } else {
945                                                                 // max_value means we'll always fail the old_entry.0 > total_fee check
946                                                                 total_fee = u64::max_value();
947                                                         }
948                                                 }
949                                                 let new_graph_node = RouteGraphNode {
950                                                         pubkey: $directional_info.src_node_id,
951                                                         lowest_fee_to_peer_through_node: total_fee,
952                                                         lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
953                                                 };
954                                                 if old_entry.0 > total_fee {
955                                                         targets.push(new_graph_node);
956                                                         old_entry.0 = total_fee;
957                                                         old_entry.3 = RouteHop {
958                                                                 pubkey: $dest_node_id.clone(),
959                                                                 node_features: NodeFeatures::empty(),
960                                                                 short_channel_id: $chan_id.clone(),
961                                                                 channel_features: $chan_features.clone(),
962                                                                 fee_msat: new_fee, // This field is ignored on the last-hop anyway
963                                                                 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
964                                                         }
965                                                 }
966                                         }
967                                 }
968                         };
969                 }
970
971                 macro_rules! add_entries_to_cheapest_to_target_node {
972                         ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
973                                 if first_hops.is_some() {
974                                         if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&$node_id) {
975                                                 add_entry!(first_hop, $node_id, dummy_directional_info, features.to_context(), $fee_to_target_msat);
976                                         }
977                                 }
978
979                                 if !$node.features.requires_unknown_bits() {
980                                         for chan_id in $node.channels.iter() {
981                                                 let chan = network.channels.get(chan_id).unwrap();
982                                                 if !chan.features.requires_unknown_bits() {
983                                                         if chan.one_to_two.src_node_id == *$node_id {
984                                                                 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
985                                                                 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
986                                                                         if chan.two_to_one.enabled {
987                                                                                 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, chan.features, $fee_to_target_msat);
988                                                                         }
989                                                                 }
990                                                         } else {
991                                                                 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
992                                                                         if chan.one_to_two.enabled {
993                                                                                 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, chan.features, $fee_to_target_msat);
994                                                                         }
995                                                                 }
996                                                         }
997                                                 }
998                                         }
999                                 }
1000                         };
1001                 }
1002
1003                 match network.nodes.get(target) {
1004                         None => {},
1005                         Some(node) => {
1006                                 add_entries_to_cheapest_to_target_node!(node, target, 0);
1007                         },
1008                 }
1009
1010                 for hop in last_hops.iter() {
1011                         if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
1012                                 if network.nodes.get(&hop.src_node_id).is_some() {
1013                                         if first_hops.is_some() {
1014                                                 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&hop.src_node_id) {
1015                                                         // Currently there are no channel-context features defined, so we are a
1016                                                         // bit lazy here. In the future, we should pull them out via our
1017                                                         // ChannelManager, but there's no reason to waste the space until we
1018                                                         // need them.
1019                                                         add_entry!(first_hop, hop.src_node_id, dummy_directional_info, features.to_context(), 0);
1020                                                 }
1021                                         }
1022                                         // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
1023                                         // really sucks, cause we're gonna need that eventually.
1024                                         add_entry!(hop.short_channel_id, target, hop, ChannelFeatures::empty(), 0);
1025                                 }
1026                         }
1027                 }
1028
1029                 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
1030                         if pubkey == network.our_node_id {
1031                                 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
1032                                 loop {
1033                                         if let Some(&(_, ref features)) = first_hop_targets.get(&res.last().unwrap().pubkey) {
1034                                                 res.last_mut().unwrap().node_features = features.to_context();
1035                                         } else if let Some(node) = network.nodes.get(&res.last().unwrap().pubkey) {
1036                                                 res.last_mut().unwrap().node_features = node.features.clone();
1037                                         } else {
1038                                                 // We should be able to fill in features for everything except the last
1039                                                 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1040                                                 // should be able to extend it further as BOLT 11 does have feature
1041                                                 // flags for the last hop node itself).
1042                                                 assert!(res.last().unwrap().pubkey == *target);
1043                                         }
1044                                         if res.last().unwrap().pubkey == *target {
1045                                                 break;
1046                                         }
1047
1048                                         let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
1049                                                 Some(hop) => hop.3,
1050                                                 None => return Err(LightningError{err: "Failed to find a non-fee-overflowing path to the given destination", action: ErrorAction::IgnoreError}),
1051                                         };
1052                                         res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
1053                                         res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
1054                                         res.push(new_entry);
1055                                 }
1056                                 res.last_mut().unwrap().fee_msat = final_value_msat;
1057                                 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
1058                                 let route = Route { paths: vec![res] };
1059                                 log_trace!(self, "Got route: {}", log_route!(route));
1060                                 return Ok(route);
1061                         }
1062
1063                         match network.nodes.get(&pubkey) {
1064                                 None => {},
1065                                 Some(node) => {
1066                                         add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
1067                                 },
1068                         }
1069                 }
1070
1071                 Err(LightningError{err: "Failed to find a path to the given destination", action: ErrorAction::IgnoreError})
1072         }
1073 }
1074
1075 #[cfg(test)]
1076 mod tests {
1077         use chain::chaininterface;
1078         use ln::channelmanager;
1079         use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
1080         use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1081         use ln::msgs::{ErrorAction, LightningError, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1082            UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
1083         use util::test_utils;
1084         use util::test_utils::TestVecWriter;
1085         use util::logger::Logger;
1086         use util::ser::{Writeable, Readable};
1087
1088         use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1089         use bitcoin_hashes::Hash;
1090         use bitcoin::network::constants::Network;
1091         use bitcoin::blockdata::constants::genesis_block;
1092         use bitcoin::blockdata::script::Builder;
1093         use bitcoin::blockdata::opcodes;
1094         use bitcoin::util::hash::BitcoinHash;
1095
1096         use hex;
1097
1098         use secp256k1::key::{PublicKey,SecretKey};
1099         use secp256k1::All;
1100         use secp256k1::Secp256k1;
1101
1102         use std::sync::Arc;
1103         use std::collections::btree_map::Entry as BtreeEntry;
1104
1105         fn create_router() -> (Secp256k1<All>, PublicKey, Router) {
1106                 let secp_ctx = Secp256k1::new();
1107                 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
1108                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1109                 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
1110                 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
1111                 (secp_ctx, our_id, router)
1112         }
1113
1114         #[test]
1115         fn route_test() {
1116                 let (secp_ctx, our_id, router) = create_router();
1117
1118                 // Build network from our_id to node8:
1119                 //
1120                 //        -1(1)2-  node1  -1(3)2-
1121                 //       /                       \
1122                 // our_id -1(12)2- node8 -1(13)2--- node3
1123                 //       \                       /
1124                 //        -1(2)2-  node2  -1(4)2-
1125                 //
1126                 //
1127                 // chan1  1-to-2: disabled
1128                 // chan1  2-to-1: enabled, 0 fee
1129                 //
1130                 // chan2  1-to-2: enabled, ignored fee
1131                 // chan2  2-to-1: enabled, 0 fee
1132                 //
1133                 // chan3  1-to-2: enabled, 0 fee
1134                 // chan3  2-to-1: enabled, 100 msat fee
1135                 //
1136                 // chan4  1-to-2: enabled, 100% fee
1137                 // chan4  2-to-1: enabled, 0 fee
1138                 //
1139                 // chan12 1-to-2: enabled, ignored fee
1140                 // chan12 2-to-1: enabled, 0 fee
1141                 //
1142                 // chan13 1-to-2: enabled, 200% fee
1143                 // chan13 2-to-1: enabled, 0 fee
1144                 //
1145                 //
1146                 //       -1(5)2- node4 -1(8)2--
1147                 //       |         2          |
1148                 //       |       (11)         |
1149                 //      /          1           \
1150                 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
1151                 //      \                      /
1152                 //       -1(7)2- node6 -1(10)2-
1153                 //
1154                 // chan5  1-to-2: enabled, 100 msat fee
1155                 // chan5  2-to-1: enabled, 0 fee
1156                 //
1157                 // chan6  1-to-2: enabled, 0 fee
1158                 // chan6  2-to-1: enabled, 0 fee
1159                 //
1160                 // chan7  1-to-2: enabled, 100% fee
1161                 // chan7  2-to-1: enabled, 0 fee
1162                 //
1163                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
1164                 // chan8  2-to-1: enabled, 0 fee
1165                 //
1166                 // chan9  1-to-2: enabled, 1001 msat fee
1167                 // chan9  2-to-1: enabled, 0 fee
1168                 //
1169                 // chan10 1-to-2: enabled, 0 fee
1170                 // chan10 2-to-1: enabled, 0 fee
1171                 //
1172                 // chan11 1-to-2: enabled, 0 fee
1173                 // chan11 2-to-1: enabled, 0 fee
1174
1175                 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1176                 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
1177                 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
1178                 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
1179                 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
1180                 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
1181                 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
1182                 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
1183
1184                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1185
1186                 macro_rules! id_to_feature_flags {
1187                         // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1188                         // test for it later.
1189                         ($id: expr) => { {
1190                                 let idx = ($id - 1) * 2 + 1;
1191                                 if idx > 8*3 {
1192                                         vec![1 << (idx - 8*3), 0, 0, 0]
1193                                 } else if idx > 8*2 {
1194                                         vec![1 << (idx - 8*2), 0, 0]
1195                                 } else if idx > 8*1 {
1196                                         vec![1 << (idx - 8*1), 0]
1197                                 } else {
1198                                         vec![1 << idx]
1199                                 }
1200                         } }
1201                 }
1202
1203                 {
1204                         let mut network = router.network_map.write().unwrap();
1205
1206                         network.nodes.insert(node1.clone(), NodeInfo {
1207                                 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
1208                                 lowest_inbound_channel_fee_base_msat: 100,
1209                                 lowest_inbound_channel_fee_proportional_millionths: 0,
1210                                 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(1)),
1211                                 last_update: Some(1),
1212                                 rgb: [0; 3],
1213                                 alias: [0; 32],
1214                                 addresses: Vec::new(),
1215                                 announcement_message: None,
1216                         });
1217                         network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
1218                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(1)),
1219                                 one_to_two: DirectionalChannelInfo {
1220                                         src_node_id: our_id.clone(),
1221                                         last_update: 0,
1222                                         enabled: false,
1223                                         cltv_expiry_delta: u16::max_value(), // This value should be ignored
1224                                         htlc_minimum_msat: 0,
1225                                         fee_base_msat: u32::max_value(), // This value should be ignored
1226                                         fee_proportional_millionths: u32::max_value(), // This value should be ignored
1227                                         last_update_message: None,
1228                                 }, two_to_one: DirectionalChannelInfo {
1229                                         src_node_id: node1.clone(),
1230                                         last_update: 0,
1231                                         enabled: true,
1232                                         cltv_expiry_delta: 0,
1233                                         htlc_minimum_msat: 0,
1234                                         fee_base_msat: 0,
1235                                         fee_proportional_millionths: 0,
1236                                         last_update_message: None,
1237                                 },
1238                                 announcement_message: None,
1239                         });
1240                         network.nodes.insert(node2.clone(), NodeInfo {
1241                                 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
1242                                 lowest_inbound_channel_fee_base_msat: 0,
1243                                 lowest_inbound_channel_fee_proportional_millionths: 0,
1244                                 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(2)),
1245                                 last_update: Some(1),
1246                                 rgb: [0; 3],
1247                                 alias: [0; 32],
1248                                 addresses: Vec::new(),
1249                                 announcement_message: None,
1250                         });
1251                         network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
1252                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(2)),
1253                                 one_to_two: DirectionalChannelInfo {
1254                                         src_node_id: our_id.clone(),
1255                                         last_update: 0,
1256                                         enabled: true,
1257                                         cltv_expiry_delta: u16::max_value(), // This value should be ignored
1258                                         htlc_minimum_msat: 0,
1259                                         fee_base_msat: u32::max_value(), // This value should be ignored
1260                                         fee_proportional_millionths: u32::max_value(), // This value should be ignored
1261                                         last_update_message: None,
1262                                 }, two_to_one: DirectionalChannelInfo {
1263                                         src_node_id: node2.clone(),
1264                                         last_update: 0,
1265                                         enabled: true,
1266                                         cltv_expiry_delta: 0,
1267                                         htlc_minimum_msat: 0,
1268                                         fee_base_msat: 0,
1269                                         fee_proportional_millionths: 0,
1270                                         last_update_message: None,
1271                                 },
1272                                 announcement_message: None,
1273                         });
1274                         network.nodes.insert(node8.clone(), NodeInfo {
1275                                 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
1276                                 lowest_inbound_channel_fee_base_msat: 0,
1277                                 lowest_inbound_channel_fee_proportional_millionths: 0,
1278                                 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(8)),
1279                                 last_update: Some(1),
1280                                 rgb: [0; 3],
1281                                 alias: [0; 32],
1282                                 addresses: Vec::new(),
1283                                 announcement_message: None,
1284                         });
1285                         network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
1286                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(12)),
1287                                 one_to_two: DirectionalChannelInfo {
1288                                         src_node_id: our_id.clone(),
1289                                         last_update: 0,
1290                                         enabled: true,
1291                                         cltv_expiry_delta: u16::max_value(), // This value should be ignored
1292                                         htlc_minimum_msat: 0,
1293                                         fee_base_msat: u32::max_value(), // This value should be ignored
1294                                         fee_proportional_millionths: u32::max_value(), // This value should be ignored
1295                                         last_update_message: None,
1296                                 }, two_to_one: DirectionalChannelInfo {
1297                                         src_node_id: node8.clone(),
1298                                         last_update: 0,
1299                                         enabled: true,
1300                                         cltv_expiry_delta: 0,
1301                                         htlc_minimum_msat: 0,
1302                                         fee_base_msat: 0,
1303                                         fee_proportional_millionths: 0,
1304                                         last_update_message: None,
1305                                 },
1306                                 announcement_message: None,
1307                         });
1308                         network.nodes.insert(node3.clone(), NodeInfo {
1309                                 channels: vec!(
1310                                         NetworkMap::get_key(3, zero_hash.clone()),
1311                                         NetworkMap::get_key(4, zero_hash.clone()),
1312                                         NetworkMap::get_key(13, zero_hash.clone()),
1313                                         NetworkMap::get_key(5, zero_hash.clone()),
1314                                         NetworkMap::get_key(6, zero_hash.clone()),
1315                                         NetworkMap::get_key(7, zero_hash.clone())),
1316                                 lowest_inbound_channel_fee_base_msat: 0,
1317                                 lowest_inbound_channel_fee_proportional_millionths: 0,
1318                                 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(3)),
1319                                 last_update: Some(1),
1320                                 rgb: [0; 3],
1321                                 alias: [0; 32],
1322                                 addresses: Vec::new(),
1323                                 announcement_message: None,
1324                         });
1325                         network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
1326                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(3)),
1327                                 one_to_two: DirectionalChannelInfo {
1328                                         src_node_id: node1.clone(),
1329                                         last_update: 0,
1330                                         enabled: true,
1331                                         cltv_expiry_delta: (3 << 8) | 1,
1332                                         htlc_minimum_msat: 0,
1333                                         fee_base_msat: 0,
1334                                         fee_proportional_millionths: 0,
1335                                         last_update_message: None,
1336                                 }, two_to_one: DirectionalChannelInfo {
1337                                         src_node_id: node3.clone(),
1338                                         last_update: 0,
1339                                         enabled: true,
1340                                         cltv_expiry_delta: (3 << 8) | 2,
1341                                         htlc_minimum_msat: 0,
1342                                         fee_base_msat: 100,
1343                                         fee_proportional_millionths: 0,
1344                                         last_update_message: None,
1345                                 },
1346                                 announcement_message: None,
1347                         });
1348                         network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
1349                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(4)),
1350                                 one_to_two: DirectionalChannelInfo {
1351                                         src_node_id: node2.clone(),
1352                                         last_update: 0,
1353                                         enabled: true,
1354                                         cltv_expiry_delta: (4 << 8) | 1,
1355                                         htlc_minimum_msat: 0,
1356                                         fee_base_msat: 0,
1357                                         fee_proportional_millionths: 1000000,
1358                                         last_update_message: None,
1359                                 }, two_to_one: DirectionalChannelInfo {
1360                                         src_node_id: node3.clone(),
1361                                         last_update: 0,
1362                                         enabled: true,
1363                                         cltv_expiry_delta: (4 << 8) | 2,
1364                                         htlc_minimum_msat: 0,
1365                                         fee_base_msat: 0,
1366                                         fee_proportional_millionths: 0,
1367                                         last_update_message: None,
1368                                 },
1369                                 announcement_message: None,
1370                         });
1371                         network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1372                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(13)),
1373                                 one_to_two: DirectionalChannelInfo {
1374                                         src_node_id: node8.clone(),
1375                                         last_update: 0,
1376                                         enabled: true,
1377                                         cltv_expiry_delta: (13 << 8) | 1,
1378                                         htlc_minimum_msat: 0,
1379                                         fee_base_msat: 0,
1380                                         fee_proportional_millionths: 2000000,
1381                                         last_update_message: None,
1382                                 }, two_to_one: DirectionalChannelInfo {
1383                                         src_node_id: node3.clone(),
1384                                         last_update: 0,
1385                                         enabled: true,
1386                                         cltv_expiry_delta: (13 << 8) | 2,
1387                                         htlc_minimum_msat: 0,
1388                                         fee_base_msat: 0,
1389                                         fee_proportional_millionths: 0,
1390                                         last_update_message: None,
1391                                 },
1392                                 announcement_message: None,
1393                         });
1394                         network.nodes.insert(node4.clone(), NodeInfo {
1395                                 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1396                                 lowest_inbound_channel_fee_base_msat: 0,
1397                                 lowest_inbound_channel_fee_proportional_millionths: 0,
1398                                 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(4)),
1399                                 last_update: Some(1),
1400                                 rgb: [0; 3],
1401                                 alias: [0; 32],
1402                                 addresses: Vec::new(),
1403                                 announcement_message: None,
1404                         });
1405                         network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1406                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(5)),
1407                                 one_to_two: DirectionalChannelInfo {
1408                                         src_node_id: node3.clone(),
1409                                         last_update: 0,
1410                                         enabled: true,
1411                                         cltv_expiry_delta: (5 << 8) | 1,
1412                                         htlc_minimum_msat: 0,
1413                                         fee_base_msat: 100,
1414                                         fee_proportional_millionths: 0,
1415                                         last_update_message: None,
1416                                 }, two_to_one: DirectionalChannelInfo {
1417                                         src_node_id: node4.clone(),
1418                                         last_update: 0,
1419                                         enabled: true,
1420                                         cltv_expiry_delta: (5 << 8) | 2,
1421                                         htlc_minimum_msat: 0,
1422                                         fee_base_msat: 0,
1423                                         fee_proportional_millionths: 0,
1424                                         last_update_message: None,
1425                                 },
1426                                 announcement_message: None,
1427                         });
1428                         network.nodes.insert(node5.clone(), NodeInfo {
1429                                 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1430                                 lowest_inbound_channel_fee_base_msat: 0,
1431                                 lowest_inbound_channel_fee_proportional_millionths: 0,
1432                                 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(5)),
1433                                 last_update: Some(1),
1434                                 rgb: [0; 3],
1435                                 alias: [0; 32],
1436                                 addresses: Vec::new(),
1437                                 announcement_message: None,
1438                         });
1439                         network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1440                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(6)),
1441                                 one_to_two: DirectionalChannelInfo {
1442                                         src_node_id: node3.clone(),
1443                                         last_update: 0,
1444                                         enabled: true,
1445                                         cltv_expiry_delta: (6 << 8) | 1,
1446                                         htlc_minimum_msat: 0,
1447                                         fee_base_msat: 0,
1448                                         fee_proportional_millionths: 0,
1449                                         last_update_message: None,
1450                                 }, two_to_one: DirectionalChannelInfo {
1451                                         src_node_id: node5.clone(),
1452                                         last_update: 0,
1453                                         enabled: true,
1454                                         cltv_expiry_delta: (6 << 8) | 2,
1455                                         htlc_minimum_msat: 0,
1456                                         fee_base_msat: 0,
1457                                         fee_proportional_millionths: 0,
1458                                         last_update_message: None,
1459                                 },
1460                                 announcement_message: None,
1461                         });
1462                         network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1463                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(11)),
1464                                 one_to_two: DirectionalChannelInfo {
1465                                         src_node_id: node5.clone(),
1466                                         last_update: 0,
1467                                         enabled: true,
1468                                         cltv_expiry_delta: (11 << 8) | 1,
1469                                         htlc_minimum_msat: 0,
1470                                         fee_base_msat: 0,
1471                                         fee_proportional_millionths: 0,
1472                                         last_update_message: None,
1473                                 }, two_to_one: DirectionalChannelInfo {
1474                                         src_node_id: node4.clone(),
1475                                         last_update: 0,
1476                                         enabled: true,
1477                                         cltv_expiry_delta: (11 << 8) | 2,
1478                                         htlc_minimum_msat: 0,
1479                                         fee_base_msat: 0,
1480                                         fee_proportional_millionths: 0,
1481                                         last_update_message: None,
1482                                 },
1483                                 announcement_message: None,
1484                         });
1485                         network.nodes.insert(node6.clone(), NodeInfo {
1486                                 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1487                                 lowest_inbound_channel_fee_base_msat: 0,
1488                                 lowest_inbound_channel_fee_proportional_millionths: 0,
1489                                 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(6)),
1490                                 last_update: Some(1),
1491                                 rgb: [0; 3],
1492                                 alias: [0; 32],
1493                                 addresses: Vec::new(),
1494                                 announcement_message: None,
1495                         });
1496                         network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1497                                 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(7)),
1498                                 one_to_two: DirectionalChannelInfo {
1499                                         src_node_id: node3.clone(),
1500                                         last_update: 0,
1501                                         enabled: true,
1502                                         cltv_expiry_delta: (7 << 8) | 1,
1503                                         htlc_minimum_msat: 0,
1504                                         fee_base_msat: 0,
1505                                         fee_proportional_millionths: 1000000,
1506                                         last_update_message: None,
1507                                 }, two_to_one: DirectionalChannelInfo {
1508                                         src_node_id: node6.clone(),
1509                                         last_update: 0,
1510                                         enabled: true,
1511                                         cltv_expiry_delta: (7 << 8) | 2,
1512                                         htlc_minimum_msat: 0,
1513                                         fee_base_msat: 0,
1514                                         fee_proportional_millionths: 0,
1515                                         last_update_message: None,
1516                                 },
1517                                 announcement_message: None,
1518                         });
1519                 }
1520
1521                 { // Simple route to 3 via 2
1522                         let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1523                         assert_eq!(route.paths[0].len(), 2);
1524
1525                         assert_eq!(route.paths[0][0].pubkey, node2);
1526                         assert_eq!(route.paths[0][0].short_channel_id, 2);
1527                         assert_eq!(route.paths[0][0].fee_msat, 100);
1528                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1529                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1530                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1531
1532                         assert_eq!(route.paths[0][1].pubkey, node3);
1533                         assert_eq!(route.paths[0][1].short_channel_id, 4);
1534                         assert_eq!(route.paths[0][1].fee_msat, 100);
1535                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1536                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1537                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1538                 }
1539
1540                 { // Disable channels 4 and 12 by requiring unknown feature bits
1541                         let mut network = router.network_map.write().unwrap();
1542                         network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1543                         network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1544                 }
1545
1546                 { // If all the channels require some features we don't understand, route should fail
1547                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1548                                 assert_eq!(err, "Failed to find a path to the given destination");
1549                         } else { panic!(); }
1550                 }
1551
1552                 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1553                         let our_chans = vec![channelmanager::ChannelDetails {
1554                                 channel_id: [0; 32],
1555                                 short_channel_id: Some(42),
1556                                 remote_network_id: node8.clone(),
1557                                 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1558                                 channel_value_satoshis: 0,
1559                                 user_id: 0,
1560                                 outbound_capacity_msat: 0,
1561                                 inbound_capacity_msat: 0,
1562                                 is_live: true,
1563                         }];
1564                         let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1565                         assert_eq!(route.paths[0].len(), 2);
1566
1567                         assert_eq!(route.paths[0][0].pubkey, node8);
1568                         assert_eq!(route.paths[0][0].short_channel_id, 42);
1569                         assert_eq!(route.paths[0][0].fee_msat, 200);
1570                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1571                         assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1572                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1573
1574                         assert_eq!(route.paths[0][1].pubkey, node3);
1575                         assert_eq!(route.paths[0][1].short_channel_id, 13);
1576                         assert_eq!(route.paths[0][1].fee_msat, 100);
1577                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1578                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1579                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1580                 }
1581
1582                 { // Re-enable channels 4 and 12 by wiping the unknown feature bits
1583                         let mut network = router.network_map.write().unwrap();
1584                         network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1585                         network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1586                 }
1587
1588                 { // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1589                         let mut network = router.network_map.write().unwrap();
1590                         network.nodes.get_mut(&node1).unwrap().features.set_require_unknown_bits();
1591                         network.nodes.get_mut(&node2).unwrap().features.set_require_unknown_bits();
1592                         network.nodes.get_mut(&node8).unwrap().features.set_require_unknown_bits();
1593                 }
1594
1595                 { // If all nodes require some features we don't understand, route should fail
1596                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1597                                 assert_eq!(err, "Failed to find a path to the given destination");
1598                         } else { panic!(); }
1599                 }
1600
1601                 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1602                         let our_chans = vec![channelmanager::ChannelDetails {
1603                                 channel_id: [0; 32],
1604                                 short_channel_id: Some(42),
1605                                 remote_network_id: node8.clone(),
1606                                 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1607                                 channel_value_satoshis: 0,
1608                                 user_id: 0,
1609                                 outbound_capacity_msat: 0,
1610                                 inbound_capacity_msat: 0,
1611                                 is_live: true,
1612                         }];
1613                         let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1614                         assert_eq!(route.paths[0].len(), 2);
1615
1616                         assert_eq!(route.paths[0][0].pubkey, node8);
1617                         assert_eq!(route.paths[0][0].short_channel_id, 42);
1618                         assert_eq!(route.paths[0][0].fee_msat, 200);
1619                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1620                         assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1621                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1622
1623                         assert_eq!(route.paths[0][1].pubkey, node3);
1624                         assert_eq!(route.paths[0][1].short_channel_id, 13);
1625                         assert_eq!(route.paths[0][1].fee_msat, 100);
1626                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1627                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1628                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1629                 }
1630
1631                 { // Re-enable nodes 1, 2, and 8
1632                         let mut network = router.network_map.write().unwrap();
1633                         network.nodes.get_mut(&node1).unwrap().features.clear_require_unknown_bits();
1634                         network.nodes.get_mut(&node2).unwrap().features.clear_require_unknown_bits();
1635                         network.nodes.get_mut(&node8).unwrap().features.clear_require_unknown_bits();
1636                 }
1637
1638                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1639                 // naively) assume that the user checked the feature bits on the invoice, which override
1640                 // the node_announcement.
1641
1642                 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1643                         let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1644                         assert_eq!(route.paths[0].len(), 3);
1645
1646                         assert_eq!(route.paths[0][0].pubkey, node2);
1647                         assert_eq!(route.paths[0][0].short_channel_id, 2);
1648                         assert_eq!(route.paths[0][0].fee_msat, 200);
1649                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1650                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1651                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1652
1653                         assert_eq!(route.paths[0][1].pubkey, node3);
1654                         assert_eq!(route.paths[0][1].short_channel_id, 4);
1655                         assert_eq!(route.paths[0][1].fee_msat, 100);
1656                         assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1657                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1658                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1659
1660                         assert_eq!(route.paths[0][2].pubkey, node1);
1661                         assert_eq!(route.paths[0][2].short_channel_id, 3);
1662                         assert_eq!(route.paths[0][2].fee_msat, 100);
1663                         assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1664                         assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(1));
1665                         assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(3));
1666                 }
1667
1668                 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1669                         let our_chans = vec![channelmanager::ChannelDetails {
1670                                 channel_id: [0; 32],
1671                                 short_channel_id: Some(42),
1672                                 remote_network_id: node8.clone(),
1673                                 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1674                                 channel_value_satoshis: 0,
1675                                 user_id: 0,
1676                                 outbound_capacity_msat: 0,
1677                                 inbound_capacity_msat: 0,
1678                                 is_live: true,
1679                         }];
1680                         let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1681                         assert_eq!(route.paths[0].len(), 2);
1682
1683                         assert_eq!(route.paths[0][0].pubkey, node8);
1684                         assert_eq!(route.paths[0][0].short_channel_id, 42);
1685                         assert_eq!(route.paths[0][0].fee_msat, 200);
1686                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1687                         assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1688                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1689
1690                         assert_eq!(route.paths[0][1].pubkey, node3);
1691                         assert_eq!(route.paths[0][1].short_channel_id, 13);
1692                         assert_eq!(route.paths[0][1].fee_msat, 100);
1693                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1694                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1695                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1696                 }
1697
1698                 let mut last_hops = vec!(RouteHint {
1699                                 src_node_id: node4.clone(),
1700                                 short_channel_id: 8,
1701                                 fee_base_msat: 0,
1702                                 fee_proportional_millionths: 0,
1703                                 cltv_expiry_delta: (8 << 8) | 1,
1704                                 htlc_minimum_msat: 0,
1705                         }, RouteHint {
1706                                 src_node_id: node5.clone(),
1707                                 short_channel_id: 9,
1708                                 fee_base_msat: 1001,
1709                                 fee_proportional_millionths: 0,
1710                                 cltv_expiry_delta: (9 << 8) | 1,
1711                                 htlc_minimum_msat: 0,
1712                         }, RouteHint {
1713                                 src_node_id: node6.clone(),
1714                                 short_channel_id: 10,
1715                                 fee_base_msat: 0,
1716                                 fee_proportional_millionths: 0,
1717                                 cltv_expiry_delta: (10 << 8) | 1,
1718                                 htlc_minimum_msat: 0,
1719                         });
1720
1721                 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1722                         let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1723                         assert_eq!(route.paths[0].len(), 5);
1724
1725                         assert_eq!(route.paths[0][0].pubkey, node2);
1726                         assert_eq!(route.paths[0][0].short_channel_id, 2);
1727                         assert_eq!(route.paths[0][0].fee_msat, 100);
1728                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1729                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1730                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1731
1732                         assert_eq!(route.paths[0][1].pubkey, node3);
1733                         assert_eq!(route.paths[0][1].short_channel_id, 4);
1734                         assert_eq!(route.paths[0][1].fee_msat, 0);
1735                         assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1736                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1737                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1738
1739                         assert_eq!(route.paths[0][2].pubkey, node5);
1740                         assert_eq!(route.paths[0][2].short_channel_id, 6);
1741                         assert_eq!(route.paths[0][2].fee_msat, 0);
1742                         assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1743                         assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(5));
1744                         assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(6));
1745
1746                         assert_eq!(route.paths[0][3].pubkey, node4);
1747                         assert_eq!(route.paths[0][3].short_channel_id, 11);
1748                         assert_eq!(route.paths[0][3].fee_msat, 0);
1749                         assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1750                         // If we have a peer in the node map, we'll use their features here since we don't have
1751                         // a way of figuring out their features from the invoice:
1752                         assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags!(4));
1753                         assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags!(11));
1754
1755                         assert_eq!(route.paths[0][4].pubkey, node7);
1756                         assert_eq!(route.paths[0][4].short_channel_id, 8);
1757                         assert_eq!(route.paths[0][4].fee_msat, 100);
1758                         assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1759                         assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1760                         assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1761                 }
1762
1763                 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1764                         let our_chans = vec![channelmanager::ChannelDetails {
1765                                 channel_id: [0; 32],
1766                                 short_channel_id: Some(42),
1767                                 remote_network_id: node4.clone(),
1768                                 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1769                                 channel_value_satoshis: 0,
1770                                 user_id: 0,
1771                                 outbound_capacity_msat: 0,
1772                                 inbound_capacity_msat: 0,
1773                                 is_live: true,
1774                         }];
1775                         let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1776                         assert_eq!(route.paths[0].len(), 2);
1777
1778                         assert_eq!(route.paths[0][0].pubkey, node4);
1779                         assert_eq!(route.paths[0][0].short_channel_id, 42);
1780                         assert_eq!(route.paths[0][0].fee_msat, 0);
1781                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
1782                         assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1783                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1784
1785                         assert_eq!(route.paths[0][1].pubkey, node7);
1786                         assert_eq!(route.paths[0][1].short_channel_id, 8);
1787                         assert_eq!(route.paths[0][1].fee_msat, 100);
1788                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1789                         assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1790                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1791                 }
1792
1793                 last_hops[0].fee_base_msat = 1000;
1794
1795                 { // Revert to via 6 as the fee on 8 goes up
1796                         let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1797                         assert_eq!(route.paths[0].len(), 4);
1798
1799                         assert_eq!(route.paths[0][0].pubkey, node2);
1800                         assert_eq!(route.paths[0][0].short_channel_id, 2);
1801                         assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
1802                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1803                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1804                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1805
1806                         assert_eq!(route.paths[0][1].pubkey, node3);
1807                         assert_eq!(route.paths[0][1].short_channel_id, 4);
1808                         assert_eq!(route.paths[0][1].fee_msat, 100);
1809                         assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
1810                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1811                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1812
1813                         assert_eq!(route.paths[0][2].pubkey, node6);
1814                         assert_eq!(route.paths[0][2].short_channel_id, 7);
1815                         assert_eq!(route.paths[0][2].fee_msat, 0);
1816                         assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
1817                         // If we have a peer in the node map, we'll use their features here since we don't have
1818                         // a way of figuring out their features from the invoice:
1819                         assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(6));
1820                         assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(7));
1821
1822                         assert_eq!(route.paths[0][3].pubkey, node7);
1823                         assert_eq!(route.paths[0][3].short_channel_id, 10);
1824                         assert_eq!(route.paths[0][3].fee_msat, 100);
1825                         assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
1826                         assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1827                         assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1828                 }
1829
1830                 { // ...but still use 8 for larger payments as 6 has a variable feerate
1831                         let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1832                         assert_eq!(route.paths[0].len(), 5);
1833
1834                         assert_eq!(route.paths[0][0].pubkey, node2);
1835                         assert_eq!(route.paths[0][0].short_channel_id, 2);
1836                         assert_eq!(route.paths[0][0].fee_msat, 3000);
1837                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1838                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1839                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1840
1841                         assert_eq!(route.paths[0][1].pubkey, node3);
1842                         assert_eq!(route.paths[0][1].short_channel_id, 4);
1843                         assert_eq!(route.paths[0][1].fee_msat, 0);
1844                         assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1845                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1846                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1847
1848                         assert_eq!(route.paths[0][2].pubkey, node5);
1849                         assert_eq!(route.paths[0][2].short_channel_id, 6);
1850                         assert_eq!(route.paths[0][2].fee_msat, 0);
1851                         assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1852                         assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(5));
1853                         assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(6));
1854
1855                         assert_eq!(route.paths[0][3].pubkey, node4);
1856                         assert_eq!(route.paths[0][3].short_channel_id, 11);
1857                         assert_eq!(route.paths[0][3].fee_msat, 1000);
1858                         assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1859                         // If we have a peer in the node map, we'll use their features here since we don't have
1860                         // a way of figuring out their features from the invoice:
1861                         assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags!(4));
1862                         assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags!(11));
1863
1864                         assert_eq!(route.paths[0][4].pubkey, node7);
1865                         assert_eq!(route.paths[0][4].short_channel_id, 8);
1866                         assert_eq!(route.paths[0][4].fee_msat, 2000);
1867                         assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1868                         assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1869                         assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1870                 }
1871
1872                 { // Test Router serialization/deserialization
1873                         let mut w = TestVecWriter(Vec::new());
1874                         let network = router.network_map.read().unwrap();
1875                         assert!(!network.channels.is_empty());
1876                         assert!(!network.nodes.is_empty());
1877                         network.write(&mut w).unwrap();
1878                         assert!(<NetworkMap>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1879                 }
1880         }
1881
1882         #[test]
1883         fn request_full_sync_finite_times() {
1884                 let (secp_ctx, _, router) = create_router();
1885                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1886
1887                 assert!(router.should_request_full_sync(&node_id));
1888                 assert!(router.should_request_full_sync(&node_id));
1889                 assert!(router.should_request_full_sync(&node_id));
1890                 assert!(router.should_request_full_sync(&node_id));
1891                 assert!(router.should_request_full_sync(&node_id));
1892                 assert!(!router.should_request_full_sync(&node_id));
1893         }
1894
1895         #[test]
1896         fn handling_node_announcements() {
1897                 let (secp_ctx, _, router) = create_router();
1898
1899                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1900                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1901                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1902                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1903                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1904                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1905                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1906                 let first_announcement_time = 500;
1907
1908                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1909                         features: NodeFeatures::known(),
1910                         timestamp: first_announcement_time,
1911                         node_id: node_id_1,
1912                         rgb: [0; 3],
1913                         alias: [0; 32],
1914                         addresses: Vec::new(),
1915                         excess_address_data: Vec::new(),
1916                         excess_data: Vec::new(),
1917                 };
1918                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1919                 let valid_announcement = NodeAnnouncement {
1920                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1921                         contents: unsigned_announcement.clone()
1922                 };
1923
1924                 match router.handle_node_announcement(&valid_announcement) {
1925                         Ok(_) => panic!(),
1926                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1927                 };
1928
1929                 {
1930                         // Announce a channel to add a corresponding node.
1931                         let unsigned_announcement = UnsignedChannelAnnouncement {
1932                                 features: ChannelFeatures::known(),
1933                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1934                                 short_channel_id: 0,
1935                                 node_id_1,
1936                                 node_id_2,
1937                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1938                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1939                                 excess_data: Vec::new(),
1940                         };
1941
1942                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1943                         let valid_announcement = ChannelAnnouncement {
1944                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1945                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1946                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1947                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1948                                 contents: unsigned_announcement.clone(),
1949                         };
1950                         match router.handle_channel_announcement(&valid_announcement) {
1951                                 Ok(res) => assert!(res),
1952                                 _ => panic!()
1953                         };
1954                 }
1955
1956                 match router.handle_node_announcement(&valid_announcement) {
1957                         Ok(res) => assert!(res),
1958                         Err(_) => panic!()
1959                 };
1960
1961                 let fake_msghash = hash_to_message!(&zero_hash);
1962                 match router.handle_node_announcement(
1963                         &NodeAnnouncement {
1964                                 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1965                                 contents: unsigned_announcement.clone()
1966                 }) {
1967                         Ok(_) => panic!(),
1968                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1969                 };
1970
1971                 unsigned_announcement.timestamp += 1000;
1972                 unsigned_announcement.excess_data.push(1);
1973                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1974                 let announcement_with_data = NodeAnnouncement {
1975                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1976                         contents: unsigned_announcement.clone()
1977                 };
1978                 // Return false because contains excess data.
1979                 match router.handle_node_announcement(&announcement_with_data) {
1980                         Ok(res) => assert!(!res),
1981                         Err(_) => panic!()
1982                 };
1983                 unsigned_announcement.excess_data = Vec::new();
1984
1985                 // Even though previous announcement was not relayed further, we still accepted it,
1986                 // so we now won't accept announcements before the previous one.
1987                 unsigned_announcement.timestamp -= 10;
1988                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1989                 let outdated_announcement = NodeAnnouncement {
1990                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1991                         contents: unsigned_announcement.clone()
1992                 };
1993                 match router.handle_node_announcement(&outdated_announcement) {
1994                         Ok(_) => panic!(),
1995                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
1996                 };
1997         }
1998
1999         #[test]
2000         fn handling_channel_announcements() {
2001                 let secp_ctx = Secp256k1::new();
2002                 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(
2003                    &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
2004                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
2005                 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
2006                 let router = Router::new(our_id, chain_monitor.clone(), Arc::clone(&logger));
2007
2008                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2009                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2010                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2011                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2012                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2013                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2014
2015                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2016                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
2017                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
2018                    .push_opcode(opcodes::all::OP_PUSHNUM_2)
2019                    .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2020
2021
2022                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
2023                         features: ChannelFeatures::known(),
2024                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
2025                         short_channel_id: 0,
2026                         node_id_1,
2027                         node_id_2,
2028                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2029                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2030                         excess_data: Vec::new(),
2031                 };
2032
2033                 let channel_key = NetworkMap::get_key(unsigned_announcement.short_channel_id,
2034                                                     unsigned_announcement.chain_hash);
2035
2036                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2037                 let valid_announcement = ChannelAnnouncement {
2038                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2039                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2040                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2041                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2042                         contents: unsigned_announcement.clone(),
2043                 };
2044
2045                 // Test if the UTXO lookups were not supported
2046                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
2047
2048                 match router.handle_channel_announcement(&valid_announcement) {
2049                         Ok(res) => assert!(res),
2050                         _ => panic!()
2051                 };
2052                 {
2053                         let network = router.network_map.write().unwrap();
2054                         match network.channels.get(&channel_key) {
2055                                 None => panic!(),
2056                                 Some(_) => ()
2057                         }
2058                 }
2059
2060                 // If we receive announcement for the same channel (with UTXO lookups disabled),
2061                 // drop new one on the floor, since we can't see any changes.
2062                 match router.handle_channel_announcement(&valid_announcement) {
2063                         Ok(_) => panic!(),
2064                         Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
2065                 };
2066
2067
2068                 // Test if an associated transaction were not on-chain (or not confirmed).
2069                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
2070                 unsigned_announcement.short_channel_id += 1;
2071
2072                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2073                 let valid_announcement = ChannelAnnouncement {
2074                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2075                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2076                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2077                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2078                         contents: unsigned_announcement.clone(),
2079                 };
2080
2081                 match router.handle_channel_announcement(&valid_announcement) {
2082                         Ok(_) => panic!(),
2083                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2084                 };
2085
2086
2087                 // Now test if the transaction is found in the UTXO set and the script is correct.
2088                 unsigned_announcement.short_channel_id += 1;
2089                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
2090                 let channel_key = NetworkMap::get_key(unsigned_announcement.short_channel_id,
2091                                                    unsigned_announcement.chain_hash);
2092
2093                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2094                 let valid_announcement = ChannelAnnouncement {
2095                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2096                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2097                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2098                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2099                         contents: unsigned_announcement.clone(),
2100                 };
2101                 match router.handle_channel_announcement(&valid_announcement) {
2102                         Ok(res) => assert!(res),
2103                         _ => panic!()
2104                 };
2105                 {
2106                         let network = router.network_map.write().unwrap();
2107                         match network.channels.get(&channel_key) {
2108                                 None => panic!(),
2109                                 Some(_) => ()
2110                         }
2111                 }
2112
2113                 // If we receive announcement for the same channel (but TX is not confirmed),
2114                 // drop new one on the floor, since we can't see any changes.
2115                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
2116                 match router.handle_channel_announcement(&valid_announcement) {
2117                         Ok(_) => panic!(),
2118                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2119                 };
2120
2121                 // But if it is confirmed, replace the channel
2122                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
2123                 unsigned_announcement.features = ChannelFeatures::empty();
2124                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2125                 let valid_announcement = ChannelAnnouncement {
2126                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2127                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2128                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2129                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2130                         contents: unsigned_announcement.clone(),
2131                 };
2132                 match router.handle_channel_announcement(&valid_announcement) {
2133                         Ok(res) => assert!(res),
2134                         _ => panic!()
2135                 };
2136                 {
2137                         let mut network = router.network_map.write().unwrap();
2138                         match network.channels.entry(channel_key) {
2139                                 BtreeEntry::Occupied(channel_entry) => {
2140                                         assert_eq!(channel_entry.get().features, ChannelFeatures::empty());
2141                                 },
2142                                 _ => panic!()
2143                         }
2144                 }
2145
2146                 // Don't relay valid channels with excess data
2147                 unsigned_announcement.short_channel_id += 1;
2148                 unsigned_announcement.excess_data.push(1);
2149                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2150                 let valid_announcement = ChannelAnnouncement {
2151                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2152                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2153                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2154                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2155                         contents: unsigned_announcement.clone(),
2156                 };
2157                 match router.handle_channel_announcement(&valid_announcement) {
2158                         Ok(res) => assert!(!res),
2159                         _ => panic!()
2160                 };
2161
2162                 unsigned_announcement.excess_data = Vec::new();
2163                 let invalid_sig_announcement = ChannelAnnouncement {
2164                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2165                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2166                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2167                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
2168                         contents: unsigned_announcement.clone(),
2169                 };
2170                 match router.handle_channel_announcement(&invalid_sig_announcement) {
2171                         Ok(_) => panic!(),
2172                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
2173                 };
2174
2175                 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2176                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2177                 let channel_to_itself_announcement = ChannelAnnouncement {
2178                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2179                         node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
2180                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2181                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2182                         contents: unsigned_announcement.clone(),
2183                 };
2184                 match router.handle_channel_announcement(&channel_to_itself_announcement) {
2185                         Ok(_) => panic!(),
2186                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2187                 };
2188         }
2189
2190         #[test]
2191         fn handling_channel_update() {
2192                 let (secp_ctx, _, router) = create_router();
2193                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2194                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2195                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2196                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2197                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2198                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2199
2200                 let zero_hash = Sha256dHash::hash(&[0; 32]);
2201                 let short_channel_id = 0;
2202                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2203                 let channel_key = NetworkMap::get_key(short_channel_id, chain_hash);
2204
2205
2206                 {
2207                         // Announce a channel we will update
2208                         let unsigned_announcement = UnsignedChannelAnnouncement {
2209                                 features: ChannelFeatures::empty(),
2210                                 chain_hash,
2211                                 short_channel_id,
2212                                 node_id_1,
2213                                 node_id_2,
2214                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2215                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2216                                 excess_data: Vec::new(),
2217                         };
2218
2219                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2220                         let valid_channel_announcement = ChannelAnnouncement {
2221                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2222                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2223                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2224                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2225                                 contents: unsigned_announcement.clone(),
2226                         };
2227                         match router.handle_channel_announcement(&valid_channel_announcement) {
2228                                 Ok(_) => (),
2229                                 Err(_) => panic!()
2230                         };
2231
2232                 }
2233
2234                 let mut unsigned_channel_update = UnsignedChannelUpdate {
2235                         chain_hash,
2236                         short_channel_id,
2237                         timestamp: 100,
2238                         flags: 0,
2239                         cltv_expiry_delta: 144,
2240                         htlc_minimum_msat: 1000000,
2241                         fee_base_msat: 10000,
2242                         fee_proportional_millionths: 20,
2243                         excess_data: Vec::new()
2244                 };
2245                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2246                 let valid_channel_update = ChannelUpdate {
2247                         signature: secp_ctx.sign(&msghash, node_1_privkey),
2248                         contents: unsigned_channel_update.clone()
2249                 };
2250
2251                 match router.handle_channel_update(&valid_channel_update) {
2252                         Ok(res) => assert!(res),
2253                         _ => panic!()
2254                 };
2255
2256                 {
2257                         let network = router.network_map.write().unwrap();
2258                         match network.channels.get(&channel_key) {
2259                                 None => panic!(),
2260                                 Some(channel_info) => {
2261                                         assert_eq!(channel_info.one_to_two.cltv_expiry_delta, 144);
2262                                         assert_eq!(channel_info.two_to_one.cltv_expiry_delta, u16::max_value());
2263                                 }
2264                         }
2265                 }
2266
2267                 unsigned_channel_update.timestamp += 100;
2268                 unsigned_channel_update.excess_data.push(1);
2269                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2270                 let valid_channel_update = ChannelUpdate {
2271                         signature: secp_ctx.sign(&msghash, node_1_privkey),
2272                         contents: unsigned_channel_update.clone()
2273                 };
2274                 // Return false because contains excess data
2275                 match router.handle_channel_update(&valid_channel_update) {
2276                         Ok(res) => assert!(!res),
2277                         _ => panic!()
2278                 };
2279
2280                 unsigned_channel_update.short_channel_id += 1;
2281                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2282                 let valid_channel_update = ChannelUpdate {
2283                         signature: secp_ctx.sign(&msghash, node_1_privkey),
2284                         contents: unsigned_channel_update.clone()
2285                 };
2286
2287                 match router.handle_channel_update(&valid_channel_update) {
2288                         Ok(_) => panic!(),
2289                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2290                 };
2291                 unsigned_channel_update.short_channel_id = short_channel_id;
2292
2293
2294                 // Even though previous update was not relayed further, we still accepted it,
2295                 // so we now won't accept update before the previous one.
2296                 unsigned_channel_update.timestamp -= 10;
2297                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2298                 let valid_channel_update = ChannelUpdate {
2299                         signature: secp_ctx.sign(&msghash, node_1_privkey),
2300                         contents: unsigned_channel_update.clone()
2301                 };
2302
2303                 match router.handle_channel_update(&valid_channel_update) {
2304                         Ok(_) => panic!(),
2305                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
2306                 };
2307                 unsigned_channel_update.timestamp += 500;
2308
2309                 let fake_msghash = hash_to_message!(&zero_hash);
2310                 let invalid_sig_channel_update = ChannelUpdate {
2311                         signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
2312                         contents: unsigned_channel_update.clone()
2313                 };
2314
2315                 match router.handle_channel_update(&invalid_sig_channel_update) {
2316                         Ok(_) => panic!(),
2317                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
2318                 };
2319
2320         }
2321
2322         #[test]
2323         fn handling_htlc_fail_channel_update() {
2324                 let (secp_ctx, our_id, router) = create_router();
2325                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2326                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2327                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2328                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2329                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2330                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2331
2332                 let short_channel_id = 0;
2333                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2334                 let channel_key = NetworkMap::get_key(short_channel_id, chain_hash);
2335
2336                 {
2337                         // There is only local node in the table at the beginning.
2338                         let network = router.network_map.read().unwrap();
2339                         assert_eq!(network.nodes.len(), 1);
2340                         assert_eq!(network.nodes.contains_key(&our_id), true);
2341                 }
2342
2343                 {
2344                         // Announce a channel we will update
2345                         let unsigned_announcement = UnsignedChannelAnnouncement {
2346                                 features: ChannelFeatures::empty(),
2347                                 chain_hash,
2348                                 short_channel_id,
2349                                 node_id_1,
2350                                 node_id_2,
2351                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2352                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2353                                 excess_data: Vec::new(),
2354                         };
2355
2356                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2357                         let valid_channel_announcement = ChannelAnnouncement {
2358                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2359                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2360                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2361                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2362                                 contents: unsigned_announcement.clone(),
2363                         };
2364                         match router.handle_channel_announcement(&valid_channel_announcement) {
2365                                 Ok(_) => (),
2366                                 Err(_) => panic!()
2367                         };
2368
2369                 }
2370
2371                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
2372                         short_channel_id,
2373                         is_permanent: false
2374                 };
2375
2376                 router.handle_htlc_fail_channel_update(&channel_close_msg);
2377
2378                 {
2379                         // Non-permanent closing just disables a channel
2380                         let network = router.network_map.write().unwrap();
2381                         match network.channels.get(&channel_key) {
2382                                 None => panic!(),
2383                                 Some(channel_info) => {
2384                                         assert!(!channel_info.one_to_two.enabled);
2385                                         assert!(!channel_info.two_to_one.enabled);
2386                                 }
2387                         }
2388                 }
2389
2390                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
2391                         short_channel_id,
2392                         is_permanent: true
2393                 };
2394
2395                 router.handle_htlc_fail_channel_update(&channel_close_msg);
2396
2397                 {
2398                         // Permanent closing deletes a channel
2399                         let network = router.network_map.read().unwrap();
2400                         assert_eq!(network.channels.len(), 0);
2401                         // Nodes are also deleted because there are no associated channels anymore
2402                         // Only the local node remains in the table.
2403                         assert_eq!(network.nodes.len(), 1);
2404                         assert_eq!(network.nodes.contains_key(&our_id), true);
2405                 }
2406
2407                 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
2408         }
2409
2410         #[test]
2411         fn getting_next_channel_announcements() {
2412                 let (secp_ctx, _, router) = create_router();
2413                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2414                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2415                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2416                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2417                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2418                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2419
2420                 let short_channel_id = 1;
2421                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2422                 let channel_key = NetworkMap::get_key(short_channel_id, chain_hash);
2423
2424                 // Channels were not announced yet.
2425                 let channels_with_announcements = router.get_next_channel_announcements(0, 1);
2426                 assert_eq!(channels_with_announcements.len(), 0);
2427
2428                 {
2429                         // Announce a channel we will update
2430                         let unsigned_announcement = UnsignedChannelAnnouncement {
2431                                 features: ChannelFeatures::empty(),
2432                                 chain_hash,
2433                                 short_channel_id,
2434                                 node_id_1,
2435                                 node_id_2,
2436                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2437                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2438                                 excess_data: Vec::new(),
2439                         };
2440
2441                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2442                         let valid_channel_announcement = ChannelAnnouncement {
2443                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2444                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2445                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2446                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2447                                 contents: unsigned_announcement.clone(),
2448                         };
2449                         match router.handle_channel_announcement(&valid_channel_announcement) {
2450                                 Ok(_) => (),
2451                                 Err(_) => panic!()
2452                         };
2453                 }
2454
2455                 // Contains initial channel announcement now.
2456                 let channels_with_announcements = router.get_next_channel_announcements(channel_key, 1);
2457                 assert_eq!(channels_with_announcements.len(), 1);
2458                 if let Some(channel_announcements) = channels_with_announcements.first() {
2459                         let &(_, ref update_1, ref update_2) = channel_announcements;
2460                         assert_eq!(update_1, &None);
2461                         assert_eq!(update_2, &None);
2462                 } else {
2463                         panic!();
2464                 }
2465
2466
2467                 {
2468                         // Valid channel update
2469                         let unsigned_channel_update = UnsignedChannelUpdate {
2470                                 chain_hash,
2471                                 short_channel_id,
2472                                 timestamp: 101,
2473                                 flags: 0,
2474                                 cltv_expiry_delta: 144,
2475                                 htlc_minimum_msat: 1000000,
2476                                 fee_base_msat: 10000,
2477                                 fee_proportional_millionths: 20,
2478                                 excess_data: Vec::new()
2479                         };
2480                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2481                         let valid_channel_update = ChannelUpdate {
2482                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
2483                                 contents: unsigned_channel_update.clone()
2484                         };
2485                         match router.handle_channel_update(&valid_channel_update) {
2486                                 Ok(_) => (),
2487                                 Err(_) => panic!()
2488                         };
2489                 }
2490
2491                 // Now contains an initial announcement and an update.
2492                 let channels_with_announcements = router.get_next_channel_announcements(channel_key, 1);
2493                 assert_eq!(channels_with_announcements.len(), 1);
2494                 if let Some(channel_announcements) = channels_with_announcements.first() {
2495                         let &(_, ref update_1, ref update_2) = channel_announcements;
2496                         assert_ne!(update_1, &None);
2497                         assert_eq!(update_2, &None);
2498                 } else {
2499                         panic!();
2500                 }
2501
2502
2503                 {
2504                         // Channel update with excess data.
2505                         let unsigned_channel_update = UnsignedChannelUpdate {
2506                                 chain_hash,
2507                                 short_channel_id,
2508                                 timestamp: 102,
2509                                 flags: 0,
2510                                 cltv_expiry_delta: 144,
2511                                 htlc_minimum_msat: 1000000,
2512                                 fee_base_msat: 10000,
2513                                 fee_proportional_millionths: 20,
2514                                 excess_data: [1; 3].to_vec()
2515                         };
2516                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2517                         let valid_channel_update = ChannelUpdate {
2518                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
2519                                 contents: unsigned_channel_update.clone()
2520                         };
2521                         match router.handle_channel_update(&valid_channel_update) {
2522                                 Ok(_) => (),
2523                                 Err(_) => panic!()
2524                         };
2525                 }
2526
2527                 // Test that announcements with excess data won't be returned
2528                 let channels_with_announcements = router.get_next_channel_announcements(channel_key, 1);
2529                 assert_eq!(channels_with_announcements.len(), 1);
2530                 if let Some(channel_announcements) = channels_with_announcements.first() {
2531                         let &(_, ref update_1, ref update_2) = channel_announcements;
2532                         assert_eq!(update_1, &None);
2533                         assert_eq!(update_2, &None);
2534                 } else {
2535                         panic!();
2536                 }
2537
2538                 // Further starting point have no channels after it
2539                 let channels_with_announcements = router.get_next_channel_announcements(channel_key + 1000, 1);
2540                 assert_eq!(channels_with_announcements.len(), 0);
2541         }
2542
2543         #[test]
2544         fn getting_next_node_announcements() {
2545                 let (secp_ctx, _, router) = create_router();
2546                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2547                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2548                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2549                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2550                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2551                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2552
2553                 let short_channel_id = 1;
2554                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2555
2556                 // No nodes yet.
2557                 let next_announcements = router.get_next_node_announcements(None, 10);
2558                 assert_eq!(next_announcements.len(), 0);
2559
2560                 {
2561                         // Announce a channel to add 2 nodes
2562                         let unsigned_announcement = UnsignedChannelAnnouncement {
2563                                 features: ChannelFeatures::empty(),
2564                                 chain_hash,
2565                                 short_channel_id,
2566                                 node_id_1,
2567                                 node_id_2,
2568                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2569                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2570                                 excess_data: Vec::new(),
2571                         };
2572
2573                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2574                         let valid_channel_announcement = ChannelAnnouncement {
2575                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2576                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2577                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2578                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2579                                 contents: unsigned_announcement.clone(),
2580                         };
2581                         match router.handle_channel_announcement(&valid_channel_announcement) {
2582                                 Ok(_) => (),
2583                                 Err(_) => panic!()
2584                         };
2585                 }
2586
2587
2588                 // Nodes were never announced
2589                 let next_announcements = router.get_next_node_announcements(None, 3);
2590                 assert_eq!(next_announcements.len(), 0);
2591
2592                 {
2593                         let mut unsigned_announcement = UnsignedNodeAnnouncement {
2594                                 features: NodeFeatures::known(),
2595                                 timestamp: 1000,
2596                                 node_id: node_id_1,
2597                                 rgb: [0; 3],
2598                                 alias: [0; 32],
2599                                 addresses: Vec::new(),
2600                                 excess_address_data: Vec::new(),
2601                                 excess_data: Vec::new(),
2602                         };
2603                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2604                         let valid_announcement = NodeAnnouncement {
2605                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
2606                                 contents: unsigned_announcement.clone()
2607                         };
2608                         match router.handle_node_announcement(&valid_announcement) {
2609                                 Ok(_) => (),
2610                                 Err(_) => panic!()
2611                         };
2612
2613                         unsigned_announcement.node_id = node_id_2;
2614                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2615                         let valid_announcement = NodeAnnouncement {
2616                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
2617                                 contents: unsigned_announcement.clone()
2618                         };
2619
2620                         match router.handle_node_announcement(&valid_announcement) {
2621                                 Ok(_) => (),
2622                                 Err(_) => panic!()
2623                         };
2624                 }
2625
2626                 let next_announcements = router.get_next_node_announcements(None, 3);
2627                 assert_eq!(next_announcements.len(), 2);
2628
2629                 // Skip the first node.
2630                 let next_announcements = router.get_next_node_announcements(Some(&node_id_1), 2);
2631                 assert_eq!(next_announcements.len(), 1);
2632
2633                 {
2634                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2635                         let unsigned_announcement = UnsignedNodeAnnouncement {
2636                                 features: NodeFeatures::known(),
2637                                 timestamp: 1010,
2638                                 node_id: node_id_2,
2639                                 rgb: [0; 3],
2640                                 alias: [0; 32],
2641                                 addresses: Vec::new(),
2642                                 excess_address_data: Vec::new(),
2643                                 excess_data: [1; 3].to_vec(),
2644                         };
2645                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2646                         let valid_announcement = NodeAnnouncement {
2647                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
2648                                 contents: unsigned_announcement.clone()
2649                         };
2650                         match router.handle_node_announcement(&valid_announcement) {
2651                                 Ok(res) => assert!(!res),
2652                                 Err(_) => panic!()
2653                         };
2654                 }
2655
2656                 let next_announcements = router.get_next_node_announcements(Some(&node_id_1), 2);
2657                 assert_eq!(next_announcements.len(), 0);
2658
2659         }
2660 }