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