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