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