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