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