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