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