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