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