Relicense as dual Apache-2.0 + MIT
[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::opcodes;
20
21 use chain::chaininterface::{ChainError, ChainWatchInterface};
22 use ln::features::{ChannelFeatures, NodeFeatures};
23 use ln::msgs::{DecodeError, ErrorAction, LightningError, RoutingMessageHandler, NetAddress, OptionalField, MAX_VALUE_MSAT};
24 use ln::msgs;
25 use util::ser::{Writeable, Readable, Writer};
26 use util::logger::Logger;
27
28 use std::{cmp, fmt};
29 use std::sync::RwLock;
30 use std::sync::atomic::{AtomicUsize, Ordering};
31 use std::collections::BTreeMap;
32 use std::collections::btree_map::Entry as BtreeEntry;
33 use std::ops::Deref;
34 use bitcoin::hashes::hex::ToHex;
35
36 /// Receives and validates network updates from peers,
37 /// stores authentic and relevant data as a network graph.
38 /// This network graph is then used for routing payments.
39 /// Provides interface to help with initial routing sync by
40 /// serving historical announcements.
41 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: ChainWatchInterface, L::Target: Logger {
42         secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
43         /// Representation of the payment channel network
44         pub network_graph: RwLock<NetworkGraph>,
45         chain_monitor: C,
46         full_syncs_requested: AtomicUsize,
47         logger: L,
48 }
49
50 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
51         /// Creates a new tracker of the actual state of the network of channels and nodes,
52         /// assuming a fresh network graph.
53         /// Chain monitor is used to make sure announced channels exist on-chain,
54         /// channel data is correct, and that the announcement is signed with
55         /// channel owners' keys.
56         pub fn new(chain_monitor: C, logger: L) -> Self {
57                 NetGraphMsgHandler {
58                         secp_ctx: Secp256k1::verification_only(),
59                         network_graph: RwLock::new(NetworkGraph {
60                                 channels: BTreeMap::new(),
61                                 nodes: BTreeMap::new(),
62                         }),
63                         full_syncs_requested: AtomicUsize::new(0),
64                         chain_monitor,
65                         logger,
66                 }
67         }
68
69         /// Creates a new tracker of the actual state of the network of channels and nodes,
70         /// assuming an existing Network Graph.
71         pub fn from_net_graph(chain_monitor: C, logger: L, network_graph: NetworkGraph) -> Self {
72                 NetGraphMsgHandler {
73                         secp_ctx: Secp256k1::verification_only(),
74                         network_graph: RwLock::new(network_graph),
75                         full_syncs_requested: AtomicUsize::new(0),
76                         chain_monitor,
77                         logger,
78                 }
79         }
80 }
81
82
83 macro_rules! secp_verify_sig {
84         ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
85                 match $secp_ctx.verify($msg, $sig, $pubkey) {
86                         Ok(_) => {},
87                         Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
88                 }
89         };
90 }
91
92 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
93         fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
94                 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
95         }
96
97         fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
98                 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
99                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
100                 }
101
102                 let utxo_value = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
103                         Ok((script_pubkey, value)) => {
104                                 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
105                                                                     .push_slice(&msg.contents.bitcoin_key_1.serialize())
106                                                                     .push_slice(&msg.contents.bitcoin_key_2.serialize())
107                                                                     .push_opcode(opcodes::all::OP_PUSHNUM_2)
108                                                                     .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
109                                 if script_pubkey != expected_script {
110                                         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});
111                                 }
112                                 //TODO: Check if value is worth storing, use it to inform routing, and compare it
113                                 //to the new HTLC max field in channel_update
114                                 Some(value)
115                         },
116                         Err(ChainError::NotSupported) => {
117                                 // Tentatively accept, potentially exposing us to DoS attacks
118                                 None
119                         },
120                         Err(ChainError::NotWatched) => {
121                                 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
122                         },
123                         Err(ChainError::UnknownTx) => {
124                                 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
125                         },
126                 };
127                 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, utxo_value, Some(&self.secp_ctx));
128                 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 { "" });
129                 result
130         }
131
132         fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
133                 match update {
134                         &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
135                                 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
136                         },
137                         &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
138                                 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
139                         },
140                         &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
141                                 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
142                         },
143                 }
144         }
145
146         fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
147                 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
148         }
149
150         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
151                 let network_graph = self.network_graph.read().unwrap();
152                 let mut result = Vec::with_capacity(batch_amount as usize);
153                 let mut iter = network_graph.get_channels().range(starting_point..);
154                 while result.len() < batch_amount as usize {
155                         if let Some((_, ref chan)) = iter.next() {
156                                 if chan.announcement_message.is_some() {
157                                         let chan_announcement = chan.announcement_message.clone().unwrap();
158                                         let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
159                                         let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
160                                         if let Some(one_to_two) = chan.one_to_two.as_ref() {
161                                                 one_to_two_announcement = one_to_two.last_update_message.clone();
162                                         }
163                                         if let Some(two_to_one) = chan.two_to_one.as_ref() {
164                                                 two_to_one_announcement = two_to_one.last_update_message.clone();
165                                         }
166                                         result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
167                                 } else {
168                                         // TODO: We may end up sending un-announced channel_updates if we are sending
169                                         // initial sync data while receiving announce/updates for this channel.
170                                 }
171                         } else {
172                                 return result;
173                         }
174                 }
175                 result
176         }
177
178         fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
179                 let network_graph = self.network_graph.read().unwrap();
180                 let mut result = Vec::with_capacity(batch_amount as usize);
181                 let mut iter = if let Some(pubkey) = starting_point {
182                                 let mut iter = network_graph.get_nodes().range((*pubkey)..);
183                                 iter.next();
184                                 iter
185                         } else {
186                                 network_graph.get_nodes().range(..)
187                         };
188                 while result.len() < batch_amount as usize {
189                         if let Some((_, ref node)) = iter.next() {
190                                 if let Some(node_info) = node.announcement_info.as_ref() {
191                                         if node_info.announcement_message.is_some() {
192                                                 result.push(node_info.announcement_message.clone().unwrap());
193                                         }
194                                 }
195                         } else {
196                                 return result;
197                         }
198                 }
199                 result
200         }
201
202         fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
203                 //TODO: Determine whether to request a full sync based on the network map.
204                 const FULL_SYNCS_TO_REQUEST: usize = 5;
205                 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
206                         self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
207                         true
208                 } else {
209                         false
210                 }
211         }
212 }
213
214 #[derive(PartialEq, Debug)]
215 /// Details about one direction of a channel. Received
216 /// within a channel update.
217 pub struct DirectionalChannelInfo {
218         /// When the last update to the channel direction was issued.
219         /// Value is opaque, as set in the announcement.
220         pub last_update: u32,
221         /// Whether the channel can be currently used for payments (in this one direction).
222         pub enabled: bool,
223         /// The difference in CLTV values that you must have when routing through this channel.
224         pub cltv_expiry_delta: u16,
225         /// The minimum value, which must be relayed to the next hop via the channel
226         pub htlc_minimum_msat: u64,
227         /// The maximum value which may be relayed to the next hop via the channel.
228         pub htlc_maximum_msat: Option<u64>,
229         /// Fees charged when the channel is used for routing
230         pub fees: RoutingFees,
231         /// Most recent update for the channel received from the network
232         /// Mostly redundant with the data we store in fields explicitly.
233         /// Everything else is useful only for sending out for initial routing sync.
234         /// Not stored if contains excess data to prevent DoS.
235         pub last_update_message: Option<msgs::ChannelUpdate>,
236 }
237
238 impl fmt::Display for DirectionalChannelInfo {
239         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
240                 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)?;
241                 Ok(())
242         }
243 }
244
245 impl_writeable!(DirectionalChannelInfo, 0, {
246         last_update,
247         enabled,
248         cltv_expiry_delta,
249         htlc_minimum_msat,
250         htlc_maximum_msat,
251         fees,
252         last_update_message
253 });
254
255 #[derive(PartialEq)]
256 /// Details about a channel (both directions).
257 /// Received within a channel announcement.
258 pub struct ChannelInfo {
259         /// Protocol features of a channel communicated during its announcement
260         pub features: ChannelFeatures,
261         /// Source node of the first direction of a channel
262         pub node_one: PublicKey,
263         /// Details about the first direction of a channel
264         pub one_to_two: Option<DirectionalChannelInfo>,
265         /// Source node of the second direction of a channel
266         pub node_two: PublicKey,
267         /// Details about the second direction of a channel
268         pub two_to_one: Option<DirectionalChannelInfo>,
269         /// The channel capacity as seen on-chain, if chain lookup is available.
270         pub capacity_sats: Option<u64>,
271         /// An initial announcement of the channel
272         /// Mostly redundant with the data we store in fields explicitly.
273         /// Everything else is useful only for sending out for initial routing sync.
274         /// Not stored if contains excess data to prevent DoS.
275         pub announcement_message: Option<msgs::ChannelAnnouncement>,
276 }
277
278 impl fmt::Display for ChannelInfo {
279         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
280                 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
281                    log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
282                 Ok(())
283         }
284 }
285
286 impl_writeable!(ChannelInfo, 0, {
287         features,
288         node_one,
289         one_to_two,
290         node_two,
291         two_to_one,
292         capacity_sats,
293         announcement_message
294 });
295
296
297 /// Fees for routing via a given channel or a node
298 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
299 pub struct RoutingFees {
300         /// Flat routing fee in satoshis
301         pub base_msat: u32,
302         /// Liquidity-based routing fee in millionths of a routed amount.
303         /// In other words, 10000 is 1%.
304         pub proportional_millionths: u32,
305 }
306
307 impl Readable for RoutingFees{
308         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
309                 let base_msat: u32 = Readable::read(reader)?;
310                 let proportional_millionths: u32 = Readable::read(reader)?;
311                 Ok(RoutingFees {
312                         base_msat,
313                         proportional_millionths,
314                 })
315         }
316 }
317
318 impl Writeable for RoutingFees {
319         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
320                 self.base_msat.write(writer)?;
321                 self.proportional_millionths.write(writer)?;
322                 Ok(())
323         }
324 }
325
326 #[derive(PartialEq, Debug)]
327 /// Information received in the latest node_announcement from this node.
328 pub struct NodeAnnouncementInfo {
329         /// Protocol features the node announced support for
330         pub features: NodeFeatures,
331         /// When the last known update to the node state was issued.
332         /// Value is opaque, as set in the announcement.
333         pub last_update: u32,
334         /// Color assigned to the node
335         pub rgb: [u8; 3],
336         /// Moniker assigned to the node.
337         /// May be invalid or malicious (eg control chars),
338         /// should not be exposed to the user.
339         pub alias: [u8; 32],
340         /// Internet-level addresses via which one can connect to the node
341         pub addresses: Vec<NetAddress>,
342         /// An initial announcement of the node
343         /// Mostly redundant with the data we store in fields explicitly.
344         /// Everything else is useful only for sending out for initial routing sync.
345         /// Not stored if contains excess data to prevent DoS.
346         pub announcement_message: Option<msgs::NodeAnnouncement>
347 }
348
349 impl Writeable for NodeAnnouncementInfo {
350         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
351                 self.features.write(writer)?;
352                 self.last_update.write(writer)?;
353                 self.rgb.write(writer)?;
354                 self.alias.write(writer)?;
355                 (self.addresses.len() as u64).write(writer)?;
356                 for ref addr in &self.addresses {
357                         addr.write(writer)?;
358                 }
359                 self.announcement_message.write(writer)?;
360                 Ok(())
361         }
362 }
363
364 impl Readable for NodeAnnouncementInfo {
365         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
366                 let features = Readable::read(reader)?;
367                 let last_update = Readable::read(reader)?;
368                 let rgb = Readable::read(reader)?;
369                 let alias = Readable::read(reader)?;
370                 let addresses_count: u64 = Readable::read(reader)?;
371                 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
372                 for _ in 0..addresses_count {
373                         match Readable::read(reader) {
374                                 Ok(Ok(addr)) => { addresses.push(addr); },
375                                 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
376                                 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
377                                 _ => unreachable!(),
378                         }
379                 }
380                 let announcement_message = Readable::read(reader)?;
381                 Ok(NodeAnnouncementInfo {
382                         features,
383                         last_update,
384                         rgb,
385                         alias,
386                         addresses,
387                         announcement_message
388                 })
389         }
390 }
391
392 #[derive(PartialEq)]
393 /// Details about a node in the network, known from the network announcement.
394 pub struct NodeInfo {
395         /// All valid channels a node has announced
396         pub channels: Vec<u64>,
397         /// Lowest fees enabling routing via any of the enabled, known channels to a node.
398         /// The two fields (flat and proportional fee) are independent,
399         /// meaning they don't have to refer to the same channel.
400         pub lowest_inbound_channel_fees: Option<RoutingFees>,
401         /// More information about a node from node_announcement.
402         /// Optional because we store a Node entry after learning about it from
403         /// a channel announcement, but before receiving a node announcement.
404         pub announcement_info: Option<NodeAnnouncementInfo>
405 }
406
407 impl fmt::Display for NodeInfo {
408         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
409                 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
410                    self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
411                 Ok(())
412         }
413 }
414
415 impl Writeable for NodeInfo {
416         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
417                 (self.channels.len() as u64).write(writer)?;
418                 for ref chan in self.channels.iter() {
419                         chan.write(writer)?;
420                 }
421                 self.lowest_inbound_channel_fees.write(writer)?;
422                 self.announcement_info.write(writer)?;
423                 Ok(())
424         }
425 }
426
427 const MAX_ALLOC_SIZE: u64 = 64*1024;
428
429 impl Readable for NodeInfo {
430         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
431                 let channels_count: u64 = Readable::read(reader)?;
432                 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
433                 for _ in 0..channels_count {
434                         channels.push(Readable::read(reader)?);
435                 }
436                 let lowest_inbound_channel_fees = Readable::read(reader)?;
437                 let announcement_info = Readable::read(reader)?;
438                 Ok(NodeInfo {
439                         channels,
440                         lowest_inbound_channel_fees,
441                         announcement_info,
442                 })
443         }
444 }
445
446 /// Represents the network as nodes and channels between them
447 #[derive(PartialEq)]
448 pub struct NetworkGraph {
449         channels: BTreeMap<u64, ChannelInfo>,
450         nodes: BTreeMap<PublicKey, NodeInfo>,
451 }
452
453 impl Writeable for NetworkGraph {
454         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
455                 (self.channels.len() as u64).write(writer)?;
456                 for (ref chan_id, ref chan_info) in self.channels.iter() {
457                         (*chan_id).write(writer)?;
458                         chan_info.write(writer)?;
459                 }
460                 (self.nodes.len() as u64).write(writer)?;
461                 for (ref node_id, ref node_info) in self.nodes.iter() {
462                         node_id.write(writer)?;
463                         node_info.write(writer)?;
464                 }
465                 Ok(())
466         }
467 }
468
469 impl Readable for NetworkGraph {
470         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
471                 let channels_count: u64 = Readable::read(reader)?;
472                 let mut channels = BTreeMap::new();
473                 for _ in 0..channels_count {
474                         let chan_id: u64 = Readable::read(reader)?;
475                         let chan_info = Readable::read(reader)?;
476                         channels.insert(chan_id, chan_info);
477                 }
478                 let nodes_count: u64 = Readable::read(reader)?;
479                 let mut nodes = BTreeMap::new();
480                 for _ in 0..nodes_count {
481                         let node_id = Readable::read(reader)?;
482                         let node_info = Readable::read(reader)?;
483                         nodes.insert(node_id, node_info);
484                 }
485                 Ok(NetworkGraph {
486                         channels,
487                         nodes,
488                 })
489         }
490 }
491
492 impl fmt::Display for NetworkGraph {
493         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
494                 write!(f, "Network map\n[Channels]\n")?;
495                 for (key, val) in self.channels.iter() {
496                         write!(f, " {}: {}\n", key, val)?;
497                 }
498                 write!(f, "[Nodes]\n")?;
499                 for (key, val) in self.nodes.iter() {
500                         write!(f, " {}: {}\n", log_pubkey!(key), val)?;
501                 }
502                 Ok(())
503         }
504 }
505
506 impl NetworkGraph {
507         /// Returns all known valid channels' short ids along with announced channel info.
508         pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
509         /// Returns all known nodes' public keys along with announced node info.
510         pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
511
512         /// Get network addresses by node id.
513         /// Returns None if the requested node is completely unknown,
514         /// or if node announcement for the node was never received.
515         pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
516                 if let Some(node) = self.nodes.get(pubkey) {
517                         if let Some(node_info) = node.announcement_info.as_ref() {
518                                 return Some(&node_info.addresses)
519                         }
520                 }
521                 None
522         }
523
524         /// Creates a new, empty, network graph.
525         pub fn new() -> NetworkGraph {
526                 Self {
527                         channels: BTreeMap::new(),
528                         nodes: BTreeMap::new(),
529                 }
530         }
531
532         /// For an already known node (from channel announcements), update its stored properties from a given node announcement
533         /// Announcement signatures are checked here only if Secp256k1 object is provided.
534         fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
535                 if let Some(sig_verifier) = secp_ctx {
536                         let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
537                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
538                 }
539
540                 match self.nodes.get_mut(&msg.contents.node_id) {
541                         None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
542                         Some(node) => {
543                                 if let Some(node_info) = node.announcement_info.as_ref() {
544                                         if node_info.last_update  >= msg.contents.timestamp {
545                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
546                                         }
547                                 }
548
549                                 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
550                                 node.announcement_info = Some(NodeAnnouncementInfo {
551                                         features: msg.contents.features.clone(),
552                                         last_update: msg.contents.timestamp,
553                                         rgb: msg.contents.rgb,
554                                         alias: msg.contents.alias,
555                                         addresses: msg.contents.addresses.clone(),
556                                         announcement_message: if should_relay { Some(msg.clone()) } else { None },
557                                 });
558
559                                 Ok(should_relay)
560                         }
561                 }
562         }
563
564         /// For a new or already known (from previous announcement) channel, store or update channel info.
565         /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
566         /// Checking utxo on-chain is useful if we receive an update for already known channel id,
567         /// which is probably result of a reorg. In that case, we update channel info only if the
568         /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
569         /// Announcement signatures are checked here only if Secp256k1 object is provided.
570         fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
571                 if let Some(sig_verifier) = secp_ctx {
572                         let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
573                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
574                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
575                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
576                         secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
577                 }
578
579                 let should_relay = msg.contents.excess_data.is_empty();
580
581                 let chan_info = ChannelInfo {
582                                 features: msg.contents.features.clone(),
583                                 node_one: msg.contents.node_id_1.clone(),
584                                 one_to_two: None,
585                                 node_two: msg.contents.node_id_2.clone(),
586                                 two_to_one: None,
587                                 capacity_sats: utxo_value,
588                                 announcement_message: if should_relay { Some(msg.clone()) } else { None },
589                         };
590
591                 match self.channels.entry(msg.contents.short_channel_id) {
592                         BtreeEntry::Occupied(mut entry) => {
593                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
594                                 //in the blockchain API, we need to handle it smartly here, though it's unclear
595                                 //exactly how...
596                                 if utxo_value.is_some() {
597                                         // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
598                                         // only sometimes returns results. In any case remove the previous entry. Note
599                                         // that the spec expects us to "blacklist" the node_ids involved, but we can't
600                                         // do that because
601                                         // a) we don't *require* a UTXO provider that always returns results.
602                                         // b) we don't track UTXOs of channels we know about and remove them if they
603                                         //    get reorg'd out.
604                                         // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
605                                         Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
606                                         *entry.get_mut() = chan_info;
607                                 } else {
608                                         return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
609                                 }
610                         },
611                         BtreeEntry::Vacant(entry) => {
612                                 entry.insert(chan_info);
613                         }
614                 };
615
616                 macro_rules! add_channel_to_node {
617                         ( $node_id: expr ) => {
618                                 match self.nodes.entry($node_id) {
619                                         BtreeEntry::Occupied(node_entry) => {
620                                                 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
621                                         },
622                                         BtreeEntry::Vacant(node_entry) => {
623                                                 node_entry.insert(NodeInfo {
624                                                         channels: vec!(msg.contents.short_channel_id),
625                                                         lowest_inbound_channel_fees: None,
626                                                         announcement_info: None,
627                                                 });
628                                         }
629                                 }
630                         };
631                 }
632
633                 add_channel_to_node!(msg.contents.node_id_1);
634                 add_channel_to_node!(msg.contents.node_id_2);
635
636                 Ok(should_relay)
637         }
638
639         /// Close a channel if a corresponding HTLC fail was sent.
640         /// If permanent, removes a channel from the local storage.
641         /// May cause the removal of nodes too, if this was their last channel.
642         /// If not permanent, makes channels unavailable for routing.
643         pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
644                 if is_permanent {
645                         if let Some(chan) = self.channels.remove(&short_channel_id) {
646                                 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
647                         }
648                 } else {
649                         if let Some(chan) = self.channels.get_mut(&short_channel_id) {
650                                 if let Some(one_to_two) = chan.one_to_two.as_mut() {
651                                         one_to_two.enabled = false;
652                                 }
653                                 if let Some(two_to_one) = chan.two_to_one.as_mut() {
654                                         two_to_one.enabled = false;
655                                 }
656                         }
657                 }
658         }
659
660         fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
661                 if is_permanent {
662                         // TODO: Wholly remove the node
663                 } else {
664                         // TODO: downgrade the node
665                 }
666         }
667
668         /// For an already known (from announcement) channel, update info about one of the directions of a channel.
669         /// Announcement signatures are checked here only if Secp256k1 object is provided.
670         fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
671                 let dest_node_id;
672                 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
673                 let chan_was_enabled;
674
675                 match self.channels.get_mut(&msg.contents.short_channel_id) {
676                         None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
677                         Some(channel) => {
678                                 if let OptionalField::Present(htlc_maximum_msat) = msg.contents.htlc_maximum_msat {
679                                         if htlc_maximum_msat > MAX_VALUE_MSAT {
680                                                 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
681                                         }
682
683                                         if let Some(capacity_sats) = channel.capacity_sats {
684                                                 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
685                                                 // Don't query UTXO set here to reduce DoS risks.
686                                                 if htlc_maximum_msat > capacity_sats * 1000 {
687                                                         return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity".to_owned(), action: ErrorAction::IgnoreError});
688                                                 }
689                                         }
690                                 }
691                                 macro_rules! maybe_update_channel_info {
692                                         ( $target: expr, $src_node: expr) => {
693                                                 if let Some(existing_chan_info) = $target.as_ref() {
694                                                         if existing_chan_info.last_update >= msg.contents.timestamp {
695                                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
696                                                         }
697                                                         chan_was_enabled = existing_chan_info.enabled;
698                                                 } else {
699                                                         chan_was_enabled = false;
700                                                 }
701
702                                                 let last_update_message = if msg.contents.excess_data.is_empty() {
703                                                         Some(msg.clone())
704                                                 } else {
705                                                         None
706                                                 };
707
708                                                 let updated_channel_dir_info = DirectionalChannelInfo {
709                                                         enabled: chan_enabled,
710                                                         last_update: msg.contents.timestamp,
711                                                         cltv_expiry_delta: msg.contents.cltv_expiry_delta,
712                                                         htlc_minimum_msat: msg.contents.htlc_minimum_msat,
713                                                         htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
714                                                         fees: RoutingFees {
715                                                                 base_msat: msg.contents.fee_base_msat,
716                                                                 proportional_millionths: msg.contents.fee_proportional_millionths,
717                                                         },
718                                                         last_update_message
719                                                 };
720                                                 $target = Some(updated_channel_dir_info);
721                                         }
722                                 }
723
724                                 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
725                                 if msg.contents.flags & 1 == 1 {
726                                         dest_node_id = channel.node_one.clone();
727                                         if let Some(sig_verifier) = secp_ctx {
728                                                 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
729                                         }
730                                         maybe_update_channel_info!(channel.two_to_one, channel.node_two);
731                                 } else {
732                                         dest_node_id = channel.node_two.clone();
733                                         if let Some(sig_verifier) = secp_ctx {
734                                                 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
735                                         }
736                                         maybe_update_channel_info!(channel.one_to_two, channel.node_one);
737                                 }
738                         }
739                 }
740
741                 if chan_enabled {
742                         let node = self.nodes.get_mut(&dest_node_id).unwrap();
743                         let mut base_msat = msg.contents.fee_base_msat;
744                         let mut proportional_millionths = msg.contents.fee_proportional_millionths;
745                         if let Some(fees) = node.lowest_inbound_channel_fees {
746                                 base_msat = cmp::min(base_msat, fees.base_msat);
747                                 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
748                         }
749                         node.lowest_inbound_channel_fees = Some(RoutingFees {
750                                 base_msat,
751                                 proportional_millionths
752                         });
753                 } else if chan_was_enabled {
754                         let node = self.nodes.get_mut(&dest_node_id).unwrap();
755                         let mut lowest_inbound_channel_fees = None;
756
757                         for chan_id in node.channels.iter() {
758                                 let chan = self.channels.get(chan_id).unwrap();
759                                 let chan_info_opt;
760                                 if chan.node_one == dest_node_id {
761                                         chan_info_opt = chan.two_to_one.as_ref();
762                                 } else {
763                                         chan_info_opt = chan.one_to_two.as_ref();
764                                 }
765                                 if let Some(chan_info) = chan_info_opt {
766                                         if chan_info.enabled {
767                                                 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
768                                                         base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
769                                                 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
770                                                 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
771                                         }
772                                 }
773                         }
774
775                         node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
776                 }
777
778                 Ok(msg.contents.excess_data.is_empty())
779         }
780
781         fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
782                 macro_rules! remove_from_node {
783                         ($node_id: expr) => {
784                                 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
785                                         entry.get_mut().channels.retain(|chan_id| {
786                                                 short_channel_id != *chan_id
787                                         });
788                                         if entry.get().channels.is_empty() {
789                                                 entry.remove_entry();
790                                         }
791                                 } else {
792                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
793                                 }
794                         }
795                 }
796
797                 remove_from_node!(chan.node_one);
798                 remove_from_node!(chan.node_two);
799         }
800 }
801
802 #[cfg(test)]
803 mod tests {
804         use chain::chaininterface;
805         use ln::features::{ChannelFeatures, NodeFeatures};
806         use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
807         use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
808                 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
809                 MAX_VALUE_MSAT};
810         use util::test_utils;
811         use util::logger::Logger;
812         use util::ser::{Readable, Writeable};
813
814         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
815         use bitcoin::hashes::Hash;
816         use bitcoin::network::constants::Network;
817         use bitcoin::blockdata::constants::genesis_block;
818         use bitcoin::blockdata::script::Builder;
819         use bitcoin::blockdata::opcodes;
820         use bitcoin::util::hash::BitcoinHash;
821
822         use hex;
823
824         use bitcoin::secp256k1::key::{PublicKey, SecretKey};
825         use bitcoin::secp256k1::{All, Secp256k1};
826
827         use std::sync::Arc;
828
829         fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
830                 let secp_ctx = Secp256k1::new();
831                 let logger = Arc::new(test_utils::TestLogger::new());
832                 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
833                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
834                 (secp_ctx, net_graph_msg_handler)
835         }
836
837         #[test]
838         fn request_full_sync_finite_times() {
839                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
840                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
841
842                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
843                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
844                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
845                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
846                 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
847                 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
848         }
849
850         #[test]
851         fn handling_node_announcements() {
852                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
853
854                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
855                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
856                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
857                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
858                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
859                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
860                 let zero_hash = Sha256dHash::hash(&[0; 32]);
861                 let first_announcement_time = 500;
862
863                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
864                         features: NodeFeatures::known(),
865                         timestamp: first_announcement_time,
866                         node_id: node_id_1,
867                         rgb: [0; 3],
868                         alias: [0; 32],
869                         addresses: Vec::new(),
870                         excess_address_data: Vec::new(),
871                         excess_data: Vec::new(),
872                 };
873                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
874                 let valid_announcement = NodeAnnouncement {
875                         signature: secp_ctx.sign(&msghash, node_1_privkey),
876                         contents: unsigned_announcement.clone()
877                 };
878
879                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
880                         Ok(_) => panic!(),
881                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
882                 };
883
884                 {
885                         // Announce a channel to add a corresponding node.
886                         let unsigned_announcement = UnsignedChannelAnnouncement {
887                                 features: ChannelFeatures::known(),
888                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
889                                 short_channel_id: 0,
890                                 node_id_1,
891                                 node_id_2,
892                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
893                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
894                                 excess_data: Vec::new(),
895                         };
896
897                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
898                         let valid_announcement = ChannelAnnouncement {
899                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
900                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
901                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
902                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
903                                 contents: unsigned_announcement.clone(),
904                         };
905                         match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
906                                 Ok(res) => assert!(res),
907                                 _ => panic!()
908                         };
909                 }
910
911                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
912                         Ok(res) => assert!(res),
913                         Err(_) => panic!()
914                 };
915
916                 let fake_msghash = hash_to_message!(&zero_hash);
917                 match net_graph_msg_handler.handle_node_announcement(
918                         &NodeAnnouncement {
919                                 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
920                                 contents: unsigned_announcement.clone()
921                 }) {
922                         Ok(_) => panic!(),
923                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
924                 };
925
926                 unsigned_announcement.timestamp += 1000;
927                 unsigned_announcement.excess_data.push(1);
928                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
929                 let announcement_with_data = NodeAnnouncement {
930                         signature: secp_ctx.sign(&msghash, node_1_privkey),
931                         contents: unsigned_announcement.clone()
932                 };
933                 // Return false because contains excess data.
934                 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
935                         Ok(res) => assert!(!res),
936                         Err(_) => panic!()
937                 };
938                 unsigned_announcement.excess_data = Vec::new();
939
940                 // Even though previous announcement was not relayed further, we still accepted it,
941                 // so we now won't accept announcements before the previous one.
942                 unsigned_announcement.timestamp -= 10;
943                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
944                 let outdated_announcement = NodeAnnouncement {
945                         signature: secp_ctx.sign(&msghash, node_1_privkey),
946                         contents: unsigned_announcement.clone()
947                 };
948                 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
949                         Ok(_) => panic!(),
950                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
951                 };
952         }
953
954         #[test]
955         fn handling_channel_announcements() {
956                 let secp_ctx = Secp256k1::new();
957                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
958                 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
959                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
960
961
962                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
963                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
964                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
965                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
966                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
967                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
968
969                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
970                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
971                    .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
972                    .push_opcode(opcodes::all::OP_PUSHNUM_2)
973                    .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
974
975
976                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
977                         features: ChannelFeatures::known(),
978                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
979                         short_channel_id: 0,
980                         node_id_1,
981                         node_id_2,
982                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
983                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
984                         excess_data: Vec::new(),
985                 };
986
987                 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
988                 let valid_announcement = ChannelAnnouncement {
989                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
990                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
991                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
992                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
993                         contents: unsigned_announcement.clone(),
994                 };
995
996                 // Test if the UTXO lookups were not supported
997                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
998
999                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1000                         Ok(res) => assert!(res),
1001                         _ => panic!()
1002                 };
1003
1004                 {
1005                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1006                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1007                                 None => panic!(),
1008                                 Some(_) => ()
1009                         }
1010                 }
1011
1012
1013                 // If we receive announcement for the same channel (with UTXO lookups disabled),
1014                 // drop new one on the floor, since we can't see any changes.
1015                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1016                         Ok(_) => panic!(),
1017                         Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1018                 };
1019
1020
1021                 // Test if an associated transaction were not on-chain (or not confirmed).
1022                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1023                 unsigned_announcement.short_channel_id += 1;
1024
1025                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1026                 let valid_announcement = ChannelAnnouncement {
1027                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1028                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1029                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1030                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1031                         contents: unsigned_announcement.clone(),
1032                 };
1033
1034                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1035                         Ok(_) => panic!(),
1036                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1037                 };
1038
1039
1040                 // Now test if the transaction is found in the UTXO set and the script is correct.
1041                 unsigned_announcement.short_channel_id += 1;
1042                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1043
1044                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1045                 let valid_announcement = ChannelAnnouncement {
1046                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1047                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1048                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1049                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1050                         contents: unsigned_announcement.clone(),
1051                 };
1052                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1053                         Ok(res) => assert!(res),
1054                         _ => panic!()
1055                 };
1056
1057                 {
1058                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1059                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1060                                 None => panic!(),
1061                                 Some(_) => ()
1062                         }
1063                 }
1064
1065                 // If we receive announcement for the same channel (but TX is not confirmed),
1066                 // drop new one on the floor, since we can't see any changes.
1067                 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1068                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1069                         Ok(_) => panic!(),
1070                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1071                 };
1072
1073                 // But if it is confirmed, replace the channel
1074                 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1075                 unsigned_announcement.features = ChannelFeatures::empty();
1076                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1077                 let valid_announcement = ChannelAnnouncement {
1078                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1079                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1080                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1081                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1082                         contents: unsigned_announcement.clone(),
1083                 };
1084                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1085                         Ok(res) => assert!(res),
1086                         _ => panic!()
1087                 };
1088                 {
1089                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1090                         match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1091                                 Some(channel_entry) => {
1092                                         assert_eq!(channel_entry.features, ChannelFeatures::empty());
1093                                 },
1094                                 _ => panic!()
1095                         }
1096                 }
1097
1098                 // Don't relay valid channels with excess data
1099                 unsigned_announcement.short_channel_id += 1;
1100                 unsigned_announcement.excess_data.push(1);
1101                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1102                 let valid_announcement = ChannelAnnouncement {
1103                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1104                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1105                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1106                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1107                         contents: unsigned_announcement.clone(),
1108                 };
1109                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1110                         Ok(res) => assert!(!res),
1111                         _ => panic!()
1112                 };
1113
1114                 unsigned_announcement.excess_data = Vec::new();
1115                 let invalid_sig_announcement = ChannelAnnouncement {
1116                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1117                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1118                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1119                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1120                         contents: unsigned_announcement.clone(),
1121                 };
1122                 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1123                         Ok(_) => panic!(),
1124                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1125                 };
1126
1127                 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1128                 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1129                 let channel_to_itself_announcement = ChannelAnnouncement {
1130                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1131                         node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1132                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1133                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1134                         contents: unsigned_announcement.clone(),
1135                 };
1136                 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1137                         Ok(_) => panic!(),
1138                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1139                 };
1140         }
1141
1142         #[test]
1143         fn handling_channel_update() {
1144                 let secp_ctx = Secp256k1::new();
1145                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1146                 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
1147                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
1148
1149                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1150                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1151                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1152                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1153                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1154                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1155
1156                 let zero_hash = Sha256dHash::hash(&[0; 32]);
1157                 let short_channel_id = 0;
1158                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1159                 let amount_sats = 1000_000;
1160
1161                 {
1162                         // Announce a channel we will update
1163                         let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1164                            .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1165                            .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1166                            .push_opcode(opcodes::all::OP_PUSHNUM_2)
1167                            .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1168                         *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), amount_sats));
1169                         let unsigned_announcement = UnsignedChannelAnnouncement {
1170                                 features: ChannelFeatures::empty(),
1171                                 chain_hash,
1172                                 short_channel_id,
1173                                 node_id_1,
1174                                 node_id_2,
1175                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1176                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1177                                 excess_data: Vec::new(),
1178                         };
1179
1180                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1181                         let valid_channel_announcement = ChannelAnnouncement {
1182                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1183                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1184                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1185                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1186                                 contents: unsigned_announcement.clone(),
1187                         };
1188                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1189                                 Ok(_) => (),
1190                                 Err(_) => panic!()
1191                         };
1192
1193                 }
1194
1195                 let mut unsigned_channel_update = UnsignedChannelUpdate {
1196                         chain_hash,
1197                         short_channel_id,
1198                         timestamp: 100,
1199                         flags: 0,
1200                         cltv_expiry_delta: 144,
1201                         htlc_minimum_msat: 1000000,
1202                         htlc_maximum_msat: OptionalField::Absent,
1203                         fee_base_msat: 10000,
1204                         fee_proportional_millionths: 20,
1205                         excess_data: Vec::new()
1206                 };
1207                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1208                 let valid_channel_update = ChannelUpdate {
1209                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1210                         contents: unsigned_channel_update.clone()
1211                 };
1212
1213                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1214                         Ok(res) => assert!(res),
1215                         _ => panic!()
1216                 };
1217
1218                 {
1219                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1220                         match network.get_channels().get(&short_channel_id) {
1221                                 None => panic!(),
1222                                 Some(channel_info) => {
1223                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1224                                         assert!(channel_info.two_to_one.is_none());
1225                                 }
1226                         }
1227                 }
1228
1229                 unsigned_channel_update.timestamp += 100;
1230                 unsigned_channel_update.excess_data.push(1);
1231                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1232                 let valid_channel_update = ChannelUpdate {
1233                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1234                         contents: unsigned_channel_update.clone()
1235                 };
1236                 // Return false because contains excess data
1237                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1238                         Ok(res) => assert!(!res),
1239                         _ => panic!()
1240                 };
1241                 unsigned_channel_update.timestamp += 10;
1242
1243                 unsigned_channel_update.short_channel_id += 1;
1244                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1245                 let valid_channel_update = ChannelUpdate {
1246                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1247                         contents: unsigned_channel_update.clone()
1248                 };
1249
1250                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1251                         Ok(_) => panic!(),
1252                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1253                 };
1254                 unsigned_channel_update.short_channel_id = short_channel_id;
1255
1256                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1257                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1258                 let valid_channel_update = ChannelUpdate {
1259                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1260                         contents: unsigned_channel_update.clone()
1261                 };
1262
1263                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1264                         Ok(_) => panic!(),
1265                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1266                 };
1267                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1268
1269                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1270                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1271                 let valid_channel_update = ChannelUpdate {
1272                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1273                         contents: unsigned_channel_update.clone()
1274                 };
1275
1276                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1277                         Ok(_) => panic!(),
1278                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity")
1279                 };
1280                 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1281
1282                 // Even though previous update was not relayed further, we still accepted it,
1283                 // so we now won't accept update before the previous one.
1284                 unsigned_channel_update.timestamp -= 10;
1285                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1286                 let valid_channel_update = ChannelUpdate {
1287                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1288                         contents: unsigned_channel_update.clone()
1289                 };
1290
1291                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1292                         Ok(_) => panic!(),
1293                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
1294                 };
1295                 unsigned_channel_update.timestamp += 500;
1296
1297                 let fake_msghash = hash_to_message!(&zero_hash);
1298                 let invalid_sig_channel_update = ChannelUpdate {
1299                         signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1300                         contents: unsigned_channel_update.clone()
1301                 };
1302
1303                 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1304                         Ok(_) => panic!(),
1305                         Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1306                 };
1307
1308         }
1309
1310         #[test]
1311         fn handling_htlc_fail_channel_update() {
1312                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1313                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1314                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1315                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1316                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1317                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1318                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1319
1320                 let short_channel_id = 0;
1321                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1322
1323                 {
1324                         // There is no nodes in the table at the beginning.
1325                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1326                         assert_eq!(network.get_nodes().len(), 0);
1327                 }
1328
1329                 {
1330                         // Announce a channel we will update
1331                         let unsigned_announcement = UnsignedChannelAnnouncement {
1332                                 features: ChannelFeatures::empty(),
1333                                 chain_hash,
1334                                 short_channel_id,
1335                                 node_id_1,
1336                                 node_id_2,
1337                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1338                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1339                                 excess_data: Vec::new(),
1340                         };
1341
1342                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1343                         let valid_channel_announcement = ChannelAnnouncement {
1344                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1345                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1346                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1347                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1348                                 contents: unsigned_announcement.clone(),
1349                         };
1350                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1351                                 Ok(_) => (),
1352                                 Err(_) => panic!()
1353                         };
1354
1355                         let unsigned_channel_update = UnsignedChannelUpdate {
1356                                 chain_hash,
1357                                 short_channel_id,
1358                                 timestamp: 100,
1359                                 flags: 0,
1360                                 cltv_expiry_delta: 144,
1361                                 htlc_minimum_msat: 1000000,
1362                                 htlc_maximum_msat: OptionalField::Absent,
1363                                 fee_base_msat: 10000,
1364                                 fee_proportional_millionths: 20,
1365                                 excess_data: Vec::new()
1366                         };
1367                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1368                         let valid_channel_update = ChannelUpdate {
1369                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1370                                 contents: unsigned_channel_update.clone()
1371                         };
1372
1373                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1374                                 Ok(res) => assert!(res),
1375                                 _ => panic!()
1376                         };
1377                 }
1378
1379                 // Non-permanent closing just disables a channel
1380                 {
1381                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1382                         match network.get_channels().get(&short_channel_id) {
1383                                 None => panic!(),
1384                                 Some(channel_info) => {
1385                                         assert!(channel_info.one_to_two.is_some());
1386                                 }
1387                         }
1388                 }
1389
1390                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1391                         short_channel_id,
1392                         is_permanent: false
1393                 };
1394
1395                 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1396
1397                 // Non-permanent closing just disables a channel
1398                 {
1399                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1400                         match network.get_channels().get(&short_channel_id) {
1401                                 None => panic!(),
1402                                 Some(channel_info) => {
1403                                         assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1404                                 }
1405                         }
1406                 }
1407
1408                 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1409                         short_channel_id,
1410                         is_permanent: true
1411                 };
1412
1413                 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1414
1415                 // Permanent closing deletes a channel
1416                 {
1417                         let network = net_graph_msg_handler.network_graph.read().unwrap();
1418                         assert_eq!(network.get_channels().len(), 0);
1419                         // Nodes are also deleted because there are no associated channels anymore
1420                         assert_eq!(network.get_nodes().len(), 0);
1421                 }
1422                 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1423         }
1424
1425         #[test]
1426         fn getting_next_channel_announcements() {
1427                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1428                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1429                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1430                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1431                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1432                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1433                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1434
1435                 let short_channel_id = 1;
1436                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1437
1438                 // Channels were not announced yet.
1439                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1440                 assert_eq!(channels_with_announcements.len(), 0);
1441
1442                 {
1443                         // Announce a channel we will update
1444                         let unsigned_announcement = UnsignedChannelAnnouncement {
1445                                 features: ChannelFeatures::empty(),
1446                                 chain_hash,
1447                                 short_channel_id,
1448                                 node_id_1,
1449                                 node_id_2,
1450                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1451                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1452                                 excess_data: Vec::new(),
1453                         };
1454
1455                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1456                         let valid_channel_announcement = ChannelAnnouncement {
1457                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1458                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1459                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1460                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1461                                 contents: unsigned_announcement.clone(),
1462                         };
1463                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1464                                 Ok(_) => (),
1465                                 Err(_) => panic!()
1466                         };
1467                 }
1468
1469                 // Contains initial channel announcement now.
1470                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1471                 assert_eq!(channels_with_announcements.len(), 1);
1472                 if let Some(channel_announcements) = channels_with_announcements.first() {
1473                         let &(_, ref update_1, ref update_2) = channel_announcements;
1474                         assert_eq!(update_1, &None);
1475                         assert_eq!(update_2, &None);
1476                 } else {
1477                         panic!();
1478                 }
1479
1480
1481                 {
1482                         // Valid channel update
1483                         let unsigned_channel_update = UnsignedChannelUpdate {
1484                                 chain_hash,
1485                                 short_channel_id,
1486                                 timestamp: 101,
1487                                 flags: 0,
1488                                 cltv_expiry_delta: 144,
1489                                 htlc_minimum_msat: 1000000,
1490                                 htlc_maximum_msat: OptionalField::Absent,
1491                                 fee_base_msat: 10000,
1492                                 fee_proportional_millionths: 20,
1493                                 excess_data: Vec::new()
1494                         };
1495                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1496                         let valid_channel_update = ChannelUpdate {
1497                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1498                                 contents: unsigned_channel_update.clone()
1499                         };
1500                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1501                                 Ok(_) => (),
1502                                 Err(_) => panic!()
1503                         };
1504                 }
1505
1506                 // Now contains an initial announcement and an update.
1507                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1508                 assert_eq!(channels_with_announcements.len(), 1);
1509                 if let Some(channel_announcements) = channels_with_announcements.first() {
1510                         let &(_, ref update_1, ref update_2) = channel_announcements;
1511                         assert_ne!(update_1, &None);
1512                         assert_eq!(update_2, &None);
1513                 } else {
1514                         panic!();
1515                 }
1516
1517
1518                 {
1519                         // Channel update with excess data.
1520                         let unsigned_channel_update = UnsignedChannelUpdate {
1521                                 chain_hash,
1522                                 short_channel_id,
1523                                 timestamp: 102,
1524                                 flags: 0,
1525                                 cltv_expiry_delta: 144,
1526                                 htlc_minimum_msat: 1000000,
1527                                 htlc_maximum_msat: OptionalField::Absent,
1528                                 fee_base_msat: 10000,
1529                                 fee_proportional_millionths: 20,
1530                                 excess_data: [1; 3].to_vec()
1531                         };
1532                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1533                         let valid_channel_update = ChannelUpdate {
1534                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1535                                 contents: unsigned_channel_update.clone()
1536                         };
1537                         match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1538                                 Ok(_) => (),
1539                                 Err(_) => panic!()
1540                         };
1541                 }
1542
1543                 // Test that announcements with excess data won't be returned
1544                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1545                 assert_eq!(channels_with_announcements.len(), 1);
1546                 if let Some(channel_announcements) = channels_with_announcements.first() {
1547                         let &(_, ref update_1, ref update_2) = channel_announcements;
1548                         assert_eq!(update_1, &None);
1549                         assert_eq!(update_2, &None);
1550                 } else {
1551                         panic!();
1552                 }
1553
1554                 // Further starting point have no channels after it
1555                 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1556                 assert_eq!(channels_with_announcements.len(), 0);
1557         }
1558
1559         #[test]
1560         fn getting_next_node_announcements() {
1561                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1562                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1563                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1564                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1565                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1566                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1567                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1568
1569                 let short_channel_id = 1;
1570                 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1571
1572                 // No nodes yet.
1573                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1574                 assert_eq!(next_announcements.len(), 0);
1575
1576                 {
1577                         // Announce a channel to add 2 nodes
1578                         let unsigned_announcement = UnsignedChannelAnnouncement {
1579                                 features: ChannelFeatures::empty(),
1580                                 chain_hash,
1581                                 short_channel_id,
1582                                 node_id_1,
1583                                 node_id_2,
1584                                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1585                                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1586                                 excess_data: Vec::new(),
1587                         };
1588
1589                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1590                         let valid_channel_announcement = ChannelAnnouncement {
1591                                 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1592                                 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1593                                 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1594                                 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1595                                 contents: unsigned_announcement.clone(),
1596                         };
1597                         match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1598                                 Ok(_) => (),
1599                                 Err(_) => panic!()
1600                         };
1601                 }
1602
1603
1604                 // Nodes were never announced
1605                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1606                 assert_eq!(next_announcements.len(), 0);
1607
1608                 {
1609                         let mut unsigned_announcement = UnsignedNodeAnnouncement {
1610                                 features: NodeFeatures::known(),
1611                                 timestamp: 1000,
1612                                 node_id: node_id_1,
1613                                 rgb: [0; 3],
1614                                 alias: [0; 32],
1615                                 addresses: Vec::new(),
1616                                 excess_address_data: Vec::new(),
1617                                 excess_data: Vec::new(),
1618                         };
1619                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1620                         let valid_announcement = NodeAnnouncement {
1621                                 signature: secp_ctx.sign(&msghash, node_1_privkey),
1622                                 contents: unsigned_announcement.clone()
1623                         };
1624                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1625                                 Ok(_) => (),
1626                                 Err(_) => panic!()
1627                         };
1628
1629                         unsigned_announcement.node_id = node_id_2;
1630                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1631                         let valid_announcement = NodeAnnouncement {
1632                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
1633                                 contents: unsigned_announcement.clone()
1634                         };
1635
1636                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1637                                 Ok(_) => (),
1638                                 Err(_) => panic!()
1639                         };
1640                 }
1641
1642                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1643                 assert_eq!(next_announcements.len(), 2);
1644
1645                 // Skip the first node.
1646                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1647                 assert_eq!(next_announcements.len(), 1);
1648
1649                 {
1650                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1651                         let unsigned_announcement = UnsignedNodeAnnouncement {
1652                                 features: NodeFeatures::known(),
1653                                 timestamp: 1010,
1654                                 node_id: node_id_2,
1655                                 rgb: [0; 3],
1656                                 alias: [0; 32],
1657                                 addresses: Vec::new(),
1658                                 excess_address_data: Vec::new(),
1659                                 excess_data: [1; 3].to_vec(),
1660                         };
1661                         let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1662                         let valid_announcement = NodeAnnouncement {
1663                                 signature: secp_ctx.sign(&msghash, node_2_privkey),
1664                                 contents: unsigned_announcement.clone()
1665                         };
1666                         match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1667                                 Ok(res) => assert!(!res),
1668                                 Err(_) => panic!()
1669                         };
1670                 }
1671
1672                 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1673                 assert_eq!(next_announcements.len(), 0);
1674         }
1675
1676         #[test]
1677         fn network_graph_serialization() {
1678                 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1679
1680                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1681                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1682                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1683                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1684
1685                 // Announce a channel to add a corresponding node.
1686                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1687                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1688                 let unsigned_announcement = UnsignedChannelAnnouncement {
1689                         features: ChannelFeatures::known(),
1690                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1691                         short_channel_id: 0,
1692                         node_id_1,
1693                         node_id_2,
1694                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1695                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1696                         excess_data: Vec::new(),
1697                 };
1698
1699                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1700                 let valid_announcement = ChannelAnnouncement {
1701                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1702                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1703                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1704                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1705                         contents: unsigned_announcement.clone(),
1706                 };
1707                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1708                         Ok(res) => assert!(res),
1709                         _ => panic!()
1710                 };
1711
1712
1713                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1714                 let unsigned_announcement = UnsignedNodeAnnouncement {
1715                         features: NodeFeatures::known(),
1716                         timestamp: 100,
1717                         node_id,
1718                         rgb: [0; 3],
1719                         alias: [0; 32],
1720                         addresses: Vec::new(),
1721                         excess_address_data: Vec::new(),
1722                         excess_data: Vec::new(),
1723                 };
1724                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1725                 let valid_announcement = NodeAnnouncement {
1726                         signature: secp_ctx.sign(&msghash, node_1_privkey),
1727                         contents: unsigned_announcement.clone()
1728                 };
1729
1730                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1731                         Ok(_) => (),
1732                         Err(_) => panic!()
1733                 };
1734
1735                 let network = net_graph_msg_handler.network_graph.write().unwrap();
1736                 let mut w = test_utils::TestVecWriter(Vec::new());
1737                 assert!(!network.get_nodes().is_empty());
1738                 assert!(!network.get_channels().is_empty());
1739                 network.write(&mut w).unwrap();
1740                 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1741         }
1742 }