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