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