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