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