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