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