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