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