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