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