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