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