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