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