1 // This file is Copyright its original authors, visible in version control
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
10 //! The top-level network map tracking logic lives here.
12 use bitcoin::secp256k1::key::PublicKey;
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::secp256k1;
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;
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};
28 use util::ser::{Writeable, Readable, Writer};
29 use util::logger::Logger;
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;
37 use bitcoin::hashes::hex::ToHex;
39 /// Represents the network as nodes and channels between them
41 pub struct NetworkGraph {
42 channels: BTreeMap<u64, ChannelInfo>,
43 nodes: BTreeMap<PublicKey, NodeInfo>,
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>);
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,
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 {
73 secp_ctx: Secp256k1::verification_only(),
74 network_graph: RwLock::new(NetworkGraph {
75 channels: BTreeMap::new(),
76 nodes: BTreeMap::new(),
78 full_syncs_requested: AtomicUsize::new(0),
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 {
88 secp_ctx: Secp256k1::verification_only(),
89 network_graph: RwLock::new(network_graph),
90 full_syncs_requested: AtomicUsize::new(0),
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
100 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
101 LockedNetworkGraph(self.network_graph.read().unwrap())
105 impl<'a> LockedNetworkGraph<'a> {
106 /// Get a reference to the NetworkGraph which this read-lock contains.
107 pub fn graph(&self) -> &NetworkGraph {
113 macro_rules! secp_verify_sig {
114 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
115 match $secp_ctx.verify($msg, $sig, $pubkey) {
117 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
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))
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});
132 let utxo_value = match &self.chain_access {
134 // Tentatively accept, potentially exposing us to DoS attacks
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});
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
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});
155 Err(chain::AccessError::UnknownTx) => {
156 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
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 { "" });
166 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
168 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
169 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
171 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
172 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
174 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
175 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
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))
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();
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();
200 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
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.
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)..);
220 network_graph.get_nodes().range(..)
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());
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);
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).
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>,
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)?;
279 impl_writeable!(DirectionalChannelInfo, 0, {
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>,
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)?;
320 impl_writeable!(ChannelInfo, 0, {
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
336 /// Liquidity-based routing fee in millionths of a routed amount.
337 /// In other words, 10000 is 1%.
338 pub proportional_millionths: u32,
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)?;
347 proportional_millionths,
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)?;
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
370 /// Moniker assigned to the node.
371 /// May be invalid or malicious (eg control chars),
372 /// should not be exposed to the user.
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>
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 {
393 self.announcement_message.write(writer)?;
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),
414 let announcement_message = Readable::read(reader)?;
415 Ok(NodeAnnouncementInfo {
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>
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)?;
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() {
455 self.lowest_inbound_channel_fees.write(writer)?;
456 self.announcement_info.write(writer)?;
461 const MAX_ALLOC_SIZE: u64 = 64*1024;
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)?);
470 let lowest_inbound_channel_fees = Readable::read(reader)?;
471 let announcement_info = Readable::read(reader)?;
474 lowest_inbound_channel_fees,
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)?;
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)?;
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);
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);
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)?;
525 writeln!(f, "[Nodes]")?;
526 for (key, val) in self.nodes.iter() {
527 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
534 /// Returns all known valid channels' short ids along with announced channel info.
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.
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 }
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.
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)
557 /// Creates a new, empty, network graph.
558 pub fn new() -> NetworkGraph {
560 channels: BTreeMap::new(),
561 nodes: BTreeMap::new(),
565 /// For an already known node (from channel announcements), update its stored properties from a given node announcement.
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.
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);
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}),
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});
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 },
602 /// Store or update channel info from a channel announcement.
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.
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.
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.
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});
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);
631 let should_relay = msg.contents.excess_data.is_empty();
633 let chan_info = ChannelInfo {
634 features: msg.contents.features.clone(),
635 node_one: msg.contents.node_id_1.clone(),
637 node_two: msg.contents.node_id_2.clone(),
639 capacity_sats: utxo_value,
640 announcement_message: if should_relay { Some(msg.clone()) } else { None },
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
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
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
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;
660 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
663 BtreeEntry::Vacant(entry) => {
664 entry.insert(chan_info);
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);
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,
685 add_channel_to_node!(msg.contents.node_id_1);
686 add_channel_to_node!(msg.contents.node_id_2);
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) {
697 if let Some(chan) = self.channels.remove(&short_channel_id) {
698 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
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;
705 if let Some(two_to_one) = chan.two_to_one.as_mut() {
706 two_to_one.enabled = false;
712 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
714 // TODO: Wholly remove the node
716 // TODO: downgrade the node
720 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
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.
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> {
729 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
730 let chan_was_enabled;
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}),
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});
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});
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});
754 chan_was_enabled = existing_chan_info.enabled;
756 chan_was_enabled = false;
759 let last_update_message = if msg.contents.excess_data.is_empty() {
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 },
772 base_msat: msg.contents.fee_base_msat,
773 proportional_millionths: msg.contents.fee_proportional_millionths,
777 $target = Some(updated_channel_dir_info);
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);
787 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
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);
793 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
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);
806 node.lowest_inbound_channel_fees = Some(RoutingFees {
808 proportional_millionths
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;
814 for chan_id in node.channels.iter() {
815 let chan = self.channels.get(chan_id).unwrap();
817 if chan.node_one == dest_node_id {
818 chan_info_opt = chan.two_to_one.as_ref();
820 chan_info_opt = chan.one_to_two.as_ref();
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);
832 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
835 Ok(msg.contents.excess_data.is_empty())
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
845 if entry.get().channels.is_empty() {
846 entry.remove_entry();
849 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
854 remove_from_node!(chan.node_one);
855 remove_from_node!(chan.node_two);
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,
867 use util::test_utils;
868 use util::logger::Logger;
869 use util::ser::{Readable, Writeable};
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;
881 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
882 use bitcoin::secp256k1::{All, Secp256k1};
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)
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());
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));
907 fn handling_node_announcements() {
908 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
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;
919 let mut unsigned_announcement = UnsignedNodeAnnouncement {
920 features: NodeFeatures::known(),
921 timestamp: first_announcement_time,
925 addresses: Vec::new(),
926 excess_address_data: Vec::new(),
927 excess_data: Vec::new(),
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()
935 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
937 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
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(),
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(),
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(),
961 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
962 Ok(res) => assert!(res),
967 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
968 Ok(res) => assert!(res),
972 let fake_msghash = hash_to_message!(&zero_hash);
973 match net_graph_msg_handler.handle_node_announcement(
975 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
976 contents: unsigned_announcement.clone()
979 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
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()
989 // Return false because contains excess data.
990 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
991 Ok(res) => assert!(!res),
994 unsigned_announcement.excess_data = Vec::new();
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()
1004 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1006 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1011 fn handling_channel_announcements() {
1012 let secp_ctx = Secp256k1::new();
1013 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
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();
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();
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,
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(),
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(),
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),
1057 let network = net_graph_msg_handler.network_graph.read().unwrap();
1058 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
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) {
1068 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
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;
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(),
1086 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1088 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
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() });
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(),
1103 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1104 Ok(res) => assert!(res),
1109 let network = net_graph_msg_handler.network_graph.read().unwrap();
1110 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
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) {
1121 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
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(),
1135 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1136 Ok(res) => assert!(res),
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());
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(),
1160 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1161 Ok(res) => assert!(!res),
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(),
1173 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1175 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
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(),
1187 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1189 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
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));
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();
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;
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(),
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(),
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(),
1239 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1246 let mut unsigned_channel_update = UnsignedChannelUpdate {
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()
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()
1264 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1265 Ok(res) => assert!(res),
1270 let network = net_graph_msg_handler.network_graph.read().unwrap();
1271 match network.get_channels().get(&short_channel_id) {
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());
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()
1287 // Return false because contains excess data
1288 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1289 Ok(res) => assert!(!res),
1292 unsigned_channel_update.timestamp += 10;
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()
1301 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1303 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1305 unsigned_channel_update.short_channel_id = short_channel_id;
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()
1314 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1316 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1318 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
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()
1327 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1329 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1331 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
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()
1342 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1344 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1346 unsigned_channel_update.timestamp += 500;
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()
1354 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1356 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
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();
1371 let short_channel_id = 0;
1372 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
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);
1381 // Announce a channel we will update
1382 let unsigned_announcement = UnsignedChannelAnnouncement {
1383 features: ChannelFeatures::empty(),
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(),
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(),
1401 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1406 let unsigned_channel_update = UnsignedChannelUpdate {
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()
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()
1424 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1425 Ok(res) => assert!(res),
1430 // Non-permanent closing just disables a channel
1432 let network = net_graph_msg_handler.network_graph.read().unwrap();
1433 match network.get_channels().get(&short_channel_id) {
1435 Some(channel_info) => {
1436 assert!(channel_info.one_to_two.is_some());
1441 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1446 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1448 // Non-permanent closing just disables a channel
1450 let network = net_graph_msg_handler.network_graph.read().unwrap();
1451 match network.get_channels().get(&short_channel_id) {
1453 Some(channel_info) => {
1454 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1459 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1464 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1466 // Permanent closing deletes a channel
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);
1473 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
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();
1486 let short_channel_id = 1;
1487 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
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);
1494 // Announce a channel we will update
1495 let unsigned_announcement = UnsignedChannelAnnouncement {
1496 features: ChannelFeatures::empty(),
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(),
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(),
1514 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
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);
1533 // Valid channel update
1534 let unsigned_channel_update = UnsignedChannelUpdate {
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()
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()
1551 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
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);
1570 // Channel update with excess data.
1571 let unsigned_channel_update = UnsignedChannelUpdate {
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()
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()
1588 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
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);
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);
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();
1620 let short_channel_id = 1;
1621 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1624 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1625 assert_eq!(next_announcements.len(), 0);
1628 // Announce a channel to add 2 nodes
1629 let unsigned_announcement = UnsignedChannelAnnouncement {
1630 features: ChannelFeatures::empty(),
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(),
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(),
1648 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
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);
1660 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1661 features: NodeFeatures::known(),
1666 addresses: Vec::new(),
1667 excess_address_data: Vec::new(),
1668 excess_data: Vec::new(),
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()
1675 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
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()
1687 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1693 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1694 assert_eq!(next_announcements.len(), 2);
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);
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(),
1708 addresses: Vec::new(),
1709 excess_address_data: Vec::new(),
1710 excess_data: [1; 3].to_vec(),
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()
1717 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1718 Ok(res) => assert!(!res),
1723 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1724 assert_eq!(next_announcements.len(), 0);
1728 fn network_graph_serialization() {
1729 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
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();
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,
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(),
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(),
1758 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1759 Ok(res) => assert!(res),
1764 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1765 let unsigned_announcement = UnsignedNodeAnnouncement {
1766 features: NodeFeatures::known(),
1771 addresses: Vec::new(),
1772 excess_address_data: Vec::new(),
1773 excess_data: Vec::new(),
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()
1781 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
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);