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