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