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