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