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, &self.secp_ctx)?;
125 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty())
128 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
129 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
130 log_trace!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
131 Ok(msg.contents.excess_data.is_empty())
134 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
136 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
137 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
139 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
140 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
142 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
143 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
148 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
149 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
150 Ok(msg.contents.excess_data.is_empty())
153 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
154 let network_graph = self.network_graph.read().unwrap();
155 let mut result = Vec::with_capacity(batch_amount as usize);
156 let mut iter = network_graph.get_channels().range(starting_point..);
157 while result.len() < batch_amount as usize {
158 if let Some((_, ref chan)) = iter.next() {
159 if chan.announcement_message.is_some() {
160 let chan_announcement = chan.announcement_message.clone().unwrap();
161 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
162 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
163 if let Some(one_to_two) = chan.one_to_two.as_ref() {
164 one_to_two_announcement = one_to_two.last_update_message.clone();
166 if let Some(two_to_one) = chan.two_to_one.as_ref() {
167 two_to_one_announcement = two_to_one.last_update_message.clone();
169 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
171 // TODO: We may end up sending un-announced channel_updates if we are sending
172 // initial sync data while receiving announce/updates for this channel.
181 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
182 let network_graph = self.network_graph.read().unwrap();
183 let mut result = Vec::with_capacity(batch_amount as usize);
184 let mut iter = if let Some(pubkey) = starting_point {
185 let mut iter = network_graph.get_nodes().range((*pubkey)..);
189 network_graph.get_nodes().range(..)
191 while result.len() < batch_amount as usize {
192 if let Some((_, ref node)) = iter.next() {
193 if let Some(node_info) = node.announcement_info.as_ref() {
194 if node_info.announcement_message.is_some() {
195 result.push(node_info.announcement_message.clone().unwrap());
205 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
206 //TODO: Determine whether to request a full sync based on the network map.
207 const FULL_SYNCS_TO_REQUEST: usize = 5;
208 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
209 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
217 #[derive(PartialEq, Debug)]
218 /// Details about one direction of a channel. Received
219 /// within a channel update.
220 pub struct DirectionalChannelInfo {
221 /// When the last update to the channel direction was issued.
222 /// Value is opaque, as set in the announcement.
223 pub last_update: u32,
224 /// Whether the channel can be currently used for payments (in this one direction).
226 /// The difference in CLTV values that you must have when routing through this channel.
227 pub cltv_expiry_delta: u16,
228 /// The minimum value, which must be relayed to the next hop via the channel
229 pub htlc_minimum_msat: u64,
230 /// The maximum value which may be relayed to the next hop via the channel.
231 pub htlc_maximum_msat: Option<u64>,
232 /// Fees charged when the channel is used for routing
233 pub fees: RoutingFees,
234 /// Most recent update for the channel received from the network
235 /// Mostly redundant with the data we store in fields explicitly.
236 /// Everything else is useful only for sending out for initial routing sync.
237 /// Not stored if contains excess data to prevent DoS.
238 pub last_update_message: Option<ChannelUpdate>,
241 impl fmt::Display for DirectionalChannelInfo {
242 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
243 write!(f, "last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fees {:?}", self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fees)?;
248 impl_writeable!(DirectionalChannelInfo, 0, {
259 /// Details about a channel (both directions).
260 /// Received within a channel announcement.
261 pub struct ChannelInfo {
262 /// Protocol features of a channel communicated during its announcement
263 pub features: ChannelFeatures,
264 /// Source node of the first direction of a channel
265 pub node_one: PublicKey,
266 /// Details about the first direction of a channel
267 pub one_to_two: Option<DirectionalChannelInfo>,
268 /// Source node of the second direction of a channel
269 pub node_two: PublicKey,
270 /// Details about the second direction of a channel
271 pub two_to_one: Option<DirectionalChannelInfo>,
272 /// The channel capacity as seen on-chain, if chain lookup is available.
273 pub capacity_sats: Option<u64>,
274 /// An initial announcement of the channel
275 /// Mostly redundant with the data we store in fields explicitly.
276 /// Everything else is useful only for sending out for initial routing sync.
277 /// Not stored if contains excess data to prevent DoS.
278 pub announcement_message: Option<ChannelAnnouncement>,
281 impl fmt::Display for ChannelInfo {
282 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
283 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
284 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
289 impl_writeable!(ChannelInfo, 0, {
300 /// Fees for routing via a given channel or a node
301 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
302 pub struct RoutingFees {
303 /// Flat routing fee in satoshis
305 /// Liquidity-based routing fee in millionths of a routed amount.
306 /// In other words, 10000 is 1%.
307 pub proportional_millionths: u32,
310 impl Readable for RoutingFees{
311 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
312 let base_msat: u32 = Readable::read(reader)?;
313 let proportional_millionths: u32 = Readable::read(reader)?;
316 proportional_millionths,
321 impl Writeable for RoutingFees {
322 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
323 self.base_msat.write(writer)?;
324 self.proportional_millionths.write(writer)?;
329 #[derive(PartialEq, Debug)]
330 /// Information received in the latest node_announcement from this node.
331 pub struct NodeAnnouncementInfo {
332 /// Protocol features the node announced support for
333 pub features: NodeFeatures,
334 /// When the last known update to the node state was issued.
335 /// Value is opaque, as set in the announcement.
336 pub last_update: u32,
337 /// Color assigned to the node
339 /// Moniker assigned to the node.
340 /// May be invalid or malicious (eg control chars),
341 /// should not be exposed to the user.
343 /// Internet-level addresses via which one can connect to the node
344 pub addresses: Vec<NetAddress>,
345 /// An initial announcement of the node
346 /// Mostly redundant with the data we store in fields explicitly.
347 /// Everything else is useful only for sending out for initial routing sync.
348 /// Not stored if contains excess data to prevent DoS.
349 pub announcement_message: Option<NodeAnnouncement>
352 impl Writeable for NodeAnnouncementInfo {
353 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
354 self.features.write(writer)?;
355 self.last_update.write(writer)?;
356 self.rgb.write(writer)?;
357 self.alias.write(writer)?;
358 (self.addresses.len() as u64).write(writer)?;
359 for ref addr in &self.addresses {
362 self.announcement_message.write(writer)?;
367 impl Readable for NodeAnnouncementInfo {
368 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
369 let features = Readable::read(reader)?;
370 let last_update = Readable::read(reader)?;
371 let rgb = Readable::read(reader)?;
372 let alias = Readable::read(reader)?;
373 let addresses_count: u64 = Readable::read(reader)?;
374 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
375 for _ in 0..addresses_count {
376 match Readable::read(reader) {
377 Ok(Ok(addr)) => { addresses.push(addr); },
378 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
379 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
383 let announcement_message = Readable::read(reader)?;
384 Ok(NodeAnnouncementInfo {
396 /// Details about a node in the network, known from the network announcement.
397 pub struct NodeInfo {
398 /// All valid channels a node has announced
399 pub channels: Vec<u64>,
400 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
401 /// The two fields (flat and proportional fee) are independent,
402 /// meaning they don't have to refer to the same channel.
403 pub lowest_inbound_channel_fees: Option<RoutingFees>,
404 /// More information about a node from node_announcement.
405 /// Optional because we store a Node entry after learning about it from
406 /// a channel announcement, but before receiving a node announcement.
407 pub announcement_info: Option<NodeAnnouncementInfo>
410 impl fmt::Display for NodeInfo {
411 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
412 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
413 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
418 impl Writeable for NodeInfo {
419 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
420 (self.channels.len() as u64).write(writer)?;
421 for ref chan in self.channels.iter() {
424 self.lowest_inbound_channel_fees.write(writer)?;
425 self.announcement_info.write(writer)?;
430 const MAX_ALLOC_SIZE: u64 = 64*1024;
432 impl Readable for NodeInfo {
433 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
434 let channels_count: u64 = Readable::read(reader)?;
435 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
436 for _ in 0..channels_count {
437 channels.push(Readable::read(reader)?);
439 let lowest_inbound_channel_fees = Readable::read(reader)?;
440 let announcement_info = Readable::read(reader)?;
443 lowest_inbound_channel_fees,
449 impl Writeable for NetworkGraph {
450 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
451 (self.channels.len() as u64).write(writer)?;
452 for (ref chan_id, ref chan_info) in self.channels.iter() {
453 (*chan_id).write(writer)?;
454 chan_info.write(writer)?;
456 (self.nodes.len() as u64).write(writer)?;
457 for (ref node_id, ref node_info) in self.nodes.iter() {
458 node_id.write(writer)?;
459 node_info.write(writer)?;
465 impl Readable for NetworkGraph {
466 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
467 let channels_count: u64 = Readable::read(reader)?;
468 let mut channels = BTreeMap::new();
469 for _ in 0..channels_count {
470 let chan_id: u64 = Readable::read(reader)?;
471 let chan_info = Readable::read(reader)?;
472 channels.insert(chan_id, chan_info);
474 let nodes_count: u64 = Readable::read(reader)?;
475 let mut nodes = BTreeMap::new();
476 for _ in 0..nodes_count {
477 let node_id = Readable::read(reader)?;
478 let node_info = Readable::read(reader)?;
479 nodes.insert(node_id, node_info);
488 impl fmt::Display for NetworkGraph {
489 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
490 writeln!(f, "Network map\n[Channels]")?;
491 for (key, val) in self.channels.iter() {
492 writeln!(f, " {}: {}", key, val)?;
494 writeln!(f, "[Nodes]")?;
495 for (key, val) in self.nodes.iter() {
496 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
503 /// Returns all known valid channels' short ids along with announced channel info.
505 /// (C-not exported) because we have no mapping for `BTreeMap`s
506 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
507 /// Returns all known nodes' public keys along with announced node info.
509 /// (C-not exported) because we have no mapping for `BTreeMap`s
510 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
512 /// Get network addresses by node id.
513 /// Returns None if the requested node is completely unknown,
514 /// or if node announcement for the node was never received.
516 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
517 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
518 if let Some(node) = self.nodes.get(pubkey) {
519 if let Some(node_info) = node.announcement_info.as_ref() {
520 return Some(&node_info.addresses)
526 /// Creates a new, empty, network graph.
527 pub fn new() -> NetworkGraph {
529 channels: BTreeMap::new(),
530 nodes: BTreeMap::new(),
534 /// For an already known node (from channel announcements), update its stored properties from a
535 /// given node announcement.
537 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
538 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
539 /// routing messages from a source using a protocol other than the lightning P2P protocol.
540 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
541 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
542 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
543 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
546 /// For an already known node (from channel announcements), update its stored properties from a
547 /// given node announcement without verifying the associated signatures. Because we aren't
548 /// given the associated signatures here we cannot relay the node announcement to any of our
550 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
551 self.update_node_from_announcement_intern(msg, None)
554 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
555 match self.nodes.get_mut(&msg.node_id) {
556 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
558 if let Some(node_info) = node.announcement_info.as_ref() {
559 if node_info.last_update >= msg.timestamp {
560 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
564 let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
565 node.announcement_info = Some(NodeAnnouncementInfo {
566 features: msg.features.clone(),
567 last_update: msg.timestamp,
570 addresses: msg.addresses.clone(),
571 announcement_message: if should_relay { full_msg.cloned() } else { None },
579 /// Store or update channel info from a channel announcement.
581 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
582 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
583 /// routing messages from a source using a protocol other than the lightning P2P protocol.
585 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
586 /// the corresponding UTXO exists on chain and is correctly-formatted.
587 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
588 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
589 -> Result<(), LightningError>
590 where C::Target: chain::Access {
591 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
592 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
593 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
594 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
595 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
596 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
599 /// Store or update channel info from a channel announcement without verifying the associated
600 /// signatures. Because we aren't given the associated signatures here we cannot relay the
601 /// channel announcement to any of our peers.
603 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
604 /// the corresponding UTXO exists on chain and is correctly-formatted.
605 pub fn update_channel_from_unsigned_announcement<C: Deref>
606 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
607 -> Result<(), LightningError>
608 where C::Target: chain::Access {
609 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
612 fn update_channel_from_unsigned_announcement_intern<C: Deref>
613 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
614 -> Result<(), LightningError>
615 where C::Target: chain::Access {
616 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
617 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
620 let utxo_value = match &chain_access {
622 // Tentatively accept, potentially exposing us to DoS attacks
625 &Some(ref chain_access) => {
626 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
627 Ok(TxOut { value, script_pubkey }) => {
628 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
629 .push_slice(&msg.bitcoin_key_1.serialize())
630 .push_slice(&msg.bitcoin_key_2.serialize())
631 .push_opcode(opcodes::all::OP_PUSHNUM_2)
632 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
633 if script_pubkey != expected_script {
634 return Err(LightningError{err: format!("Channel announcement key ({}) didn't match on-chain script ({})", script_pubkey.to_hex(), expected_script.to_hex()), action: ErrorAction::IgnoreError});
636 //TODO: Check if value is worth storing, use it to inform routing, and compare it
637 //to the new HTLC max field in channel_update
640 Err(chain::AccessError::UnknownChain) => {
641 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
643 Err(chain::AccessError::UnknownTx) => {
644 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
650 let chan_info = ChannelInfo {
651 features: msg.features.clone(),
652 node_one: msg.node_id_1.clone(),
654 node_two: msg.node_id_2.clone(),
656 capacity_sats: utxo_value,
657 announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
660 match self.channels.entry(msg.short_channel_id) {
661 BtreeEntry::Occupied(mut entry) => {
662 //TODO: because asking the blockchain if short_channel_id is valid is only optional
663 //in the blockchain API, we need to handle it smartly here, though it's unclear
665 if utxo_value.is_some() {
666 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
667 // only sometimes returns results. In any case remove the previous entry. Note
668 // that the spec expects us to "blacklist" the node_ids involved, but we can't
670 // a) we don't *require* a UTXO provider that always returns results.
671 // b) we don't track UTXOs of channels we know about and remove them if they
673 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
674 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
675 *entry.get_mut() = chan_info;
677 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
680 BtreeEntry::Vacant(entry) => {
681 entry.insert(chan_info);
685 macro_rules! add_channel_to_node {
686 ( $node_id: expr ) => {
687 match self.nodes.entry($node_id) {
688 BtreeEntry::Occupied(node_entry) => {
689 node_entry.into_mut().channels.push(msg.short_channel_id);
691 BtreeEntry::Vacant(node_entry) => {
692 node_entry.insert(NodeInfo {
693 channels: vec!(msg.short_channel_id),
694 lowest_inbound_channel_fees: None,
695 announcement_info: None,
702 add_channel_to_node!(msg.node_id_1);
703 add_channel_to_node!(msg.node_id_2);
708 /// Close a channel if a corresponding HTLC fail was sent.
709 /// If permanent, removes a channel from the local storage.
710 /// May cause the removal of nodes too, if this was their last channel.
711 /// If not permanent, makes channels unavailable for routing.
712 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
714 if let Some(chan) = self.channels.remove(&short_channel_id) {
715 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
718 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
719 if let Some(one_to_two) = chan.one_to_two.as_mut() {
720 one_to_two.enabled = false;
722 if let Some(two_to_one) = chan.two_to_one.as_mut() {
723 two_to_one.enabled = false;
729 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
731 // TODO: Wholly remove the node
733 // TODO: downgrade the node
737 /// For an already known (from announcement) channel, update info about one of the directions
740 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
741 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
742 /// routing messages from a source using a protocol other than the lightning P2P protocol.
743 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
744 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
747 /// For an already known (from announcement) channel, update info about one of the directions
748 /// of the channel without verifying the associated signatures. Because we aren't given the
749 /// associated signatures here we cannot relay the channel update to any of our peers.
750 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
751 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
754 fn update_channel_intern<T: secp256k1::Verification>(&mut self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate>, sig_info: Option<(&secp256k1::Signature, &Secp256k1<T>)>) -> Result<(), LightningError> {
756 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
757 let chan_was_enabled;
759 match self.channels.get_mut(&msg.short_channel_id) {
760 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
762 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
763 if htlc_maximum_msat > MAX_VALUE_MSAT {
764 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
767 if let Some(capacity_sats) = channel.capacity_sats {
768 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
769 // Don't query UTXO set here to reduce DoS risks.
770 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
771 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
775 macro_rules! maybe_update_channel_info {
776 ( $target: expr, $src_node: expr) => {
777 if let Some(existing_chan_info) = $target.as_ref() {
778 if existing_chan_info.last_update >= msg.timestamp {
779 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
781 chan_was_enabled = existing_chan_info.enabled;
783 chan_was_enabled = false;
786 let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
788 let updated_channel_dir_info = DirectionalChannelInfo {
789 enabled: chan_enabled,
790 last_update: msg.timestamp,
791 cltv_expiry_delta: msg.cltv_expiry_delta,
792 htlc_minimum_msat: msg.htlc_minimum_msat,
793 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
795 base_msat: msg.fee_base_msat,
796 proportional_millionths: msg.fee_proportional_millionths,
800 $target = Some(updated_channel_dir_info);
804 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
805 if msg.flags & 1 == 1 {
806 dest_node_id = channel.node_one.clone();
807 if let Some((sig, ctx)) = sig_info {
808 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
810 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
812 dest_node_id = channel.node_two.clone();
813 if let Some((sig, ctx)) = sig_info {
814 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
816 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
822 let node = self.nodes.get_mut(&dest_node_id).unwrap();
823 let mut base_msat = msg.fee_base_msat;
824 let mut proportional_millionths = msg.fee_proportional_millionths;
825 if let Some(fees) = node.lowest_inbound_channel_fees {
826 base_msat = cmp::min(base_msat, fees.base_msat);
827 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
829 node.lowest_inbound_channel_fees = Some(RoutingFees {
831 proportional_millionths
833 } else if chan_was_enabled {
834 let node = self.nodes.get_mut(&dest_node_id).unwrap();
835 let mut lowest_inbound_channel_fees = None;
837 for chan_id in node.channels.iter() {
838 let chan = self.channels.get(chan_id).unwrap();
840 if chan.node_one == dest_node_id {
841 chan_info_opt = chan.two_to_one.as_ref();
843 chan_info_opt = chan.one_to_two.as_ref();
845 if let Some(chan_info) = chan_info_opt {
846 if chan_info.enabled {
847 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
848 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
849 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
850 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
855 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
861 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
862 macro_rules! remove_from_node {
863 ($node_id: expr) => {
864 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
865 entry.get_mut().channels.retain(|chan_id| {
866 short_channel_id != *chan_id
868 if entry.get().channels.is_empty() {
869 entry.remove_entry();
872 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
877 remove_from_node!(chan.node_one);
878 remove_from_node!(chan.node_two);
885 use ln::features::{ChannelFeatures, NodeFeatures};
886 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
887 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
888 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
890 use util::test_utils;
891 use util::logger::Logger;
892 use util::ser::{Readable, Writeable};
894 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
895 use bitcoin::hashes::Hash;
896 use bitcoin::network::constants::Network;
897 use bitcoin::blockdata::constants::genesis_block;
898 use bitcoin::blockdata::script::Builder;
899 use bitcoin::blockdata::transaction::TxOut;
900 use bitcoin::blockdata::opcodes;
904 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
905 use bitcoin::secp256k1::{All, Secp256k1};
909 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
910 let secp_ctx = Secp256k1::new();
911 let logger = Arc::new(test_utils::TestLogger::new());
912 let net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
913 (secp_ctx, net_graph_msg_handler)
917 fn request_full_sync_finite_times() {
918 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
919 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
921 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
922 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
923 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
924 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
925 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
926 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
930 fn handling_node_announcements() {
931 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
933 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
934 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
935 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
936 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
937 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
938 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
939 let zero_hash = Sha256dHash::hash(&[0; 32]);
940 let first_announcement_time = 500;
942 let mut unsigned_announcement = UnsignedNodeAnnouncement {
943 features: NodeFeatures::known(),
944 timestamp: first_announcement_time,
948 addresses: Vec::new(),
949 excess_address_data: Vec::new(),
950 excess_data: Vec::new(),
952 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
953 let valid_announcement = NodeAnnouncement {
954 signature: secp_ctx.sign(&msghash, node_1_privkey),
955 contents: unsigned_announcement.clone()
958 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
960 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
964 // Announce a channel to add a corresponding node.
965 let unsigned_announcement = UnsignedChannelAnnouncement {
966 features: ChannelFeatures::known(),
967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
971 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
972 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
973 excess_data: Vec::new(),
976 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
977 let valid_announcement = ChannelAnnouncement {
978 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
979 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
980 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
981 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
982 contents: unsigned_announcement.clone(),
984 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
985 Ok(res) => assert!(res),
990 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
991 Ok(res) => assert!(res),
995 let fake_msghash = hash_to_message!(&zero_hash);
996 match net_graph_msg_handler.handle_node_announcement(
998 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
999 contents: unsigned_announcement.clone()
1002 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1005 unsigned_announcement.timestamp += 1000;
1006 unsigned_announcement.excess_data.push(1);
1007 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1008 let announcement_with_data = NodeAnnouncement {
1009 signature: secp_ctx.sign(&msghash, node_1_privkey),
1010 contents: unsigned_announcement.clone()
1012 // Return false because contains excess data.
1013 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1014 Ok(res) => assert!(!res),
1017 unsigned_announcement.excess_data = Vec::new();
1019 // Even though previous announcement was not relayed further, we still accepted it,
1020 // so we now won't accept announcements before the previous one.
1021 unsigned_announcement.timestamp -= 10;
1022 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1023 let outdated_announcement = NodeAnnouncement {
1024 signature: secp_ctx.sign(&msghash, node_1_privkey),
1025 contents: unsigned_announcement.clone()
1027 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1029 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1034 fn handling_channel_announcements() {
1035 let secp_ctx = Secp256k1::new();
1036 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1038 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1039 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1040 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1041 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1042 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1043 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1045 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1046 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1047 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1048 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1049 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1052 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1053 features: ChannelFeatures::known(),
1054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1055 short_channel_id: 0,
1058 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1059 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1060 excess_data: Vec::new(),
1063 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1064 let valid_announcement = ChannelAnnouncement {
1065 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1066 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1067 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1068 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1069 contents: unsigned_announcement.clone(),
1072 // Test if the UTXO lookups were not supported
1073 let mut net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
1074 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1075 Ok(res) => assert!(res),
1080 let network = net_graph_msg_handler.network_graph.read().unwrap();
1081 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1087 // If we receive announcement for the same channel (with UTXO lookups disabled),
1088 // drop new one on the floor, since we can't see any changes.
1089 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1091 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1094 // Test if an associated transaction were not on-chain (or not confirmed).
1095 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1096 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1097 net_graph_msg_handler = NetGraphMsgHandler::new(Some(chain_source.clone()), Arc::clone(&logger));
1098 unsigned_announcement.short_channel_id += 1;
1100 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1101 let valid_announcement = ChannelAnnouncement {
1102 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1103 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1104 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1105 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1106 contents: unsigned_announcement.clone(),
1109 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1111 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1114 // Now test if the transaction is found in the UTXO set and the script is correct.
1115 unsigned_announcement.short_channel_id += 1;
1116 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1118 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1119 let valid_announcement = ChannelAnnouncement {
1120 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1121 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1122 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1123 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1124 contents: unsigned_announcement.clone(),
1126 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1127 Ok(res) => assert!(res),
1132 let network = net_graph_msg_handler.network_graph.read().unwrap();
1133 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1139 // If we receive announcement for the same channel (but TX is not confirmed),
1140 // drop new one on the floor, since we can't see any changes.
1141 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1142 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1144 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1147 // But if it is confirmed, replace the channel
1148 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1149 unsigned_announcement.features = ChannelFeatures::empty();
1150 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1151 let valid_announcement = ChannelAnnouncement {
1152 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1153 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1154 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1155 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1156 contents: unsigned_announcement.clone(),
1158 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1159 Ok(res) => assert!(res),
1163 let network = net_graph_msg_handler.network_graph.read().unwrap();
1164 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1165 Some(channel_entry) => {
1166 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1172 // Don't relay valid channels with excess data
1173 unsigned_announcement.short_channel_id += 1;
1174 unsigned_announcement.excess_data.push(1);
1175 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1176 let valid_announcement = ChannelAnnouncement {
1177 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1178 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1179 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1180 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1181 contents: unsigned_announcement.clone(),
1183 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1184 Ok(res) => assert!(!res),
1188 unsigned_announcement.excess_data = Vec::new();
1189 let invalid_sig_announcement = ChannelAnnouncement {
1190 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1191 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1192 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1193 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1194 contents: unsigned_announcement.clone(),
1196 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1198 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1201 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1202 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1203 let channel_to_itself_announcement = ChannelAnnouncement {
1204 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1205 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1206 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1207 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1208 contents: unsigned_announcement.clone(),
1210 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1212 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1217 fn handling_channel_update() {
1218 let secp_ctx = Secp256k1::new();
1219 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1220 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1221 let net_graph_msg_handler = NetGraphMsgHandler::new(Some(chain_source.clone()), Arc::clone(&logger));
1223 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1224 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1225 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1226 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1227 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1228 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1230 let zero_hash = Sha256dHash::hash(&[0; 32]);
1231 let short_channel_id = 0;
1232 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1233 let amount_sats = 1000_000;
1236 // Announce a channel we will update
1237 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1238 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1239 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1240 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1241 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1242 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1243 let unsigned_announcement = UnsignedChannelAnnouncement {
1244 features: ChannelFeatures::empty(),
1249 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1250 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1251 excess_data: Vec::new(),
1254 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1255 let valid_channel_announcement = ChannelAnnouncement {
1256 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1257 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1258 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1259 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1260 contents: unsigned_announcement.clone(),
1262 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1269 let mut unsigned_channel_update = UnsignedChannelUpdate {
1274 cltv_expiry_delta: 144,
1275 htlc_minimum_msat: 1000000,
1276 htlc_maximum_msat: OptionalField::Absent,
1277 fee_base_msat: 10000,
1278 fee_proportional_millionths: 20,
1279 excess_data: Vec::new()
1281 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1282 let valid_channel_update = ChannelUpdate {
1283 signature: secp_ctx.sign(&msghash, node_1_privkey),
1284 contents: unsigned_channel_update.clone()
1287 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1288 Ok(res) => assert!(res),
1293 let network = net_graph_msg_handler.network_graph.read().unwrap();
1294 match network.get_channels().get(&short_channel_id) {
1296 Some(channel_info) => {
1297 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1298 assert!(channel_info.two_to_one.is_none());
1303 unsigned_channel_update.timestamp += 100;
1304 unsigned_channel_update.excess_data.push(1);
1305 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1306 let valid_channel_update = ChannelUpdate {
1307 signature: secp_ctx.sign(&msghash, node_1_privkey),
1308 contents: unsigned_channel_update.clone()
1310 // Return false because contains excess data
1311 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1312 Ok(res) => assert!(!res),
1315 unsigned_channel_update.timestamp += 10;
1317 unsigned_channel_update.short_channel_id += 1;
1318 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1319 let valid_channel_update = ChannelUpdate {
1320 signature: secp_ctx.sign(&msghash, node_1_privkey),
1321 contents: unsigned_channel_update.clone()
1324 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1326 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1328 unsigned_channel_update.short_channel_id = short_channel_id;
1330 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1331 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1332 let valid_channel_update = ChannelUpdate {
1333 signature: secp_ctx.sign(&msghash, node_1_privkey),
1334 contents: unsigned_channel_update.clone()
1337 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1339 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1341 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1343 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1344 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1345 let valid_channel_update = ChannelUpdate {
1346 signature: secp_ctx.sign(&msghash, node_1_privkey),
1347 contents: unsigned_channel_update.clone()
1350 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1352 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1354 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1356 // Even though previous update was not relayed further, we still accepted it,
1357 // so we now won't accept update before the previous one.
1358 unsigned_channel_update.timestamp -= 10;
1359 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1360 let valid_channel_update = ChannelUpdate {
1361 signature: secp_ctx.sign(&msghash, node_1_privkey),
1362 contents: unsigned_channel_update.clone()
1365 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1367 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1369 unsigned_channel_update.timestamp += 500;
1371 let fake_msghash = hash_to_message!(&zero_hash);
1372 let invalid_sig_channel_update = ChannelUpdate {
1373 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1374 contents: unsigned_channel_update.clone()
1377 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1379 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1385 fn handling_htlc_fail_channel_update() {
1386 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1387 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1388 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1389 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1390 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1391 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1392 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1394 let short_channel_id = 0;
1395 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1398 // There is no nodes in the table at the beginning.
1399 let network = net_graph_msg_handler.network_graph.read().unwrap();
1400 assert_eq!(network.get_nodes().len(), 0);
1404 // Announce a channel we will update
1405 let unsigned_announcement = UnsignedChannelAnnouncement {
1406 features: ChannelFeatures::empty(),
1411 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1412 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1413 excess_data: Vec::new(),
1416 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1417 let valid_channel_announcement = ChannelAnnouncement {
1418 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1419 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1420 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1421 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1422 contents: unsigned_announcement.clone(),
1424 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1429 let unsigned_channel_update = UnsignedChannelUpdate {
1434 cltv_expiry_delta: 144,
1435 htlc_minimum_msat: 1000000,
1436 htlc_maximum_msat: OptionalField::Absent,
1437 fee_base_msat: 10000,
1438 fee_proportional_millionths: 20,
1439 excess_data: Vec::new()
1441 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1442 let valid_channel_update = ChannelUpdate {
1443 signature: secp_ctx.sign(&msghash, node_1_privkey),
1444 contents: unsigned_channel_update.clone()
1447 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1448 Ok(res) => assert!(res),
1453 // Non-permanent closing just disables a channel
1455 let network = net_graph_msg_handler.network_graph.read().unwrap();
1456 match network.get_channels().get(&short_channel_id) {
1458 Some(channel_info) => {
1459 assert!(channel_info.one_to_two.is_some());
1464 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1469 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1471 // Non-permanent closing just disables a channel
1473 let network = net_graph_msg_handler.network_graph.read().unwrap();
1474 match network.get_channels().get(&short_channel_id) {
1476 Some(channel_info) => {
1477 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1482 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1487 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1489 // Permanent closing deletes a channel
1491 let network = net_graph_msg_handler.network_graph.read().unwrap();
1492 assert_eq!(network.get_channels().len(), 0);
1493 // Nodes are also deleted because there are no associated channels anymore
1494 assert_eq!(network.get_nodes().len(), 0);
1496 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1500 fn getting_next_channel_announcements() {
1501 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1502 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1503 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1504 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1505 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1506 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1507 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1509 let short_channel_id = 1;
1510 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1512 // Channels were not announced yet.
1513 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1514 assert_eq!(channels_with_announcements.len(), 0);
1517 // Announce a channel we will update
1518 let unsigned_announcement = UnsignedChannelAnnouncement {
1519 features: ChannelFeatures::empty(),
1524 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1525 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1526 excess_data: Vec::new(),
1529 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1530 let valid_channel_announcement = ChannelAnnouncement {
1531 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1532 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1533 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1534 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1535 contents: unsigned_announcement.clone(),
1537 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1543 // Contains initial channel announcement now.
1544 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1545 assert_eq!(channels_with_announcements.len(), 1);
1546 if let Some(channel_announcements) = channels_with_announcements.first() {
1547 let &(_, ref update_1, ref update_2) = channel_announcements;
1548 assert_eq!(update_1, &None);
1549 assert_eq!(update_2, &None);
1556 // Valid channel update
1557 let unsigned_channel_update = UnsignedChannelUpdate {
1562 cltv_expiry_delta: 144,
1563 htlc_minimum_msat: 1000000,
1564 htlc_maximum_msat: OptionalField::Absent,
1565 fee_base_msat: 10000,
1566 fee_proportional_millionths: 20,
1567 excess_data: Vec::new()
1569 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1570 let valid_channel_update = ChannelUpdate {
1571 signature: secp_ctx.sign(&msghash, node_1_privkey),
1572 contents: unsigned_channel_update.clone()
1574 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1580 // Now contains an initial announcement and an update.
1581 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1582 assert_eq!(channels_with_announcements.len(), 1);
1583 if let Some(channel_announcements) = channels_with_announcements.first() {
1584 let &(_, ref update_1, ref update_2) = channel_announcements;
1585 assert_ne!(update_1, &None);
1586 assert_eq!(update_2, &None);
1593 // Channel update with excess data.
1594 let unsigned_channel_update = UnsignedChannelUpdate {
1599 cltv_expiry_delta: 144,
1600 htlc_minimum_msat: 1000000,
1601 htlc_maximum_msat: OptionalField::Absent,
1602 fee_base_msat: 10000,
1603 fee_proportional_millionths: 20,
1604 excess_data: [1; 3].to_vec()
1606 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1607 let valid_channel_update = ChannelUpdate {
1608 signature: secp_ctx.sign(&msghash, node_1_privkey),
1609 contents: unsigned_channel_update.clone()
1611 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1617 // Test that announcements with excess data won't be returned
1618 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1619 assert_eq!(channels_with_announcements.len(), 1);
1620 if let Some(channel_announcements) = channels_with_announcements.first() {
1621 let &(_, ref update_1, ref update_2) = channel_announcements;
1622 assert_eq!(update_1, &None);
1623 assert_eq!(update_2, &None);
1628 // Further starting point have no channels after it
1629 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1630 assert_eq!(channels_with_announcements.len(), 0);
1634 fn getting_next_node_announcements() {
1635 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1636 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1637 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1638 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1639 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1640 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1641 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1643 let short_channel_id = 1;
1644 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1647 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1648 assert_eq!(next_announcements.len(), 0);
1651 // Announce a channel to add 2 nodes
1652 let unsigned_announcement = UnsignedChannelAnnouncement {
1653 features: ChannelFeatures::empty(),
1658 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1659 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1660 excess_data: Vec::new(),
1663 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1664 let valid_channel_announcement = ChannelAnnouncement {
1665 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1666 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1667 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1668 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1669 contents: unsigned_announcement.clone(),
1671 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1678 // Nodes were never announced
1679 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1680 assert_eq!(next_announcements.len(), 0);
1683 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1684 features: NodeFeatures::known(),
1689 addresses: Vec::new(),
1690 excess_address_data: Vec::new(),
1691 excess_data: Vec::new(),
1693 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1694 let valid_announcement = NodeAnnouncement {
1695 signature: secp_ctx.sign(&msghash, node_1_privkey),
1696 contents: unsigned_announcement.clone()
1698 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1703 unsigned_announcement.node_id = node_id_2;
1704 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1705 let valid_announcement = NodeAnnouncement {
1706 signature: secp_ctx.sign(&msghash, node_2_privkey),
1707 contents: unsigned_announcement.clone()
1710 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1716 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1717 assert_eq!(next_announcements.len(), 2);
1719 // Skip the first node.
1720 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1721 assert_eq!(next_announcements.len(), 1);
1724 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1725 let unsigned_announcement = UnsignedNodeAnnouncement {
1726 features: NodeFeatures::known(),
1731 addresses: Vec::new(),
1732 excess_address_data: Vec::new(),
1733 excess_data: [1; 3].to_vec(),
1735 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1736 let valid_announcement = NodeAnnouncement {
1737 signature: secp_ctx.sign(&msghash, node_2_privkey),
1738 contents: unsigned_announcement.clone()
1740 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1741 Ok(res) => assert!(!res),
1746 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1747 assert_eq!(next_announcements.len(), 0);
1751 fn network_graph_serialization() {
1752 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1754 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1755 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1756 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1757 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1759 // Announce a channel to add a corresponding node.
1760 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1761 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1762 let unsigned_announcement = UnsignedChannelAnnouncement {
1763 features: ChannelFeatures::known(),
1764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1765 short_channel_id: 0,
1768 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1769 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1770 excess_data: Vec::new(),
1773 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1774 let valid_announcement = ChannelAnnouncement {
1775 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1776 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1777 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1778 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1779 contents: unsigned_announcement.clone(),
1781 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1782 Ok(res) => assert!(res),
1787 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1788 let unsigned_announcement = UnsignedNodeAnnouncement {
1789 features: NodeFeatures::known(),
1794 addresses: Vec::new(),
1795 excess_address_data: Vec::new(),
1796 excess_data: Vec::new(),
1798 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1799 let valid_announcement = NodeAnnouncement {
1800 signature: secp_ctx.sign(&msghash, node_1_privkey),
1801 contents: unsigned_announcement.clone()
1804 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1809 let network = net_graph_msg_handler.network_graph.write().unwrap();
1810 let mut w = test_utils::TestVecWriter(Vec::new());
1811 assert!(!network.get_nodes().is_empty());
1812 assert!(!network.get_channels().is_empty());
1813 network.write(&mut w).unwrap();
1814 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);