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