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