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