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