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