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