Automatically prune NetworkGraph of stale channels hourly in BP
[rust-lightning] / lightning / src / routing / network_graph.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! The top-level network map tracking logic lives here.
11
12 use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
13 use bitcoin::secp256k1::key::PublicKey;
14 use bitcoin::secp256k1::Secp256k1;
15 use bitcoin::secp256k1;
16
17 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
18 use bitcoin::hashes::Hash;
19 use bitcoin::blockdata::script::Builder;
20 use bitcoin::blockdata::transaction::TxOut;
21 use bitcoin::blockdata::opcodes;
22 use bitcoin::hash_types::BlockHash;
23
24 use chain;
25 use chain::Access;
26 use ln::features::{ChannelFeatures, NodeFeatures};
27 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
28 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
29 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use ln::msgs;
31 use util::ser::{Writeable, Readable, Writer};
32 use util::logger::{Logger, Level};
33 use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
34 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
35
36 use io;
37 use prelude::*;
38 use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
39 use core::{cmp, fmt};
40 use sync::{RwLock, RwLockReadGuard};
41 use core::sync::atomic::{AtomicUsize, Ordering};
42 use sync::Mutex;
43 use core::ops::Deref;
44 use bitcoin::hashes::hex::ToHex;
45
46 #[cfg(feature = "std")]
47 use std::time::{SystemTime, UNIX_EPOCH};
48
49 /// We remove stale channel directional info two weeks after the last update, per BOLT 7's
50 /// suggestion.
51 const STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14;
52
53 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
54 /// refuse to relay the message.
55 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
56
57 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
58 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
59 const MAX_SCIDS_PER_REPLY: usize = 8000;
60
61 /// Represents the compressed public key of a node
62 #[derive(Clone, Copy)]
63 pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
64
65 impl NodeId {
66         /// Create a new NodeId from a public key
67         pub fn from_pubkey(pubkey: &PublicKey) -> Self {
68                 NodeId(pubkey.serialize())
69         }
70         
71         /// Get the public key slice from this NodeId
72         pub fn as_slice(&self) -> &[u8] {
73                 &self.0
74         }
75 }
76
77 impl fmt::Debug for NodeId {
78         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79                 write!(f, "NodeId({})", log_bytes!(self.0))
80         }
81 }
82
83 impl core::hash::Hash for NodeId {
84         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
85                 self.0.hash(hasher);
86         }
87 }
88
89 impl Eq for NodeId {}
90
91 impl PartialEq for NodeId {
92         fn eq(&self, other: &Self) -> bool {
93                 self.0[..] == other.0[..]
94         }
95 }
96
97 impl cmp::PartialOrd for NodeId {
98         fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
99                 Some(self.cmp(other))
100         }
101 }
102
103 impl Ord for NodeId {
104         fn cmp(&self, other: &Self) -> cmp::Ordering {
105                 self.0[..].cmp(&other.0[..])
106         }
107 }
108
109 impl Writeable for NodeId {
110         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
111                 writer.write_all(&self.0)?;
112                 Ok(())
113         }
114 }
115
116 impl Readable for NodeId {
117         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
118                 let mut buf = [0; PUBLIC_KEY_SIZE];
119                 reader.read_exact(&mut buf)?;
120                 Ok(Self(buf))
121         }
122 }
123
124 /// Represents the network as nodes and channels between them
125 pub struct NetworkGraph {
126         genesis_hash: BlockHash,
127         // Lock order: channels -> nodes
128         channels: RwLock<BTreeMap<u64, ChannelInfo>>,
129         nodes: RwLock<BTreeMap<NodeId, NodeInfo>>,
130 }
131
132 impl Clone for NetworkGraph {
133         fn clone(&self) -> Self {
134                 let channels = self.channels.read().unwrap();
135                 let nodes = self.nodes.read().unwrap();
136                 Self {
137                         genesis_hash: self.genesis_hash.clone(),
138                         channels: RwLock::new(channels.clone()),
139                         nodes: RwLock::new(nodes.clone()),
140                 }
141         }
142 }
143
144 /// A read-only view of [`NetworkGraph`].
145 pub struct ReadOnlyNetworkGraph<'a> {
146         channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
147         nodes: RwLockReadGuard<'a, BTreeMap<NodeId, NodeInfo>>,
148 }
149
150 /// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
151 /// return packet by a node along the route. See [BOLT #4] for details.
152 ///
153 /// [BOLT #4]: https://github.com/lightningnetwork/lightning-rfc/blob/master/04-onion-routing.md
154 #[derive(Clone, Debug, PartialEq)]
155 pub enum NetworkUpdate {
156         /// An error indicating a `channel_update` messages should be applied via
157         /// [`NetworkGraph::update_channel`].
158         ChannelUpdateMessage {
159                 /// The update to apply via [`NetworkGraph::update_channel`].
160                 msg: ChannelUpdate,
161         },
162         /// An error indicating only that a channel has been closed, which should be applied via
163         /// [`NetworkGraph::close_channel_from_update`].
164         ChannelClosed {
165                 /// The short channel id of the closed channel.
166                 short_channel_id: u64,
167                 /// Whether the channel should be permanently removed or temporarily disabled until a new
168                 /// `channel_update` message is received.
169                 is_permanent: bool,
170         },
171         /// An error indicating only that a node has failed, which should be applied via
172         /// [`NetworkGraph::fail_node`].
173         NodeFailure {
174                 /// The node id of the failed node.
175                 node_id: PublicKey,
176                 /// Whether the node should be permanently removed from consideration or can be restored
177                 /// when a new `channel_update` message is received.
178                 is_permanent: bool,
179         }
180 }
181
182 impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
183         (0, ChannelUpdateMessage) => {
184                 (0, msg, required),
185         },
186         (2, ChannelClosed) => {
187                 (0, short_channel_id, required),
188                 (2, is_permanent, required),
189         },
190         (4, NodeFailure) => {
191                 (0, node_id, required),
192                 (2, is_permanent, required),
193         },
194 );
195
196 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> EventHandler for NetGraphMsgHandler<G, C, L>
197 where C::Target: chain::Access, L::Target: Logger {
198         fn handle_event(&self, event: &Event) {
199                 if let Event::PaymentPathFailed { payment_hash: _, rejected_by_dest: _, network_update, .. } = event {
200                         if let Some(network_update) = network_update {
201                                 self.handle_network_update(network_update);
202                         }
203                 }
204         }
205 }
206
207 /// Receives and validates network updates from peers,
208 /// stores authentic and relevant data as a network graph.
209 /// This network graph is then used for routing payments.
210 /// Provides interface to help with initial routing sync by
211 /// serving historical announcements.
212 ///
213 /// Serves as an [`EventHandler`] for applying updates from [`Event::PaymentPathFailed`] to the
214 /// [`NetworkGraph`].
215 pub struct NetGraphMsgHandler<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref>
216 where C::Target: chain::Access, L::Target: Logger
217 {
218         secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
219         network_graph: G,
220         chain_access: Option<C>,
221         full_syncs_requested: AtomicUsize,
222         pending_events: Mutex<Vec<MessageSendEvent>>,
223         logger: L,
224 }
225
226 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> NetGraphMsgHandler<G, C, L>
227 where C::Target: chain::Access, L::Target: Logger
228 {
229         /// Creates a new tracker of the actual state of the network of channels and nodes,
230         /// assuming an existing Network Graph.
231         /// Chain monitor is used to make sure announced channels exist on-chain,
232         /// channel data is correct, and that the announcement is signed with
233         /// channel owners' keys.
234         pub fn new(network_graph: G, chain_access: Option<C>, logger: L) -> Self {
235                 NetGraphMsgHandler {
236                         secp_ctx: Secp256k1::verification_only(),
237                         network_graph,
238                         full_syncs_requested: AtomicUsize::new(0),
239                         chain_access,
240                         pending_events: Mutex::new(vec![]),
241                         logger,
242                 }
243         }
244
245         /// Adds a provider used to check new announcements. Does not affect
246         /// existing announcements unless they are updated.
247         /// Add, update or remove the provider would replace the current one.
248         pub fn add_chain_access(&mut self, chain_access: Option<C>) {
249                 self.chain_access = chain_access;
250         }
251
252         /// Gets a reference to the underlying [`NetworkGraph`] which was provided in
253         /// [`NetGraphMsgHandler::new`].
254         pub fn network_graph(&self) -> &G {
255                 &self.network_graph
256         }
257
258         /// Returns true when a full routing table sync should be performed with a peer.
259         fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
260                 //TODO: Determine whether to request a full sync based on the network map.
261                 const FULL_SYNCS_TO_REQUEST: usize = 5;
262                 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
263                         self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
264                         true
265                 } else {
266                         false
267                 }
268         }
269
270         /// Applies changes to the [`NetworkGraph`] from the given update.
271         fn handle_network_update(&self, update: &NetworkUpdate) {
272                 match *update {
273                         NetworkUpdate::ChannelUpdateMessage { ref msg } => {
274                                 let short_channel_id = msg.contents.short_channel_id;
275                                 let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
276                                 let status = if is_enabled { "enabled" } else { "disabled" };
277                                 log_debug!(self.logger, "Updating channel with channel_update from a payment failure. Channel {} is {}.", short_channel_id, status);
278                                 let _ = self.network_graph.update_channel(msg, &self.secp_ctx);
279                         },
280                         NetworkUpdate::ChannelClosed { short_channel_id, is_permanent } => {
281                                 let action = if is_permanent { "Removing" } else { "Disabling" };
282                                 log_debug!(self.logger, "{} channel graph entry for {} due to a payment failure.", action, short_channel_id);
283                                 self.network_graph.close_channel_from_update(short_channel_id, is_permanent);
284                         },
285                         NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
286                                 let action = if is_permanent { "Removing" } else { "Disabling" };
287                                 log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", action, node_id);
288                                 self.network_graph.fail_node(node_id, is_permanent);
289                         },
290                 }
291         }
292 }
293
294 macro_rules! secp_verify_sig {
295         ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
296                 match $secp_ctx.verify($msg, $sig, $pubkey) {
297                         Ok(_) => {},
298                         Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
299                 }
300         };
301 }
302
303 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> RoutingMessageHandler for NetGraphMsgHandler<G, C, L>
304 where C::Target: chain::Access, L::Target: Logger
305 {
306         fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
307                 self.network_graph.update_node_from_announcement(msg, &self.secp_ctx)?;
308                 Ok(msg.contents.excess_data.len() <=  MAX_EXCESS_BYTES_FOR_RELAY &&
309                    msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
310                    msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
311         }
312
313         fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
314                 self.network_graph.update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
315                 log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
316                 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
317         }
318
319         fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
320                 self.network_graph.update_channel(msg, &self.secp_ctx)?;
321                 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
322         }
323
324         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
325                 let mut result = Vec::with_capacity(batch_amount as usize);
326                 let channels = self.network_graph.channels.read().unwrap();
327                 let mut iter = channels.range(starting_point..);
328                 while result.len() < batch_amount as usize {
329                         if let Some((_, ref chan)) = iter.next() {
330                                 if chan.announcement_message.is_some() {
331                                         let chan_announcement = chan.announcement_message.clone().unwrap();
332                                         let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
333                                         let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
334                                         if let Some(one_to_two) = chan.one_to_two.as_ref() {
335                                                 one_to_two_announcement = one_to_two.last_update_message.clone();
336                                         }
337                                         if let Some(two_to_one) = chan.two_to_one.as_ref() {
338                                                 two_to_one_announcement = two_to_one.last_update_message.clone();
339                                         }
340                                         result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
341                                 } else {
342                                         // TODO: We may end up sending un-announced channel_updates if we are sending
343                                         // initial sync data while receiving announce/updates for this channel.
344                                 }
345                         } else {
346                                 return result;
347                         }
348                 }
349                 result
350         }
351
352         fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
353                 let mut result = Vec::with_capacity(batch_amount as usize);
354                 let nodes = self.network_graph.nodes.read().unwrap();
355                 let mut iter = if let Some(pubkey) = starting_point {
356                                 let mut iter = nodes.range(NodeId::from_pubkey(pubkey)..);
357                                 iter.next();
358                                 iter
359                         } else {
360                                 nodes.range::<NodeId, _>(..)
361                         };
362                 while result.len() < batch_amount as usize {
363                         if let Some((_, ref node)) = iter.next() {
364                                 if let Some(node_info) = node.announcement_info.as_ref() {
365                                         if node_info.announcement_message.is_some() {
366                                                 result.push(node_info.announcement_message.clone().unwrap());
367                                         }
368                                 }
369                         } else {
370                                 return result;
371                         }
372                 }
373                 result
374         }
375
376         /// Initiates a stateless sync of routing gossip information with a peer
377         /// using gossip_queries. The default strategy used by this implementation
378         /// is to sync the full block range with several peers.
379         ///
380         /// We should expect one or more reply_channel_range messages in response
381         /// to our query_channel_range. Each reply will enqueue a query_scid message
382         /// to request gossip messages for each channel. The sync is considered complete
383         /// when the final reply_scids_end message is received, though we are not
384         /// tracking this directly.
385         fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
386
387                 // We will only perform a sync with peers that support gossip_queries.
388                 if !init_msg.features.supports_gossip_queries() {
389                         return ();
390                 }
391
392                 // Check if we need to perform a full synchronization with this peer
393                 if !self.should_request_full_sync(&their_node_id) {
394                         return ();
395                 }
396
397                 let first_blocknum = 0;
398                 let number_of_blocks = 0xffffffff;
399                 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
400                 let mut pending_events = self.pending_events.lock().unwrap();
401                 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
402                         node_id: their_node_id.clone(),
403                         msg: QueryChannelRange {
404                                 chain_hash: self.network_graph.genesis_hash,
405                                 first_blocknum,
406                                 number_of_blocks,
407                         },
408                 });
409         }
410
411         /// Statelessly processes a reply to a channel range query by immediately
412         /// sending an SCID query with SCIDs in the reply. To keep this handler
413         /// stateless, it does not validate the sequencing of replies for multi-
414         /// reply ranges. It does not validate whether the reply(ies) cover the
415         /// queried range. It also does not filter SCIDs to only those in the
416         /// original query range. We also do not validate that the chain_hash
417         /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
418         /// does not match our chain_hash will be rejected when the announcement is
419         /// processed.
420         fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
421                 log_debug!(self.logger, "Handling reply_channel_range peer={}, first_blocknum={}, number_of_blocks={}, sync_complete={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.sync_complete, msg.short_channel_ids.len(),);
422
423                 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
424                 let mut pending_events = self.pending_events.lock().unwrap();
425                 pending_events.push(MessageSendEvent::SendShortIdsQuery {
426                         node_id: their_node_id.clone(),
427                         msg: QueryShortChannelIds {
428                                 chain_hash: msg.chain_hash,
429                                 short_channel_ids: msg.short_channel_ids,
430                         }
431                 });
432
433                 Ok(())
434         }
435
436         /// When an SCID query is initiated the remote peer will begin streaming
437         /// gossip messages. In the event of a failure, we may have received
438         /// some channel information. Before trying with another peer, the
439         /// caller should update its set of SCIDs that need to be queried.
440         fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
441                 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
442
443                 // If the remote node does not have up-to-date information for the
444                 // chain_hash they will set full_information=false. We can fail
445                 // the result and try again with a different peer.
446                 if !msg.full_information {
447                         return Err(LightningError {
448                                 err: String::from("Received reply_short_channel_ids_end with no information"),
449                                 action: ErrorAction::IgnoreError
450                         });
451                 }
452
453                 Ok(())
454         }
455
456         /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
457         /// are in the specified block range. Due to message size limits, large range
458         /// queries may result in several reply messages. This implementation enqueues
459         /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
460         /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
461         /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
462         /// memory constrained systems.
463         fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
464                 log_debug!(self.logger, "Handling query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks);
465
466                 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
467
468                 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
469                 // If so, we manually cap the ending block to avoid this overflow.
470                 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
471
472                 // Per spec, we must reply to a query. Send an empty message when things are invalid.
473                 if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
474                         let mut pending_events = self.pending_events.lock().unwrap();
475                         pending_events.push(MessageSendEvent::SendReplyChannelRange {
476                                 node_id: their_node_id.clone(),
477                                 msg: ReplyChannelRange {
478                                         chain_hash: msg.chain_hash.clone(),
479                                         first_blocknum: msg.first_blocknum,
480                                         number_of_blocks: msg.number_of_blocks,
481                                         sync_complete: true,
482                                         short_channel_ids: vec![],
483                                 }
484                         });
485                         return Err(LightningError {
486                                 err: String::from("query_channel_range could not be processed"),
487                                 action: ErrorAction::IgnoreError,
488                         });
489                 }
490
491                 // Creates channel batches. We are not checking if the channel is routable
492                 // (has at least one update). A peer may still want to know the channel
493                 // exists even if its not yet routable.
494                 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
495                 let channels = self.network_graph.channels.read().unwrap();
496                 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
497                         if let Some(chan_announcement) = &chan.announcement_message {
498                                 // Construct a new batch if last one is full
499                                 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
500                                         batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
501                                 }
502
503                                 let batch = batches.last_mut().unwrap();
504                                 batch.push(chan_announcement.contents.short_channel_id);
505                         }
506                 }
507                 drop(channels);
508
509                 let mut pending_events = self.pending_events.lock().unwrap();
510                 let batch_count = batches.len();
511                 let mut prev_batch_endblock = msg.first_blocknum;
512                 for (batch_index, batch) in batches.into_iter().enumerate() {
513                         // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
514                         // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
515                         //
516                         // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
517                         // reply is >= the previous reply's `first_blocknum` and either exactly the previous
518                         // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
519                         // significant diversion from the requirements set by the spec, and, in case of blocks
520                         // with no channel opens (e.g. empty blocks), requires that we use the previous value
521                         // and *not* derive the first_blocknum from the actual first block of the reply.
522                         let first_blocknum = prev_batch_endblock;
523
524                         // Each message carries the number of blocks (from the `first_blocknum`) its contents
525                         // fit in. Though there is no requirement that we use exactly the number of blocks its
526                         // contents are from, except for the bogus requirements c-lightning enforces, above.
527                         //
528                         // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
529                         // >= the query's end block. Thus, for the last reply, we calculate the difference
530                         // between the query's end block and the start of the reply.
531                         //
532                         // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
533                         // first_blocknum will be either msg.first_blocknum or a higher block height.
534                         let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
535                                 (true, msg.end_blocknum() - first_blocknum)
536                         }
537                         // Prior replies should use the number of blocks that fit into the reply. Overflow
538                         // safe since first_blocknum is always <= last SCID's block.
539                         else {
540                                 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
541                         };
542
543                         prev_batch_endblock = first_blocknum + number_of_blocks;
544
545                         pending_events.push(MessageSendEvent::SendReplyChannelRange {
546                                 node_id: their_node_id.clone(),
547                                 msg: ReplyChannelRange {
548                                         chain_hash: msg.chain_hash.clone(),
549                                         first_blocknum,
550                                         number_of_blocks,
551                                         sync_complete,
552                                         short_channel_ids: batch,
553                                 }
554                         });
555                 }
556
557                 Ok(())
558         }
559
560         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
561                 // TODO
562                 Err(LightningError {
563                         err: String::from("Not implemented"),
564                         action: ErrorAction::IgnoreError,
565                 })
566         }
567 }
568
569 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<G, C, L>
570 where
571         C::Target: chain::Access,
572         L::Target: Logger,
573 {
574         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
575                 let mut ret = Vec::new();
576                 let mut pending_events = self.pending_events.lock().unwrap();
577                 core::mem::swap(&mut ret, &mut pending_events);
578                 ret
579         }
580 }
581
582 #[derive(Clone, Debug, PartialEq)]
583 /// Details about one direction of a channel. Received
584 /// within a channel update.
585 pub struct DirectionalChannelInfo {
586         /// When the last update to the channel direction was issued.
587         /// Value is opaque, as set in the announcement.
588         pub last_update: u32,
589         /// Whether the channel can be currently used for payments (in this one direction).
590         pub enabled: bool,
591         /// The difference in CLTV values that you must have when routing through this channel.
592         pub cltv_expiry_delta: u16,
593         /// The minimum value, which must be relayed to the next hop via the channel
594         pub htlc_minimum_msat: u64,
595         /// The maximum value which may be relayed to the next hop via the channel.
596         pub htlc_maximum_msat: Option<u64>,
597         /// Fees charged when the channel is used for routing
598         pub fees: RoutingFees,
599         /// Most recent update for the channel received from the network
600         /// Mostly redundant with the data we store in fields explicitly.
601         /// Everything else is useful only for sending out for initial routing sync.
602         /// Not stored if contains excess data to prevent DoS.
603         pub last_update_message: Option<ChannelUpdate>,
604 }
605
606 impl fmt::Display for DirectionalChannelInfo {
607         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
608                 write!(f, "last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fees {:?}", self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fees)?;
609                 Ok(())
610         }
611 }
612
613 impl_writeable_tlv_based!(DirectionalChannelInfo, {
614         (0, last_update, required),
615         (2, enabled, required),
616         (4, cltv_expiry_delta, required),
617         (6, htlc_minimum_msat, required),
618         (8, htlc_maximum_msat, required),
619         (10, fees, required),
620         (12, last_update_message, required),
621 });
622
623 #[derive(Clone, Debug, PartialEq)]
624 /// Details about a channel (both directions).
625 /// Received within a channel announcement.
626 pub struct ChannelInfo {
627         /// Protocol features of a channel communicated during its announcement
628         pub features: ChannelFeatures,
629         /// Source node of the first direction of a channel
630         pub node_one: NodeId,
631         /// Details about the first direction of a channel
632         pub one_to_two: Option<DirectionalChannelInfo>,
633         /// Source node of the second direction of a channel
634         pub node_two: NodeId,
635         /// Details about the second direction of a channel
636         pub two_to_one: Option<DirectionalChannelInfo>,
637         /// The channel capacity as seen on-chain, if chain lookup is available.
638         pub capacity_sats: Option<u64>,
639         /// An initial announcement of the channel
640         /// Mostly redundant with the data we store in fields explicitly.
641         /// Everything else is useful only for sending out for initial routing sync.
642         /// Not stored if contains excess data to prevent DoS.
643         pub announcement_message: Option<ChannelAnnouncement>,
644         /// The timestamp when we received the announcement, if we are running with feature = "std"
645         /// (which we can probably assume we are - no-std environments probably won't have a full
646         /// network graph in memory!).
647         announcement_received_time: u64,
648 }
649
650 impl fmt::Display for ChannelInfo {
651         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
652                 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
653                    log_bytes!(self.features.encode()), log_bytes!(self.node_one.as_slice()), self.one_to_two, log_bytes!(self.node_two.as_slice()), self.two_to_one)?;
654                 Ok(())
655         }
656 }
657
658 impl_writeable_tlv_based!(ChannelInfo, {
659         (0, features, required),
660         (1, announcement_received_time, (default_value, 0)),
661         (2, node_one, required),
662         (4, one_to_two, required),
663         (6, node_two, required),
664         (8, two_to_one, required),
665         (10, capacity_sats, required),
666         (12, announcement_message, required),
667 });
668
669
670 /// Fees for routing via a given channel or a node
671 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
672 pub struct RoutingFees {
673         /// Flat routing fee in satoshis
674         pub base_msat: u32,
675         /// Liquidity-based routing fee in millionths of a routed amount.
676         /// In other words, 10000 is 1%.
677         pub proportional_millionths: u32,
678 }
679
680 impl_writeable_tlv_based!(RoutingFees, {
681         (0, base_msat, required),
682         (2, proportional_millionths, required)
683 });
684
685 #[derive(Clone, Debug, PartialEq)]
686 /// Information received in the latest node_announcement from this node.
687 pub struct NodeAnnouncementInfo {
688         /// Protocol features the node announced support for
689         pub features: NodeFeatures,
690         /// When the last known update to the node state was issued.
691         /// Value is opaque, as set in the announcement.
692         pub last_update: u32,
693         /// Color assigned to the node
694         pub rgb: [u8; 3],
695         /// Moniker assigned to the node.
696         /// May be invalid or malicious (eg control chars),
697         /// should not be exposed to the user.
698         pub alias: [u8; 32],
699         /// Internet-level addresses via which one can connect to the node
700         pub addresses: Vec<NetAddress>,
701         /// An initial announcement of the node
702         /// Mostly redundant with the data we store in fields explicitly.
703         /// Everything else is useful only for sending out for initial routing sync.
704         /// Not stored if contains excess data to prevent DoS.
705         pub announcement_message: Option<NodeAnnouncement>
706 }
707
708 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
709         (0, features, required),
710         (2, last_update, required),
711         (4, rgb, required),
712         (6, alias, required),
713         (8, announcement_message, option),
714         (10, addresses, vec_type),
715 });
716
717 #[derive(Clone, Debug, PartialEq)]
718 /// Details about a node in the network, known from the network announcement.
719 pub struct NodeInfo {
720         /// All valid channels a node has announced
721         pub channels: Vec<u64>,
722         /// Lowest fees enabling routing via any of the enabled, known channels to a node.
723         /// The two fields (flat and proportional fee) are independent,
724         /// meaning they don't have to refer to the same channel.
725         pub lowest_inbound_channel_fees: Option<RoutingFees>,
726         /// More information about a node from node_announcement.
727         /// Optional because we store a Node entry after learning about it from
728         /// a channel announcement, but before receiving a node announcement.
729         pub announcement_info: Option<NodeAnnouncementInfo>
730 }
731
732 impl fmt::Display for NodeInfo {
733         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
734                 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
735                    self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
736                 Ok(())
737         }
738 }
739
740 impl_writeable_tlv_based!(NodeInfo, {
741         (0, lowest_inbound_channel_fees, option),
742         (2, announcement_info, option),
743         (4, channels, vec_type),
744 });
745
746 const SERIALIZATION_VERSION: u8 = 1;
747 const MIN_SERIALIZATION_VERSION: u8 = 1;
748
749 impl Writeable for NetworkGraph {
750         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
751                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
752
753                 self.genesis_hash.write(writer)?;
754                 let channels = self.channels.read().unwrap();
755                 (channels.len() as u64).write(writer)?;
756                 for (ref chan_id, ref chan_info) in channels.iter() {
757                         (*chan_id).write(writer)?;
758                         chan_info.write(writer)?;
759                 }
760                 let nodes = self.nodes.read().unwrap();
761                 (nodes.len() as u64).write(writer)?;
762                 for (ref node_id, ref node_info) in nodes.iter() {
763                         node_id.write(writer)?;
764                         node_info.write(writer)?;
765                 }
766
767                 write_tlv_fields!(writer, {});
768                 Ok(())
769         }
770 }
771
772 impl Readable for NetworkGraph {
773         fn read<R: io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
774                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
775
776                 let genesis_hash: BlockHash = Readable::read(reader)?;
777                 let channels_count: u64 = Readable::read(reader)?;
778                 let mut channels = BTreeMap::new();
779                 for _ in 0..channels_count {
780                         let chan_id: u64 = Readable::read(reader)?;
781                         let chan_info = Readable::read(reader)?;
782                         channels.insert(chan_id, chan_info);
783                 }
784                 let nodes_count: u64 = Readable::read(reader)?;
785                 let mut nodes = BTreeMap::new();
786                 for _ in 0..nodes_count {
787                         let node_id = Readable::read(reader)?;
788                         let node_info = Readable::read(reader)?;
789                         nodes.insert(node_id, node_info);
790                 }
791                 read_tlv_fields!(reader, {});
792
793                 Ok(NetworkGraph {
794                         genesis_hash,
795                         channels: RwLock::new(channels),
796                         nodes: RwLock::new(nodes),
797                 })
798         }
799 }
800
801 impl fmt::Display for NetworkGraph {
802         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
803                 writeln!(f, "Network map\n[Channels]")?;
804                 for (key, val) in self.channels.read().unwrap().iter() {
805                         writeln!(f, " {}: {}", key, val)?;
806                 }
807                 writeln!(f, "[Nodes]")?;
808                 for (&node_id, val) in self.nodes.read().unwrap().iter() {
809                         writeln!(f, " {}: {}", log_bytes!(node_id.as_slice()), val)?;
810                 }
811                 Ok(())
812         }
813 }
814
815 impl PartialEq for NetworkGraph {
816         fn eq(&self, other: &Self) -> bool {
817                 self.genesis_hash == other.genesis_hash &&
818                         *self.channels.read().unwrap() == *other.channels.read().unwrap() &&
819                         *self.nodes.read().unwrap() == *other.nodes.read().unwrap()
820         }
821 }
822
823 impl NetworkGraph {
824         /// Creates a new, empty, network graph.
825         pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
826                 Self {
827                         genesis_hash,
828                         channels: RwLock::new(BTreeMap::new()),
829                         nodes: RwLock::new(BTreeMap::new()),
830                 }
831         }
832
833         /// Returns a read-only view of the network graph.
834         pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
835                 let channels = self.channels.read().unwrap();
836                 let nodes = self.nodes.read().unwrap();
837                 ReadOnlyNetworkGraph {
838                         channels,
839                         nodes,
840                 }
841         }
842
843         /// For an already known node (from channel announcements), update its stored properties from a
844         /// given node announcement.
845         ///
846         /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
847         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
848         /// routing messages from a source using a protocol other than the lightning P2P protocol.
849         pub fn update_node_from_announcement<T: secp256k1::Verification>(&self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
850                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
851                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
852                 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
853         }
854
855         /// For an already known node (from channel announcements), update its stored properties from a
856         /// given node announcement without verifying the associated signatures. Because we aren't
857         /// given the associated signatures here we cannot relay the node announcement to any of our
858         /// peers.
859         pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
860                 self.update_node_from_announcement_intern(msg, None)
861         }
862
863         fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
864                 match self.nodes.write().unwrap().get_mut(&NodeId::from_pubkey(&msg.node_id)) {
865                         None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
866                         Some(node) => {
867                                 if let Some(node_info) = node.announcement_info.as_ref() {
868                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
869                                         // updates to ensure you always have the latest one, only vaguely suggesting
870                                         // that it be at least the current time.
871                                         if node_info.last_update  > msg.timestamp {
872                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
873                                         } else if node_info.last_update  == msg.timestamp {
874                                                 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
875                                         }
876                                 }
877
878                                 let should_relay =
879                                         msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
880                                         msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
881                                         msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
882                                 node.announcement_info = Some(NodeAnnouncementInfo {
883                                         features: msg.features.clone(),
884                                         last_update: msg.timestamp,
885                                         rgb: msg.rgb,
886                                         alias: msg.alias,
887                                         addresses: msg.addresses.clone(),
888                                         announcement_message: if should_relay { full_msg.cloned() } else { None },
889                                 });
890
891                                 Ok(())
892                         }
893                 }
894         }
895
896         /// Store or update channel info from a channel announcement.
897         ///
898         /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
899         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
900         /// routing messages from a source using a protocol other than the lightning P2P protocol.
901         ///
902         /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
903         /// the corresponding UTXO exists on chain and is correctly-formatted.
904         pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>(
905                 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>
906         ) -> Result<(), LightningError>
907         where
908                 C::Target: chain::Access,
909         {
910                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
911                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
912                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
913                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
914                 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
915                 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
916         }
917
918         /// Store or update channel info from a channel announcement without verifying the associated
919         /// signatures. Because we aren't given the associated signatures here we cannot relay the
920         /// channel announcement to any of our peers.
921         ///
922         /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
923         /// the corresponding UTXO exists on chain and is correctly-formatted.
924         pub fn update_channel_from_unsigned_announcement<C: Deref>(
925                 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
926         ) -> Result<(), LightningError>
927         where
928                 C::Target: chain::Access,
929         {
930                 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
931         }
932
933         fn update_channel_from_unsigned_announcement_intern<C: Deref>(
934                 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
935         ) -> Result<(), LightningError>
936         where
937                 C::Target: chain::Access,
938         {
939                 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
940                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
941                 }
942
943                 let utxo_value = match &chain_access {
944                         &None => {
945                                 // Tentatively accept, potentially exposing us to DoS attacks
946                                 None
947                         },
948                         &Some(ref chain_access) => {
949                                 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
950                                         Ok(TxOut { value, script_pubkey }) => {
951                                                 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
952                                                                                     .push_slice(&msg.bitcoin_key_1.serialize())
953                                                                                     .push_slice(&msg.bitcoin_key_2.serialize())
954                                                                                     .push_opcode(opcodes::all::OP_PUSHNUM_2)
955                                                                                     .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
956                                                 if script_pubkey != expected_script {
957                                                         return Err(LightningError{err: format!("Channel announcement key ({}) didn't match on-chain script ({})", script_pubkey.to_hex(), expected_script.to_hex()), action: ErrorAction::IgnoreError});
958                                                 }
959                                                 //TODO: Check if value is worth storing, use it to inform routing, and compare it
960                                                 //to the new HTLC max field in channel_update
961                                                 Some(value)
962                                         },
963                                         Err(chain::AccessError::UnknownChain) => {
964                                                 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
965                                         },
966                                         Err(chain::AccessError::UnknownTx) => {
967                                                 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
968                                         },
969                                 }
970                         },
971                 };
972
973                 #[allow(unused_mut, unused_assignments)]
974                 let mut announcement_received_time = 0;
975                 #[cfg(feature = "std")]
976                 {
977                         announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
978                 }
979
980                 let chan_info = ChannelInfo {
981                                 features: msg.features.clone(),
982                                 node_one: NodeId::from_pubkey(&msg.node_id_1),
983                                 one_to_two: None,
984                                 node_two: NodeId::from_pubkey(&msg.node_id_2),
985                                 two_to_one: None,
986                                 capacity_sats: utxo_value,
987                                 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
988                                         { full_msg.cloned() } else { None },
989                                 announcement_received_time,
990                         };
991
992                 let mut channels = self.channels.write().unwrap();
993                 let mut nodes = self.nodes.write().unwrap();
994                 match channels.entry(msg.short_channel_id) {
995                         BtreeEntry::Occupied(mut entry) => {
996                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
997                                 //in the blockchain API, we need to handle it smartly here, though it's unclear
998                                 //exactly how...
999                                 if utxo_value.is_some() {
1000                                         // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1001                                         // only sometimes returns results. In any case remove the previous entry. Note
1002                                         // that the spec expects us to "blacklist" the node_ids involved, but we can't
1003                                         // do that because
1004                                         // a) we don't *require* a UTXO provider that always returns results.
1005                                         // b) we don't track UTXOs of channels we know about and remove them if they
1006                                         //    get reorg'd out.
1007                                         // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1008                                         Self::remove_channel_in_nodes(&mut nodes, &entry.get(), msg.short_channel_id);
1009                                         *entry.get_mut() = chan_info;
1010                                 } else {
1011                                         return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1012                                 }
1013                         },
1014                         BtreeEntry::Vacant(entry) => {
1015                                 entry.insert(chan_info);
1016                         }
1017                 };
1018
1019                 macro_rules! add_channel_to_node {
1020                         ( $node_id: expr ) => {
1021                                 match nodes.entry($node_id) {
1022                                         BtreeEntry::Occupied(node_entry) => {
1023                                                 node_entry.into_mut().channels.push(msg.short_channel_id);
1024                                         },
1025                                         BtreeEntry::Vacant(node_entry) => {
1026                                                 node_entry.insert(NodeInfo {
1027                                                         channels: vec!(msg.short_channel_id),
1028                                                         lowest_inbound_channel_fees: None,
1029                                                         announcement_info: None,
1030                                                 });
1031                                         }
1032                                 }
1033                         };
1034                 }
1035
1036                 add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_1));
1037                 add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_2));
1038
1039                 Ok(())
1040         }
1041
1042         /// Close a channel if a corresponding HTLC fail was sent.
1043         /// If permanent, removes a channel from the local storage.
1044         /// May cause the removal of nodes too, if this was their last channel.
1045         /// If not permanent, makes channels unavailable for routing.
1046         pub fn close_channel_from_update(&self, short_channel_id: u64, is_permanent: bool) {
1047                 let mut channels = self.channels.write().unwrap();
1048                 if is_permanent {
1049                         if let Some(chan) = channels.remove(&short_channel_id) {
1050                                 let mut nodes = self.nodes.write().unwrap();
1051                                 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1052                         }
1053                 } else {
1054                         if let Some(chan) = channels.get_mut(&short_channel_id) {
1055                                 if let Some(one_to_two) = chan.one_to_two.as_mut() {
1056                                         one_to_two.enabled = false;
1057                                 }
1058                                 if let Some(two_to_one) = chan.two_to_one.as_mut() {
1059                                         two_to_one.enabled = false;
1060                                 }
1061                         }
1062                 }
1063         }
1064
1065         /// Marks a node in the graph as failed.
1066         pub fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
1067                 if is_permanent {
1068                         // TODO: Wholly remove the node
1069                 } else {
1070                         // TODO: downgrade the node
1071                 }
1072         }
1073
1074         #[cfg(feature = "std")]
1075         /// Removes information about channels that we haven't heard any updates about in some time.
1076         /// This can be used regularly to prune the network graph of channels that likely no longer
1077         /// exist.
1078         ///
1079         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1080         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1081         /// pruning occur for updates which are at least two weeks old, which we implement here.
1082         ///
1083         /// Note that for users of the `lightning-background-processor` crate this method may be
1084         /// automatically called regularly for you.
1085         ///
1086         /// This method is only available with the `std` feature. See
1087         /// [`NetworkGraph::remove_stale_channels_with_time`] for `no-std` use.
1088         pub fn remove_stale_channels(&self) {
1089                 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1090                 self.remove_stale_channels_with_time(time);
1091         }
1092
1093         /// Removes information about channels that we haven't heard any updates about in some time.
1094         /// This can be used regularly to prune the network graph of channels that likely no longer
1095         /// exist.
1096         ///
1097         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1098         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1099         /// pruning occur for updates which are at least two weeks old, which we implement here.
1100         ///
1101         /// This function takes the current unix time as an argument. For users with the `std` feature
1102         /// enabled, [`NetworkGraph::remove_stale_channels`] may be preferable.
1103         pub fn remove_stale_channels_with_time(&self, current_time_unix: u64) {
1104                 let mut channels = self.channels.write().unwrap();
1105                 // Time out if we haven't received an update in at least 14 days.
1106                 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1107                 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1108                 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1109                 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1110                 // time.
1111                 let mut scids_to_remove = Vec::new();
1112                 for (scid, info) in channels.iter_mut() {
1113                         if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1114                                 info.one_to_two = None;
1115                         }
1116                         if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1117                                 info.two_to_one = None;
1118                         }
1119                         if info.one_to_two.is_none() && info.two_to_one.is_none() {
1120                                 // We check the announcement_received_time here to ensure we don't drop
1121                                 // announcements that we just received and are just waiting for our peer to send a
1122                                 // channel_update for.
1123                                 if info.announcement_received_time < min_time_unix as u64 {
1124                                         scids_to_remove.push(*scid);
1125                                 }
1126                         }
1127                 }
1128                 if !scids_to_remove.is_empty() {
1129                         let mut nodes = self.nodes.write().unwrap();
1130                         for scid in scids_to_remove {
1131                                 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1132                                 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
1133                         }
1134                 }
1135         }
1136
1137         /// For an already known (from announcement) channel, update info about one of the directions
1138         /// of the channel.
1139         ///
1140         /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1141         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1142         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1143         ///
1144         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1145         /// materially in the future will be rejected.
1146         pub fn update_channel<T: secp256k1::Verification>(&self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
1147                 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
1148         }
1149
1150         /// For an already known (from announcement) channel, update info about one of the directions
1151         /// of the channel without verifying the associated signatures. Because we aren't given the
1152         /// associated signatures here we cannot relay the channel update to any of our peers.
1153         ///
1154         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1155         /// materially in the future will be rejected.
1156         pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1157                 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
1158         }
1159
1160         fn update_channel_intern<T: secp256k1::Verification>(&self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate>, sig_info: Option<(&secp256k1::Signature, &Secp256k1<T>)>) -> Result<(), LightningError> {
1161                 let dest_node_id;
1162                 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
1163                 let chan_was_enabled;
1164
1165                 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
1166                 {
1167                         // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
1168                         // disable this check during tests!
1169                         let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1170                         if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
1171                                 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreError});
1172                         }
1173                         if msg.timestamp as u64 > time + 60 * 60 * 24 {
1174                                 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreError});
1175                         }
1176                 }
1177
1178                 let mut channels = self.channels.write().unwrap();
1179                 match channels.get_mut(&msg.short_channel_id) {
1180                         None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
1181                         Some(channel) => {
1182                                 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
1183                                         if htlc_maximum_msat > MAX_VALUE_MSAT {
1184                                                 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
1185                                         }
1186
1187                                         if let Some(capacity_sats) = channel.capacity_sats {
1188                                                 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1189                                                 // Don't query UTXO set here to reduce DoS risks.
1190                                                 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1191                                                         return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1192                                                 }
1193                                         }
1194                                 }
1195                                 macro_rules! maybe_update_channel_info {
1196                                         ( $target: expr, $src_node: expr) => {
1197                                                 if let Some(existing_chan_info) = $target.as_ref() {
1198                                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to
1199                                                         // order updates to ensure you always have the latest one, only
1200                                                         // suggesting  that it be at least the current time. For
1201                                                         // channel_updates specifically, the BOLTs discuss the possibility of
1202                                                         // pruning based on the timestamp field being more than two weeks old,
1203                                                         // but only in the non-normative section.
1204                                                         if existing_chan_info.last_update > msg.timestamp {
1205                                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1206                                                         } else if existing_chan_info.last_update == msg.timestamp {
1207                                                                 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1208                                                         }
1209                                                         chan_was_enabled = existing_chan_info.enabled;
1210                                                 } else {
1211                                                         chan_was_enabled = false;
1212                                                 }
1213
1214                                                 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1215                                                         { full_msg.cloned() } else { None };
1216
1217                                                 let updated_channel_dir_info = DirectionalChannelInfo {
1218                                                         enabled: chan_enabled,
1219                                                         last_update: msg.timestamp,
1220                                                         cltv_expiry_delta: msg.cltv_expiry_delta,
1221                                                         htlc_minimum_msat: msg.htlc_minimum_msat,
1222                                                         htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1223                                                         fees: RoutingFees {
1224                                                                 base_msat: msg.fee_base_msat,
1225                                                                 proportional_millionths: msg.fee_proportional_millionths,
1226                                                         },
1227                                                         last_update_message
1228                                                 };
1229                                                 $target = Some(updated_channel_dir_info);
1230                                         }
1231                                 }
1232
1233                                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1234                                 if msg.flags & 1 == 1 {
1235                                         dest_node_id = channel.node_one.clone();
1236                                         if let Some((sig, ctx)) = sig_info {
1237                                                 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
1238                                                         err: "Couldn't parse source node pubkey".to_owned(),
1239                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
1240                                                 })?);
1241                                         }
1242                                         maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1243                                 } else {
1244                                         dest_node_id = channel.node_two.clone();
1245                                         if let Some((sig, ctx)) = sig_info {
1246                                                 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
1247                                                         err: "Couldn't parse destination node pubkey".to_owned(),
1248                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
1249                                                 })?);
1250                                         }
1251                                         maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1252                                 }
1253                         }
1254                 }
1255
1256                 let mut nodes = self.nodes.write().unwrap();
1257                 if chan_enabled {
1258                         let node = nodes.get_mut(&dest_node_id).unwrap();
1259                         let mut base_msat = msg.fee_base_msat;
1260                         let mut proportional_millionths = msg.fee_proportional_millionths;
1261                         if let Some(fees) = node.lowest_inbound_channel_fees {
1262                                 base_msat = cmp::min(base_msat, fees.base_msat);
1263                                 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1264                         }
1265                         node.lowest_inbound_channel_fees = Some(RoutingFees {
1266                                 base_msat,
1267                                 proportional_millionths
1268                         });
1269                 } else if chan_was_enabled {
1270                         let node = nodes.get_mut(&dest_node_id).unwrap();
1271                         let mut lowest_inbound_channel_fees = None;
1272
1273                         for chan_id in node.channels.iter() {
1274                                 let chan = channels.get(chan_id).unwrap();
1275                                 let chan_info_opt;
1276                                 if chan.node_one == dest_node_id {
1277                                         chan_info_opt = chan.two_to_one.as_ref();
1278                                 } else {
1279                                         chan_info_opt = chan.one_to_two.as_ref();
1280                                 }
1281                                 if let Some(chan_info) = chan_info_opt {
1282                                         if chan_info.enabled {
1283                                                 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1284                                                         base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1285                                                 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1286                                                 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1287                                         }
1288                                 }
1289                         }
1290
1291                         node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1292                 }
1293
1294                 Ok(())
1295         }
1296
1297         fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1298                 macro_rules! remove_from_node {
1299                         ($node_id: expr) => {
1300                                 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1301                                         entry.get_mut().channels.retain(|chan_id| {
1302                                                 short_channel_id != *chan_id
1303                                         });
1304                                         if entry.get().channels.is_empty() {
1305                                                 entry.remove_entry();
1306                                         }
1307                                 } else {
1308                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1309                                 }
1310                         }
1311                 }
1312
1313                 remove_from_node!(chan.node_one);
1314                 remove_from_node!(chan.node_two);
1315         }
1316 }
1317
1318 impl ReadOnlyNetworkGraph<'_> {
1319         /// Returns all known valid channels' short ids along with announced channel info.
1320         ///
1321         /// (C-not exported) because we have no mapping for `BTreeMap`s
1322         pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1323                 &*self.channels
1324         }
1325
1326         /// Returns all known nodes' public keys along with announced node info.
1327         ///
1328         /// (C-not exported) because we have no mapping for `BTreeMap`s
1329         pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
1330                 &*self.nodes
1331         }
1332
1333         /// Get network addresses by node id.
1334         /// Returns None if the requested node is completely unknown,
1335         /// or if node announcement for the node was never received.
1336         pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
1337                 if let Some(node) = self.nodes.get(&NodeId::from_pubkey(&pubkey)) {
1338                         if let Some(node_info) = node.announcement_info.as_ref() {
1339                                 return Some(node_info.addresses.clone())
1340                         }
1341                 }
1342                 None
1343         }
1344 }
1345
1346 #[cfg(test)]
1347 mod tests {
1348         use chain;
1349         use ln::PaymentHash;
1350         use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1351         use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, NetworkUpdate, MAX_EXCESS_BYTES_FOR_RELAY};
1352         use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1353                 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, 
1354                 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1355         use util::test_utils;
1356         use util::logger::Logger;
1357         use util::ser::{Readable, Writeable};
1358         use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
1359         use util::scid_utils::scid_from_parts;
1360
1361         use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
1362
1363         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1364         use bitcoin::hashes::Hash;
1365         use bitcoin::network::constants::Network;
1366         use bitcoin::blockdata::constants::genesis_block;
1367         use bitcoin::blockdata::script::{Builder, Script};
1368         use bitcoin::blockdata::transaction::TxOut;
1369         use bitcoin::blockdata::opcodes;
1370
1371         use hex;
1372
1373         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1374         use bitcoin::secp256k1::{All, Secp256k1};
1375
1376         use io;
1377         use prelude::*;
1378         use sync::Arc;
1379
1380         fn create_network_graph() -> NetworkGraph {
1381                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1382                 NetworkGraph::new(genesis_hash)
1383         }
1384
1385         fn create_net_graph_msg_handler(network_graph: &NetworkGraph) -> (
1386                 Secp256k1<All>, NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
1387         ) {
1388                 let secp_ctx = Secp256k1::new();
1389                 let logger = Arc::new(test_utils::TestLogger::new());
1390                 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1391                 (secp_ctx, net_graph_msg_handler)
1392         }
1393
1394         #[test]
1395         fn request_full_sync_finite_times() {
1396                 let network_graph = create_network_graph();
1397                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1398                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1399
1400                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1401                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1402                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1403                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1404                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1405                 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1406         }
1407
1408         fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
1409                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_key);
1410                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1411                         features: NodeFeatures::known(),
1412                         timestamp: 100,
1413                         node_id: node_id,
1414                         rgb: [0; 3],
1415                         alias: [0; 32],
1416                         addresses: Vec::new(),
1417                         excess_address_data: Vec::new(),
1418                         excess_data: Vec::new(),
1419                 };
1420                 f(&mut unsigned_announcement);
1421                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1422                 NodeAnnouncement {
1423                         signature: secp_ctx.sign(&msghash, node_key),
1424                         contents: unsigned_announcement
1425                 }
1426         }
1427
1428         fn get_signed_channel_announcement<F: Fn(&mut UnsignedChannelAnnouncement)>(f: F, node_1_key: &SecretKey, node_2_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelAnnouncement {
1429                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
1430                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
1431                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1432                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1433
1434                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1435                         features: ChannelFeatures::known(),
1436                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1437                         short_channel_id: 0,
1438                         node_id_1,
1439                         node_id_2,
1440                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1441                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1442                         excess_data: Vec::new(),
1443                 };
1444                 f(&mut unsigned_announcement);
1445                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1446                 ChannelAnnouncement {
1447                         node_signature_1: secp_ctx.sign(&msghash, node_1_key),
1448                         node_signature_2: secp_ctx.sign(&msghash, node_2_key),
1449                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1450                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1451                         contents: unsigned_announcement,
1452                 }
1453         }
1454
1455         fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> Script {
1456                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1457                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1458                 Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1459                               .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1460                               .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1461                               .push_opcode(opcodes::all::OP_PUSHNUM_2)
1462                               .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
1463                               .to_v0_p2wsh()
1464         }
1465
1466         fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
1467                 let mut unsigned_channel_update = UnsignedChannelUpdate {
1468                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1469                         short_channel_id: 0,
1470                         timestamp: 100,
1471                         flags: 0,
1472                         cltv_expiry_delta: 144,
1473                         htlc_minimum_msat: 1_000_000,
1474                         htlc_maximum_msat: OptionalField::Absent,
1475                         fee_base_msat: 10_000,
1476                         fee_proportional_millionths: 20,
1477                         excess_data: Vec::new()
1478                 };
1479                 f(&mut unsigned_channel_update);
1480                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1481                 ChannelUpdate {
1482                         signature: secp_ctx.sign(&msghash, node_key),
1483                         contents: unsigned_channel_update
1484                 }
1485         }
1486
1487         #[test]
1488         fn handling_node_announcements() {
1489                 let network_graph = create_network_graph();
1490                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1491
1492                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1493                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1494                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1495
1496                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
1497                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1498                         Ok(_) => panic!(),
1499                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1500                 };
1501
1502                 {
1503                         // Announce a channel to add a corresponding node.
1504                         let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1505                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1506                                 Ok(res) => assert!(res),
1507                                 _ => panic!()
1508                         };
1509                 }
1510
1511                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1512                         Ok(res) => assert!(res),
1513                         Err(_) => panic!()
1514                 };
1515
1516                 let fake_msghash = hash_to_message!(&zero_hash);
1517                 match net_graph_msg_handler.handle_node_announcement(
1518                         &NodeAnnouncement {
1519                                 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1520                                 contents: valid_announcement.contents.clone()
1521                 }) {
1522                         Ok(_) => panic!(),
1523                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1524                 };
1525
1526                 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
1527                         unsigned_announcement.timestamp += 1000;
1528                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1529                 }, node_1_privkey, &secp_ctx);
1530                 // Return false because contains excess data.
1531                 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1532                         Ok(res) => assert!(!res),
1533                         Err(_) => panic!()
1534                 };
1535
1536                 // Even though previous announcement was not relayed further, we still accepted it,
1537                 // so we now won't accept announcements before the previous one.
1538                 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
1539                         unsigned_announcement.timestamp += 1000 - 10;
1540                 }, node_1_privkey, &secp_ctx);
1541                 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1542                         Ok(_) => panic!(),
1543                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
1544                 };
1545         }
1546
1547         #[test]
1548         fn handling_channel_announcements() {
1549                 let secp_ctx = Secp256k1::new();
1550                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1551
1552                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1553                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1554
1555                 let good_script = get_channel_script(&secp_ctx);
1556                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1557
1558                 // Test if the UTXO lookups were not supported
1559                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1560                 let mut net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, None, Arc::clone(&logger));
1561                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1562                         Ok(res) => assert!(res),
1563                         _ => panic!()
1564                 };
1565
1566                 {
1567                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1568                                 None => panic!(),
1569                                 Some(_) => ()
1570                         };
1571                 }
1572
1573                 // If we receive announcement for the same channel (with UTXO lookups disabled),
1574                 // drop new one on the floor, since we can't see any changes.
1575                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1576                         Ok(_) => panic!(),
1577                         Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1578                 };
1579
1580                 // Test if an associated transaction were not on-chain (or not confirmed).
1581                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1582                 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1583                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1584                 net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1585
1586                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1587                         unsigned_announcement.short_channel_id += 1;
1588                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1589                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1590                         Ok(_) => panic!(),
1591                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1592                 };
1593
1594                 // Now test if the transaction is found in the UTXO set and the script is correct.
1595                 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1596                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1597                         unsigned_announcement.short_channel_id += 2;
1598                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1599                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1600                         Ok(res) => assert!(res),
1601                         _ => panic!()
1602                 };
1603
1604                 {
1605                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1606                                 None => panic!(),
1607                                 Some(_) => ()
1608                         };
1609                 }
1610
1611                 // If we receive announcement for the same channel (but TX is not confirmed),
1612                 // drop new one on the floor, since we can't see any changes.
1613                 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1614                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1615                         Ok(_) => panic!(),
1616                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1617                 };
1618
1619                 // But if it is confirmed, replace the channel
1620                 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1621                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1622                         unsigned_announcement.features = ChannelFeatures::empty();
1623                         unsigned_announcement.short_channel_id += 2;
1624                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1625                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1626                         Ok(res) => assert!(res),
1627                         _ => panic!()
1628                 };
1629                 {
1630                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1631                                 Some(channel_entry) => {
1632                                         assert_eq!(channel_entry.features, ChannelFeatures::empty());
1633                                 },
1634                                 _ => panic!()
1635                         };
1636                 }
1637
1638                 // Don't relay valid channels with excess data
1639                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1640                         unsigned_announcement.short_channel_id += 3;
1641                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1642                 }, node_1_privkey, node_2_privkey, &secp_ctx);
1643                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1644                         Ok(res) => assert!(!res),
1645                         _ => panic!()
1646                 };
1647
1648                 let mut invalid_sig_announcement = valid_announcement.clone();
1649                 invalid_sig_announcement.contents.excess_data = Vec::new();
1650                 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1651                         Ok(_) => panic!(),
1652                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1653                 };
1654
1655                 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
1656                 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1657                         Ok(_) => panic!(),
1658                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1659                 };
1660         }
1661
1662         #[test]
1663         fn handling_channel_update() {
1664                 let secp_ctx = Secp256k1::new();
1665                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1666                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1667                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1668                 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1669
1670                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1671                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1672
1673                 let amount_sats = 1000_000;
1674                 let short_channel_id;
1675
1676                 {
1677                         // Announce a channel we will update
1678                         let good_script = get_channel_script(&secp_ctx);
1679                         *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1680
1681                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1682                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
1683                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1684                                 Ok(_) => (),
1685                                 Err(_) => panic!()
1686                         };
1687
1688                 }
1689
1690                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1691                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1692                         Ok(res) => assert!(res),
1693                         _ => panic!()
1694                 };
1695
1696                 {
1697                         match network_graph.read_only().channels().get(&short_channel_id) {
1698                                 None => panic!(),
1699                                 Some(channel_info) => {
1700                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1701                                         assert!(channel_info.two_to_one.is_none());
1702                                 }
1703                         };
1704                 }
1705
1706                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1707                         unsigned_channel_update.timestamp += 100;
1708                         unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1709                 }, node_1_privkey, &secp_ctx);
1710                 // Return false because contains excess data
1711                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1712                         Ok(res) => assert!(!res),
1713                         _ => panic!()
1714                 };
1715
1716                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1717                         unsigned_channel_update.timestamp += 110;
1718                         unsigned_channel_update.short_channel_id += 1;
1719                 }, node_1_privkey, &secp_ctx);
1720                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1721                         Ok(_) => panic!(),
1722                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1723                 };
1724
1725                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1726                         unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1727                         unsigned_channel_update.timestamp += 110;
1728                 }, node_1_privkey, &secp_ctx);
1729                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1730                         Ok(_) => panic!(),
1731                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1732                 };
1733
1734                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1735                         unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1736                         unsigned_channel_update.timestamp += 110;
1737                 }, node_1_privkey, &secp_ctx);
1738                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1739                         Ok(_) => panic!(),
1740                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1741                 };
1742
1743                 // Even though previous update was not relayed further, we still accepted it,
1744                 // so we now won't accept update before the previous one.
1745                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1746                         unsigned_channel_update.timestamp += 100;
1747                 }, node_1_privkey, &secp_ctx);
1748                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1749                         Ok(_) => panic!(),
1750                         Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
1751                 };
1752
1753                 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1754                         unsigned_channel_update.timestamp += 500;
1755                 }, node_1_privkey, &secp_ctx);
1756                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1757                 let fake_msghash = hash_to_message!(&zero_hash);
1758                 invalid_sig_channel_update.signature = secp_ctx.sign(&fake_msghash, node_1_privkey);
1759                 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1760                         Ok(_) => panic!(),
1761                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1762                 };
1763         }
1764
1765         #[test]
1766         fn handling_network_update() {
1767                 let logger = test_utils::TestLogger::new();
1768                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1769                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1770                 let network_graph = NetworkGraph::new(genesis_hash);
1771                 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
1772                 let secp_ctx = Secp256k1::new();
1773
1774                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1775                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1776
1777                 {
1778                         // There is no nodes in the table at the beginning.
1779                         assert_eq!(network_graph.read_only().nodes().len(), 0);
1780                 }
1781
1782                 let short_channel_id;
1783                 {
1784                         // Announce a channel we will update
1785                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1786                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
1787                         let chain_source: Option<&test_utils::TestChainSource> = None;
1788                         assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
1789                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
1790
1791                         let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1792                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
1793
1794                         net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1795                                 payment_id: None,
1796                                 payment_hash: PaymentHash([0; 32]),
1797                                 rejected_by_dest: false,
1798                                 all_paths_failed: true,
1799                                 path: vec![],
1800                                 network_update: Some(NetworkUpdate::ChannelUpdateMessage {
1801                                         msg: valid_channel_update,
1802                                 }),
1803                                 short_channel_id: None,
1804                                 retry: None,
1805                                 error_code: None,
1806                                 error_data: None,
1807                         });
1808
1809                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
1810                 }
1811
1812                 // Non-permanent closing just disables a channel
1813                 {
1814                         match network_graph.read_only().channels().get(&short_channel_id) {
1815                                 None => panic!(),
1816                                 Some(channel_info) => {
1817                                         assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
1818                                 }
1819                         };
1820
1821                         net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1822                                 payment_id: None,
1823                                 payment_hash: PaymentHash([0; 32]),
1824                                 rejected_by_dest: false,
1825                                 all_paths_failed: true,
1826                                 path: vec![],
1827                                 network_update: Some(NetworkUpdate::ChannelClosed {
1828                                         short_channel_id,
1829                                         is_permanent: false,
1830                                 }),
1831                                 short_channel_id: None,
1832                                 retry: None,
1833                                 error_code: None,
1834                                 error_data: None,
1835                         });
1836
1837                         match network_graph.read_only().channels().get(&short_channel_id) {
1838                                 None => panic!(),
1839                                 Some(channel_info) => {
1840                                         assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1841                                 }
1842                         };
1843                 }
1844
1845                 // Permanent closing deletes a channel
1846                 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1847                         payment_id: None,
1848                         payment_hash: PaymentHash([0; 32]),
1849                         rejected_by_dest: false,
1850                         all_paths_failed: true,
1851                         path: vec![],
1852                         network_update: Some(NetworkUpdate::ChannelClosed {
1853                                 short_channel_id,
1854                                 is_permanent: true,
1855                         }),
1856                         short_channel_id: None,
1857                         retry: None,
1858                         error_code: None,
1859                         error_data: None,
1860                 });
1861
1862                 assert_eq!(network_graph.read_only().channels().len(), 0);
1863                 // Nodes are also deleted because there are no associated channels anymore
1864                 assert_eq!(network_graph.read_only().nodes().len(), 0);
1865                 // TODO: Test NetworkUpdate::NodeFailure, which is not implemented yet.
1866         }
1867
1868         #[test]
1869         fn test_channel_timeouts() {
1870                 // Test the removal of channels with `remove_stale_channels`.
1871                 let logger = test_utils::TestLogger::new();
1872                 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1873                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1874                 let network_graph = NetworkGraph::new(genesis_hash);
1875                 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
1876                 let secp_ctx = Secp256k1::new();
1877
1878                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1879                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1880
1881                 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1882                 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
1883                 let chain_source: Option<&test_utils::TestChainSource> = None;
1884                 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
1885                 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
1886
1887                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1888                 assert!(net_graph_msg_handler.handle_channel_update(&valid_channel_update).is_ok());
1889                 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
1890
1891                 network_graph.remove_stale_channels_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
1892                 assert_eq!(network_graph.read_only().channels().len(), 1);
1893                 assert_eq!(network_graph.read_only().nodes().len(), 2);
1894
1895                 network_graph.remove_stale_channels_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
1896                 #[cfg(feature = "std")]
1897                 {
1898                         // In std mode, a further check is performed before fully removing the channel -
1899                         // the channel_announcement must have been received at least two weeks ago. We
1900                         // fudge that here by indicating the time has jumped two weeks. Note that the
1901                         // directional channel information will have been removed already..
1902                         assert_eq!(network_graph.read_only().channels().len(), 1);
1903                         assert_eq!(network_graph.read_only().nodes().len(), 2);
1904                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
1905
1906                         use std::time::{SystemTime, UNIX_EPOCH};
1907                         let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1908                         network_graph.remove_stale_channels_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
1909                 }
1910
1911                 assert_eq!(network_graph.read_only().channels().len(), 0);
1912                 assert_eq!(network_graph.read_only().nodes().len(), 0);
1913         }
1914
1915         #[test]
1916         fn getting_next_channel_announcements() {
1917                 let network_graph = create_network_graph();
1918                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1919                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1920                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1921
1922                 // Channels were not announced yet.
1923                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1924                 assert_eq!(channels_with_announcements.len(), 0);
1925
1926                 let short_channel_id;
1927                 {
1928                         // Announce a channel we will update
1929                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1930                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
1931                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1932                                 Ok(_) => (),
1933                                 Err(_) => panic!()
1934                         };
1935                 }
1936
1937                 // Contains initial channel announcement now.
1938                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1939                 assert_eq!(channels_with_announcements.len(), 1);
1940                 if let Some(channel_announcements) = channels_with_announcements.first() {
1941                         let &(_, ref update_1, ref update_2) = channel_announcements;
1942                         assert_eq!(update_1, &None);
1943                         assert_eq!(update_2, &None);
1944                 } else {
1945                         panic!();
1946                 }
1947
1948
1949                 {
1950                         // Valid channel update
1951                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1952                                 unsigned_channel_update.timestamp = 101;
1953                         }, node_1_privkey, &secp_ctx);
1954                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1955                                 Ok(_) => (),
1956                                 Err(_) => panic!()
1957                         };
1958                 }
1959
1960                 // Now contains an initial announcement and an update.
1961                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1962                 assert_eq!(channels_with_announcements.len(), 1);
1963                 if let Some(channel_announcements) = channels_with_announcements.first() {
1964                         let &(_, ref update_1, ref update_2) = channel_announcements;
1965                         assert_ne!(update_1, &None);
1966                         assert_eq!(update_2, &None);
1967                 } else {
1968                         panic!();
1969                 }
1970
1971                 {
1972                         // Channel update with excess data.
1973                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1974                                 unsigned_channel_update.timestamp = 102;
1975                                 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
1976                         }, node_1_privkey, &secp_ctx);
1977                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1978                                 Ok(_) => (),
1979                                 Err(_) => panic!()
1980                         };
1981                 }
1982
1983                 // Test that announcements with excess data won't be returned
1984                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1985                 assert_eq!(channels_with_announcements.len(), 1);
1986                 if let Some(channel_announcements) = channels_with_announcements.first() {
1987                         let &(_, ref update_1, ref update_2) = channel_announcements;
1988                         assert_eq!(update_1, &None);
1989                         assert_eq!(update_2, &None);
1990                 } else {
1991                         panic!();
1992                 }
1993
1994                 // Further starting point have no channels after it
1995                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1996                 assert_eq!(channels_with_announcements.len(), 0);
1997         }
1998
1999         #[test]
2000         fn getting_next_node_announcements() {
2001                 let network_graph = create_network_graph();
2002                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2003                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2004                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2005                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2006
2007                 // No nodes yet.
2008                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
2009                 assert_eq!(next_announcements.len(), 0);
2010
2011                 {
2012                         // Announce a channel to add 2 nodes
2013                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2014                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2015                                 Ok(_) => (),
2016                                 Err(_) => panic!()
2017                         };
2018                 }
2019
2020
2021                 // Nodes were never announced
2022                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2023                 assert_eq!(next_announcements.len(), 0);
2024
2025                 {
2026                         let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2027                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2028                                 Ok(_) => (),
2029                                 Err(_) => panic!()
2030                         };
2031
2032                         let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
2033                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2034                                 Ok(_) => (),
2035                                 Err(_) => panic!()
2036                         };
2037                 }
2038
2039                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2040                 assert_eq!(next_announcements.len(), 2);
2041
2042                 // Skip the first node.
2043                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2044                 assert_eq!(next_announcements.len(), 1);
2045
2046                 {
2047                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2048                         let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
2049                                 unsigned_announcement.timestamp += 10;
2050                                 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2051                         }, node_2_privkey, &secp_ctx);
2052                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2053                                 Ok(res) => assert!(!res),
2054                                 Err(_) => panic!()
2055                         };
2056                 }
2057
2058                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2059                 assert_eq!(next_announcements.len(), 0);
2060         }
2061
2062         #[test]
2063         fn network_graph_serialization() {
2064                 let network_graph = create_network_graph();
2065                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2066
2067                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2068                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2069
2070                 // Announce a channel to add a corresponding node.
2071                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2072                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2073                         Ok(res) => assert!(res),
2074                         _ => panic!()
2075                 };
2076
2077                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2078                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2079                         Ok(_) => (),
2080                         Err(_) => panic!()
2081                 };
2082
2083                 let mut w = test_utils::TestVecWriter(Vec::new());
2084                 assert!(!network_graph.read_only().nodes().is_empty());
2085                 assert!(!network_graph.read_only().channels().is_empty());
2086                 network_graph.write(&mut w).unwrap();
2087                 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == network_graph);
2088         }
2089
2090         #[test]
2091         fn calling_sync_routing_table() {
2092                 let network_graph = create_network_graph();
2093                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2094                 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2095                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2096
2097                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2098                 let first_blocknum = 0;
2099                 let number_of_blocks = 0xffff_ffff;
2100
2101                 // It should ignore if gossip_queries feature is not enabled
2102                 {
2103                         let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2104                         net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2105                         let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2106                         assert_eq!(events.len(), 0);
2107                 }
2108
2109                 // It should send a query_channel_message with the correct information
2110                 {
2111                         let init_msg = Init { features: InitFeatures::known() };
2112                         net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2113                         let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2114                         assert_eq!(events.len(), 1);
2115                         match &events[0] {
2116                                 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2117                                         assert_eq!(node_id, &node_id_1);
2118                                         assert_eq!(msg.chain_hash, chain_hash);
2119                                         assert_eq!(msg.first_blocknum, first_blocknum);
2120                                         assert_eq!(msg.number_of_blocks, number_of_blocks);
2121                                 },
2122                                 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2123                         };
2124                 }
2125
2126                 // It should not enqueue a query when should_request_full_sync return false.
2127                 // The initial implementation allows syncing with the first 5 peers after
2128                 // which should_request_full_sync will return false
2129                 {
2130                         let network_graph = create_network_graph();
2131                         let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2132                         let init_msg = Init { features: InitFeatures::known() };
2133                         for n in 1..7 {
2134                                 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2135                                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2136                                 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2137                                 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2138                                 if n <= 5 {
2139                                         assert_eq!(events.len(), 1);
2140                                 } else {
2141                                         assert_eq!(events.len(), 0);
2142                                 }
2143
2144                         }
2145                 }
2146         }
2147
2148         #[test]
2149         fn handling_reply_channel_range() {
2150                 let network_graph = create_network_graph();
2151                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2152                 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2153                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2154
2155                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2156
2157                 // Test receipt of a single reply that should enqueue an SCID query
2158                 // matching the SCIDs in the reply
2159                 {
2160                         let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2161                                 chain_hash,
2162                                 sync_complete: true,
2163                                 first_blocknum: 0,
2164                                 number_of_blocks: 2000,
2165                                 short_channel_ids: vec![
2166                                         0x0003e0_000000_0000, // 992x0x0
2167                                         0x0003e8_000000_0000, // 1000x0x0
2168                                         0x0003e9_000000_0000, // 1001x0x0
2169                                         0x0003f0_000000_0000, // 1008x0x0
2170                                         0x00044c_000000_0000, // 1100x0x0
2171                                         0x0006e0_000000_0000, // 1760x0x0
2172                                 ],
2173                         });
2174                         assert!(result.is_ok());
2175
2176                         // We expect to emit a query_short_channel_ids message with the received scids
2177                         let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2178                         assert_eq!(events.len(), 1);
2179                         match &events[0] {
2180                                 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2181                                         assert_eq!(node_id, &node_id_1);
2182                                         assert_eq!(msg.chain_hash, chain_hash);
2183                                         assert_eq!(msg.short_channel_ids, vec![
2184                                                 0x0003e0_000000_0000, // 992x0x0
2185                                                 0x0003e8_000000_0000, // 1000x0x0
2186                                                 0x0003e9_000000_0000, // 1001x0x0
2187                                                 0x0003f0_000000_0000, // 1008x0x0
2188                                                 0x00044c_000000_0000, // 1100x0x0
2189                                                 0x0006e0_000000_0000, // 1760x0x0
2190                                         ]);
2191                                 },
2192                                 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2193                         }
2194                 }
2195         }
2196
2197         #[test]
2198         fn handling_reply_short_channel_ids() {
2199                 let network_graph = create_network_graph();
2200                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2201                 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2202                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2203
2204                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2205
2206                 // Test receipt of a successful reply
2207                 {
2208                         let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2209                                 chain_hash,
2210                                 full_information: true,
2211                         });
2212                         assert!(result.is_ok());
2213                 }
2214
2215                 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2216                 // for the chain_hash requested in the query.
2217                 {
2218                         let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2219                                 chain_hash,
2220                                 full_information: false,
2221                         });
2222                         assert!(result.is_err());
2223                         assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2224                 }
2225         }
2226
2227         #[test]
2228         fn handling_query_channel_range() {
2229                 let network_graph = create_network_graph();
2230                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2231
2232                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2233                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2234                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2235                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2236
2237                 let mut scids: Vec<u64> = vec![
2238                         scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2239                         scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2240                 ];
2241
2242                 // used for testing multipart reply across blocks
2243                 for block in 100000..=108001 {
2244                         scids.push(scid_from_parts(block, 0, 0).unwrap());
2245                 }
2246
2247                 // used for testing resumption on same block
2248                 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2249
2250                 for scid in scids {
2251                         let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2252                                 unsigned_announcement.short_channel_id = scid;
2253                         }, node_1_privkey, node_2_privkey, &secp_ctx);
2254                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2255                                 Ok(_) => (),
2256                                 _ => panic!()
2257                         };
2258                 }
2259
2260                 // Error when number_of_blocks=0
2261                 do_handling_query_channel_range(
2262                         &net_graph_msg_handler,
2263                         &node_id_2,
2264                         QueryChannelRange {
2265                                 chain_hash: chain_hash.clone(),
2266                                 first_blocknum: 0,
2267                                 number_of_blocks: 0,
2268                         },
2269                         false,
2270                         vec![ReplyChannelRange {
2271                                 chain_hash: chain_hash.clone(),
2272                                 first_blocknum: 0,
2273                                 number_of_blocks: 0,
2274                                 sync_complete: true,
2275                                 short_channel_ids: vec![]
2276                         }]
2277                 );
2278
2279                 // Error when wrong chain
2280                 do_handling_query_channel_range(
2281                         &net_graph_msg_handler,
2282                         &node_id_2,
2283                         QueryChannelRange {
2284                                 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2285                                 first_blocknum: 0,
2286                                 number_of_blocks: 0xffff_ffff,
2287                         },
2288                         false,
2289                         vec![ReplyChannelRange {
2290                                 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2291                                 first_blocknum: 0,
2292                                 number_of_blocks: 0xffff_ffff,
2293                                 sync_complete: true,
2294                                 short_channel_ids: vec![],
2295                         }]
2296                 );
2297
2298                 // Error when first_blocknum > 0xffffff
2299                 do_handling_query_channel_range(
2300                         &net_graph_msg_handler,
2301                         &node_id_2,
2302                         QueryChannelRange {
2303                                 chain_hash: chain_hash.clone(),
2304                                 first_blocknum: 0x01000000,
2305                                 number_of_blocks: 0xffff_ffff,
2306                         },
2307                         false,
2308                         vec![ReplyChannelRange {
2309                                 chain_hash: chain_hash.clone(),
2310                                 first_blocknum: 0x01000000,
2311                                 number_of_blocks: 0xffff_ffff,
2312                                 sync_complete: true,
2313                                 short_channel_ids: vec![]
2314                         }]
2315                 );
2316
2317                 // Empty reply when max valid SCID block num
2318                 do_handling_query_channel_range(
2319                         &net_graph_msg_handler,
2320                         &node_id_2,
2321                         QueryChannelRange {
2322                                 chain_hash: chain_hash.clone(),
2323                                 first_blocknum: 0xffffff,
2324                                 number_of_blocks: 1,
2325                         },
2326                         true,
2327                         vec![
2328                                 ReplyChannelRange {
2329                                         chain_hash: chain_hash.clone(),
2330                                         first_blocknum: 0xffffff,
2331                                         number_of_blocks: 1,
2332                                         sync_complete: true,
2333                                         short_channel_ids: vec![]
2334                                 },
2335                         ]
2336                 );
2337
2338                 // No results in valid query range
2339                 do_handling_query_channel_range(
2340                         &net_graph_msg_handler,
2341                         &node_id_2,
2342                         QueryChannelRange {
2343                                 chain_hash: chain_hash.clone(),
2344                                 first_blocknum: 1000,
2345                                 number_of_blocks: 1000,
2346                         },
2347                         true,
2348                         vec![
2349                                 ReplyChannelRange {
2350                                         chain_hash: chain_hash.clone(),
2351                                         first_blocknum: 1000,
2352                                         number_of_blocks: 1000,
2353                                         sync_complete: true,
2354                                         short_channel_ids: vec![],
2355                                 }
2356                         ]
2357                 );
2358
2359                 // Overflow first_blocknum + number_of_blocks
2360                 do_handling_query_channel_range(
2361                         &net_graph_msg_handler,
2362                         &node_id_2,
2363                         QueryChannelRange {
2364                                 chain_hash: chain_hash.clone(),
2365                                 first_blocknum: 0xfe0000,
2366                                 number_of_blocks: 0xffffffff,
2367                         },
2368                         true,
2369                         vec![
2370                                 ReplyChannelRange {
2371                                         chain_hash: chain_hash.clone(),
2372                                         first_blocknum: 0xfe0000,
2373                                         number_of_blocks: 0xffffffff - 0xfe0000,
2374                                         sync_complete: true,
2375                                         short_channel_ids: vec![
2376                                                 0xfffffe_ffffff_ffff, // max
2377                                         ]
2378                                 }
2379                         ]
2380                 );
2381
2382                 // Single block exactly full
2383                 do_handling_query_channel_range(
2384                         &net_graph_msg_handler,
2385                         &node_id_2,
2386                         QueryChannelRange {
2387                                 chain_hash: chain_hash.clone(),
2388                                 first_blocknum: 100000,
2389                                 number_of_blocks: 8000,
2390                         },
2391                         true,
2392                         vec![
2393                                 ReplyChannelRange {
2394                                         chain_hash: chain_hash.clone(),
2395                                         first_blocknum: 100000,
2396                                         number_of_blocks: 8000,
2397                                         sync_complete: true,
2398                                         short_channel_ids: (100000..=107999)
2399                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2400                                                 .collect(),
2401                                 },
2402                         ]
2403                 );
2404
2405                 // Multiple split on new block
2406                 do_handling_query_channel_range(
2407                         &net_graph_msg_handler,
2408                         &node_id_2,
2409                         QueryChannelRange {
2410                                 chain_hash: chain_hash.clone(),
2411                                 first_blocknum: 100000,
2412                                 number_of_blocks: 8001,
2413                         },
2414                         true,
2415                         vec![
2416                                 ReplyChannelRange {
2417                                         chain_hash: chain_hash.clone(),
2418                                         first_blocknum: 100000,
2419                                         number_of_blocks: 7999,
2420                                         sync_complete: false,
2421                                         short_channel_ids: (100000..=107999)
2422                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2423                                                 .collect(),
2424                                 },
2425                                 ReplyChannelRange {
2426                                         chain_hash: chain_hash.clone(),
2427                                         first_blocknum: 107999,
2428                                         number_of_blocks: 2,
2429                                         sync_complete: true,
2430                                         short_channel_ids: vec![
2431                                                 scid_from_parts(108000, 0, 0).unwrap(),
2432                                         ],
2433                                 }
2434                         ]
2435                 );
2436
2437                 // Multiple split on same block
2438                 do_handling_query_channel_range(
2439                         &net_graph_msg_handler,
2440                         &node_id_2,
2441                         QueryChannelRange {
2442                                 chain_hash: chain_hash.clone(),
2443                                 first_blocknum: 100002,
2444                                 number_of_blocks: 8000,
2445                         },
2446                         true,
2447                         vec![
2448                                 ReplyChannelRange {
2449                                         chain_hash: chain_hash.clone(),
2450                                         first_blocknum: 100002,
2451                                         number_of_blocks: 7999,
2452                                         sync_complete: false,
2453                                         short_channel_ids: (100002..=108001)
2454                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2455                                                 .collect(),
2456                                 },
2457                                 ReplyChannelRange {
2458                                         chain_hash: chain_hash.clone(),
2459                                         first_blocknum: 108001,
2460                                         number_of_blocks: 1,
2461                                         sync_complete: true,
2462                                         short_channel_ids: vec![
2463                                                 scid_from_parts(108001, 1, 0).unwrap(),
2464                                         ],
2465                                 }
2466                         ]
2467                 );
2468         }
2469
2470         fn do_handling_query_channel_range(
2471                 net_graph_msg_handler: &NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2472                 test_node_id: &PublicKey,
2473                 msg: QueryChannelRange,
2474                 expected_ok: bool,
2475                 expected_replies: Vec<ReplyChannelRange>
2476         ) {
2477                 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2478                 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2479                 let query_end_blocknum = msg.end_blocknum();
2480                 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2481
2482                 if expected_ok {
2483                         assert!(result.is_ok());
2484                 } else {
2485                         assert!(result.is_err());
2486                 }
2487
2488                 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2489                 assert_eq!(events.len(), expected_replies.len());
2490
2491                 for i in 0..events.len() {
2492                         let expected_reply = &expected_replies[i];
2493                         match &events[i] {
2494                                 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2495                                         assert_eq!(node_id, test_node_id);
2496                                         assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2497                                         assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2498                                         assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2499                                         assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2500                                         assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2501
2502                                         // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2503                                         assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2504                                         assert!(msg.first_blocknum >= max_firstblocknum);
2505                                         max_firstblocknum = msg.first_blocknum;
2506                                         c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2507
2508                                         // Check that the last block count is >= the query's end_blocknum
2509                                         if i == events.len() - 1 {
2510                                                 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2511                                         }
2512                                 },
2513                                 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2514                         }
2515                 }
2516         }
2517
2518         #[test]
2519         fn handling_query_short_channel_ids() {
2520                 let network_graph = create_network_graph();
2521                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2522                 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2523                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2524
2525                 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2526
2527                 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2528                         chain_hash,
2529                         short_channel_ids: vec![0x0003e8_000000_0000],
2530                 });
2531                 assert!(result.is_err());
2532         }
2533 }
2534
2535 #[cfg(all(test, feature = "unstable"))]
2536 mod benches {
2537         use super::*;
2538
2539         use test::Bencher;
2540         use std::io::Read;
2541
2542         #[bench]
2543         fn read_network_graph(bench: &mut Bencher) {
2544                 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2545                 let mut v = Vec::new();
2546                 d.read_to_end(&mut v).unwrap();
2547                 bench.iter(|| {
2548                         let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2549                 });
2550         }
2551
2552         #[bench]
2553         fn write_network_graph(bench: &mut Bencher) {
2554                 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2555                 let net_graph = NetworkGraph::read(&mut d).unwrap();
2556                 bench.iter(|| {
2557                         let _ = net_graph.encode();
2558                 });
2559         }
2560 }