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