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;
21 use bitcoin::hash_types::BlockHash;
25 use ln::features::{ChannelFeatures, NodeFeatures};
26 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
27 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
28 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use util::ser::{Writeable, Readable, Writer};
31 use util::logger::Logger;
32 use util::events::{MessageSendEvent, MessageSendEventsProvider};
35 use std::sync::{RwLock, RwLockReadGuard};
36 use std::sync::atomic::{AtomicUsize, Ordering};
38 use std::collections::BTreeMap;
39 use std::collections::btree_map::Entry as BtreeEntry;
41 use bitcoin::hashes::hex::ToHex;
43 /// Represents the network as nodes and channels between them
45 pub struct NetworkGraph {
46 genesis_hash: BlockHash,
47 channels: BTreeMap<u64, ChannelInfo>,
48 nodes: BTreeMap<PublicKey, NodeInfo>,
51 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
52 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
53 /// the C bindings, as it can be done directly in Rust code.
54 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
56 /// Receives and validates network updates from peers,
57 /// stores authentic and relevant data as a network graph.
58 /// This network graph is then used for routing payments.
59 /// Provides interface to help with initial routing sync by
60 /// serving historical announcements.
61 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
62 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
63 /// Representation of the payment channel network
64 pub network_graph: RwLock<NetworkGraph>,
65 chain_access: Option<C>,
66 full_syncs_requested: AtomicUsize,
67 pending_events: Mutex<Vec<MessageSendEvent>>,
71 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
72 /// Creates a new tracker of the actual state of the network of channels and nodes,
73 /// assuming a fresh network graph.
74 /// Chain monitor is used to make sure announced channels exist on-chain,
75 /// channel data is correct, and that the announcement is signed with
76 /// channel owners' keys.
77 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
79 secp_ctx: Secp256k1::verification_only(),
80 network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
81 full_syncs_requested: AtomicUsize::new(0),
83 pending_events: Mutex::new(vec![]),
88 /// Creates a new tracker of the actual state of the network of channels and nodes,
89 /// assuming an existing Network Graph.
90 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
92 secp_ctx: Secp256k1::verification_only(),
93 network_graph: RwLock::new(network_graph),
94 full_syncs_requested: AtomicUsize::new(0),
96 pending_events: Mutex::new(vec![]),
101 /// Take a read lock on the network_graph and return it in the C-bindings
102 /// newtype helper. This is likely only useful when called via the C
103 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
105 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
106 LockedNetworkGraph(self.network_graph.read().unwrap())
109 /// Returns true when a full routing table sync should be performed with a peer.
110 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
111 //TODO: Determine whether to request a full sync based on the network map.
112 const FULL_SYNCS_TO_REQUEST: usize = 5;
113 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
114 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
122 impl<'a> LockedNetworkGraph<'a> {
123 /// Get a reference to the NetworkGraph which this read-lock contains.
124 pub fn graph(&self) -> &NetworkGraph {
130 macro_rules! secp_verify_sig {
131 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
132 match $secp_ctx.verify($msg, $sig, $pubkey) {
134 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
139 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
140 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
141 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
142 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty())
145 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
146 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
147 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 { "" });
148 Ok(msg.contents.excess_data.is_empty())
151 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
153 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
154 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
156 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
157 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
159 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
160 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
165 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
166 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
167 Ok(msg.contents.excess_data.is_empty())
170 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
171 let network_graph = self.network_graph.read().unwrap();
172 let mut result = Vec::with_capacity(batch_amount as usize);
173 let mut iter = network_graph.get_channels().range(starting_point..);
174 while result.len() < batch_amount as usize {
175 if let Some((_, ref chan)) = iter.next() {
176 if chan.announcement_message.is_some() {
177 let chan_announcement = chan.announcement_message.clone().unwrap();
178 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
179 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
180 if let Some(one_to_two) = chan.one_to_two.as_ref() {
181 one_to_two_announcement = one_to_two.last_update_message.clone();
183 if let Some(two_to_one) = chan.two_to_one.as_ref() {
184 two_to_one_announcement = two_to_one.last_update_message.clone();
186 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
188 // TODO: We may end up sending un-announced channel_updates if we are sending
189 // initial sync data while receiving announce/updates for this channel.
198 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
199 let network_graph = self.network_graph.read().unwrap();
200 let mut result = Vec::with_capacity(batch_amount as usize);
201 let mut iter = if let Some(pubkey) = starting_point {
202 let mut iter = network_graph.get_nodes().range((*pubkey)..);
206 network_graph.get_nodes().range(..)
208 while result.len() < batch_amount as usize {
209 if let Some((_, ref node)) = iter.next() {
210 if let Some(node_info) = node.announcement_info.as_ref() {
211 if node_info.announcement_message.is_some() {
212 result.push(node_info.announcement_message.clone().unwrap());
222 /// Initiates a stateless sync of routing gossip information with a peer
223 /// using gossip_queries. The default strategy used by this implementation
224 /// is to sync the full block range with several peers.
226 /// We should expect one or more reply_channel_range messages in response
227 /// to our query_channel_range. Each reply will enqueue a query_scid message
228 /// to request gossip messages for each channel. The sync is considered complete
229 /// when the final reply_scids_end message is received, though we are not
230 /// tracking this directly.
231 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
233 // We will only perform a sync with peers that support gossip_queries.
234 if !init_msg.features.supports_gossip_queries() {
238 // Check if we need to perform a full synchronization with this peer
239 if !self.should_request_full_sync(their_node_id) {
243 let first_blocknum = 0;
244 let number_of_blocks = 0xffffffff;
245 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
246 let mut pending_events = self.pending_events.lock().unwrap();
247 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
248 node_id: their_node_id.clone(),
249 msg: QueryChannelRange {
250 chain_hash: self.network_graph.read().unwrap().genesis_hash,
257 /// Statelessly processes a reply to a channel range query by immediately
258 /// sending an SCID query with SCIDs in the reply. To keep this handler
259 /// stateless, it does not validate the sequencing of replies for multi-
260 /// reply ranges. It does not validate whether the reply(ies) cover the
261 /// queried range. It also does not filter SCIDs to only those in the
262 /// original query range. We also do not validate that the chain_hash
263 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
264 /// does not match our chain_hash will be rejected when the announcement is
266 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
267 log_debug!(self.logger, "Handling reply_channel_range peer={}, first_blocknum={}, number_of_blocks={}, sync_complete={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.sync_complete, msg.short_channel_ids.len(),);
269 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
270 let mut pending_events = self.pending_events.lock().unwrap();
271 pending_events.push(MessageSendEvent::SendShortIdsQuery {
272 node_id: their_node_id.clone(),
273 msg: QueryShortChannelIds {
274 chain_hash: msg.chain_hash,
275 short_channel_ids: msg.short_channel_ids,
282 /// When an SCID query is initiated the remote peer will begin streaming
283 /// gossip messages. In the event of a failure, we may have received
284 /// some channel information. Before trying with another peer, the
285 /// caller should update its set of SCIDs that need to be queried.
286 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
287 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
289 // If the remote node does not have up-to-date information for the
290 // chain_hash they will set full_information=false. We can fail
291 // the result and try again with a different peer.
292 if !msg.full_information {
293 return Err(LightningError {
294 err: String::from("Received reply_short_channel_ids_end with no information"),
295 action: ErrorAction::IgnoreError
302 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: QueryChannelRange) -> Result<(), LightningError> {
305 err: String::from("Not implemented"),
306 action: ErrorAction::IgnoreError,
310 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
313 err: String::from("Not implemented"),
314 action: ErrorAction::IgnoreError,
319 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
321 C::Target: chain::Access,
324 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
325 let mut ret = Vec::new();
326 let mut pending_events = self.pending_events.lock().unwrap();
327 std::mem::swap(&mut ret, &mut pending_events);
332 #[derive(Clone, PartialEq, Debug)]
333 /// Details about one direction of a channel. Received
334 /// within a channel update.
335 pub struct DirectionalChannelInfo {
336 /// When the last update to the channel direction was issued.
337 /// Value is opaque, as set in the announcement.
338 pub last_update: u32,
339 /// Whether the channel can be currently used for payments (in this one direction).
341 /// The difference in CLTV values that you must have when routing through this channel.
342 pub cltv_expiry_delta: u16,
343 /// The minimum value, which must be relayed to the next hop via the channel
344 pub htlc_minimum_msat: u64,
345 /// The maximum value which may be relayed to the next hop via the channel.
346 pub htlc_maximum_msat: Option<u64>,
347 /// Fees charged when the channel is used for routing
348 pub fees: RoutingFees,
349 /// Most recent update for the channel received from the network
350 /// Mostly redundant with the data we store in fields explicitly.
351 /// Everything else is useful only for sending out for initial routing sync.
352 /// Not stored if contains excess data to prevent DoS.
353 pub last_update_message: Option<ChannelUpdate>,
356 impl fmt::Display for DirectionalChannelInfo {
357 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
358 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)?;
363 impl_writeable!(DirectionalChannelInfo, 0, {
374 /// Details about a channel (both directions).
375 /// Received within a channel announcement.
376 pub struct ChannelInfo {
377 /// Protocol features of a channel communicated during its announcement
378 pub features: ChannelFeatures,
379 /// Source node of the first direction of a channel
380 pub node_one: PublicKey,
381 /// Details about the first direction of a channel
382 pub one_to_two: Option<DirectionalChannelInfo>,
383 /// Source node of the second direction of a channel
384 pub node_two: PublicKey,
385 /// Details about the second direction of a channel
386 pub two_to_one: Option<DirectionalChannelInfo>,
387 /// The channel capacity as seen on-chain, if chain lookup is available.
388 pub capacity_sats: Option<u64>,
389 /// An initial announcement of the channel
390 /// Mostly redundant with the data we store in fields explicitly.
391 /// Everything else is useful only for sending out for initial routing sync.
392 /// Not stored if contains excess data to prevent DoS.
393 pub announcement_message: Option<ChannelAnnouncement>,
396 impl fmt::Display for ChannelInfo {
397 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
398 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
399 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
404 impl_writeable!(ChannelInfo, 0, {
415 /// Fees for routing via a given channel or a node
416 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
417 pub struct RoutingFees {
418 /// Flat routing fee in satoshis
420 /// Liquidity-based routing fee in millionths of a routed amount.
421 /// In other words, 10000 is 1%.
422 pub proportional_millionths: u32,
425 impl Readable for RoutingFees{
426 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
427 let base_msat: u32 = Readable::read(reader)?;
428 let proportional_millionths: u32 = Readable::read(reader)?;
431 proportional_millionths,
436 impl Writeable for RoutingFees {
437 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
438 self.base_msat.write(writer)?;
439 self.proportional_millionths.write(writer)?;
444 #[derive(Clone, PartialEq, Debug)]
445 /// Information received in the latest node_announcement from this node.
446 pub struct NodeAnnouncementInfo {
447 /// Protocol features the node announced support for
448 pub features: NodeFeatures,
449 /// When the last known update to the node state was issued.
450 /// Value is opaque, as set in the announcement.
451 pub last_update: u32,
452 /// Color assigned to the node
454 /// Moniker assigned to the node.
455 /// May be invalid or malicious (eg control chars),
456 /// should not be exposed to the user.
458 /// Internet-level addresses via which one can connect to the node
459 pub addresses: Vec<NetAddress>,
460 /// An initial announcement of the node
461 /// Mostly redundant with the data we store in fields explicitly.
462 /// Everything else is useful only for sending out for initial routing sync.
463 /// Not stored if contains excess data to prevent DoS.
464 pub announcement_message: Option<NodeAnnouncement>
467 impl Writeable for NodeAnnouncementInfo {
468 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
469 self.features.write(writer)?;
470 self.last_update.write(writer)?;
471 self.rgb.write(writer)?;
472 self.alias.write(writer)?;
473 (self.addresses.len() as u64).write(writer)?;
474 for ref addr in &self.addresses {
477 self.announcement_message.write(writer)?;
482 impl Readable for NodeAnnouncementInfo {
483 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
484 let features = Readable::read(reader)?;
485 let last_update = Readable::read(reader)?;
486 let rgb = Readable::read(reader)?;
487 let alias = Readable::read(reader)?;
488 let addresses_count: u64 = Readable::read(reader)?;
489 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
490 for _ in 0..addresses_count {
491 match Readable::read(reader) {
492 Ok(Ok(addr)) => { addresses.push(addr); },
493 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
494 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
498 let announcement_message = Readable::read(reader)?;
499 Ok(NodeAnnouncementInfo {
510 #[derive(Clone, PartialEq)]
511 /// Details about a node in the network, known from the network announcement.
512 pub struct NodeInfo {
513 /// All valid channels a node has announced
514 pub channels: Vec<u64>,
515 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
516 /// The two fields (flat and proportional fee) are independent,
517 /// meaning they don't have to refer to the same channel.
518 pub lowest_inbound_channel_fees: Option<RoutingFees>,
519 /// More information about a node from node_announcement.
520 /// Optional because we store a Node entry after learning about it from
521 /// a channel announcement, but before receiving a node announcement.
522 pub announcement_info: Option<NodeAnnouncementInfo>
525 impl fmt::Display for NodeInfo {
526 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
527 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
528 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
533 impl Writeable for NodeInfo {
534 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
535 (self.channels.len() as u64).write(writer)?;
536 for ref chan in self.channels.iter() {
539 self.lowest_inbound_channel_fees.write(writer)?;
540 self.announcement_info.write(writer)?;
545 const MAX_ALLOC_SIZE: u64 = 64*1024;
547 impl Readable for NodeInfo {
548 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
549 let channels_count: u64 = Readable::read(reader)?;
550 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
551 for _ in 0..channels_count {
552 channels.push(Readable::read(reader)?);
554 let lowest_inbound_channel_fees = Readable::read(reader)?;
555 let announcement_info = Readable::read(reader)?;
558 lowest_inbound_channel_fees,
564 impl Writeable for NetworkGraph {
565 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
566 self.genesis_hash.write(writer)?;
567 (self.channels.len() as u64).write(writer)?;
568 for (ref chan_id, ref chan_info) in self.channels.iter() {
569 (*chan_id).write(writer)?;
570 chan_info.write(writer)?;
572 (self.nodes.len() as u64).write(writer)?;
573 for (ref node_id, ref node_info) in self.nodes.iter() {
574 node_id.write(writer)?;
575 node_info.write(writer)?;
581 impl Readable for NetworkGraph {
582 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
583 let genesis_hash: BlockHash = Readable::read(reader)?;
584 let channels_count: u64 = Readable::read(reader)?;
585 let mut channels = BTreeMap::new();
586 for _ in 0..channels_count {
587 let chan_id: u64 = Readable::read(reader)?;
588 let chan_info = Readable::read(reader)?;
589 channels.insert(chan_id, chan_info);
591 let nodes_count: u64 = Readable::read(reader)?;
592 let mut nodes = BTreeMap::new();
593 for _ in 0..nodes_count {
594 let node_id = Readable::read(reader)?;
595 let node_info = Readable::read(reader)?;
596 nodes.insert(node_id, node_info);
606 impl fmt::Display for NetworkGraph {
607 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
608 writeln!(f, "Network map\n[Channels]")?;
609 for (key, val) in self.channels.iter() {
610 writeln!(f, " {}: {}", key, val)?;
612 writeln!(f, "[Nodes]")?;
613 for (key, val) in self.nodes.iter() {
614 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
621 /// Returns all known valid channels' short ids along with announced channel info.
623 /// (C-not exported) because we have no mapping for `BTreeMap`s
624 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
625 /// Returns all known nodes' public keys along with announced node info.
627 /// (C-not exported) because we have no mapping for `BTreeMap`s
628 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
630 /// Get network addresses by node id.
631 /// Returns None if the requested node is completely unknown,
632 /// or if node announcement for the node was never received.
634 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
635 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
636 if let Some(node) = self.nodes.get(pubkey) {
637 if let Some(node_info) = node.announcement_info.as_ref() {
638 return Some(&node_info.addresses)
644 /// Creates a new, empty, network graph.
645 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
648 channels: BTreeMap::new(),
649 nodes: BTreeMap::new(),
653 /// For an already known node (from channel announcements), update its stored properties from a
654 /// given node announcement.
656 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
657 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
658 /// routing messages from a source using a protocol other than the lightning P2P protocol.
659 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
660 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
661 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
662 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
665 /// For an already known node (from channel announcements), update its stored properties from a
666 /// given node announcement without verifying the associated signatures. Because we aren't
667 /// given the associated signatures here we cannot relay the node announcement to any of our
669 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
670 self.update_node_from_announcement_intern(msg, None)
673 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
674 match self.nodes.get_mut(&msg.node_id) {
675 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
677 if let Some(node_info) = node.announcement_info.as_ref() {
678 if node_info.last_update >= msg.timestamp {
679 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
683 let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
684 node.announcement_info = Some(NodeAnnouncementInfo {
685 features: msg.features.clone(),
686 last_update: msg.timestamp,
689 addresses: msg.addresses.clone(),
690 announcement_message: if should_relay { full_msg.cloned() } else { None },
698 /// Store or update channel info from a channel announcement.
700 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
701 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
702 /// routing messages from a source using a protocol other than the lightning P2P protocol.
704 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
705 /// the corresponding UTXO exists on chain and is correctly-formatted.
706 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
707 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
708 -> Result<(), LightningError>
709 where C::Target: chain::Access {
710 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
711 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
712 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
713 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
714 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
715 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
718 /// Store or update channel info from a channel announcement without verifying the associated
719 /// signatures. Because we aren't given the associated signatures here we cannot relay the
720 /// channel announcement to any of our peers.
722 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
723 /// the corresponding UTXO exists on chain and is correctly-formatted.
724 pub fn update_channel_from_unsigned_announcement<C: Deref>
725 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
726 -> Result<(), LightningError>
727 where C::Target: chain::Access {
728 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
731 fn update_channel_from_unsigned_announcement_intern<C: Deref>
732 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
733 -> Result<(), LightningError>
734 where C::Target: chain::Access {
735 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
736 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
739 let utxo_value = match &chain_access {
741 // Tentatively accept, potentially exposing us to DoS attacks
744 &Some(ref chain_access) => {
745 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
746 Ok(TxOut { value, script_pubkey }) => {
747 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
748 .push_slice(&msg.bitcoin_key_1.serialize())
749 .push_slice(&msg.bitcoin_key_2.serialize())
750 .push_opcode(opcodes::all::OP_PUSHNUM_2)
751 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
752 if script_pubkey != expected_script {
753 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});
755 //TODO: Check if value is worth storing, use it to inform routing, and compare it
756 //to the new HTLC max field in channel_update
759 Err(chain::AccessError::UnknownChain) => {
760 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
762 Err(chain::AccessError::UnknownTx) => {
763 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
769 let chan_info = ChannelInfo {
770 features: msg.features.clone(),
771 node_one: msg.node_id_1.clone(),
773 node_two: msg.node_id_2.clone(),
775 capacity_sats: utxo_value,
776 announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
779 match self.channels.entry(msg.short_channel_id) {
780 BtreeEntry::Occupied(mut entry) => {
781 //TODO: because asking the blockchain if short_channel_id is valid is only optional
782 //in the blockchain API, we need to handle it smartly here, though it's unclear
784 if utxo_value.is_some() {
785 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
786 // only sometimes returns results. In any case remove the previous entry. Note
787 // that the spec expects us to "blacklist" the node_ids involved, but we can't
789 // a) we don't *require* a UTXO provider that always returns results.
790 // b) we don't track UTXOs of channels we know about and remove them if they
792 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
793 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
794 *entry.get_mut() = chan_info;
796 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
799 BtreeEntry::Vacant(entry) => {
800 entry.insert(chan_info);
804 macro_rules! add_channel_to_node {
805 ( $node_id: expr ) => {
806 match self.nodes.entry($node_id) {
807 BtreeEntry::Occupied(node_entry) => {
808 node_entry.into_mut().channels.push(msg.short_channel_id);
810 BtreeEntry::Vacant(node_entry) => {
811 node_entry.insert(NodeInfo {
812 channels: vec!(msg.short_channel_id),
813 lowest_inbound_channel_fees: None,
814 announcement_info: None,
821 add_channel_to_node!(msg.node_id_1);
822 add_channel_to_node!(msg.node_id_2);
827 /// Close a channel if a corresponding HTLC fail was sent.
828 /// If permanent, removes a channel from the local storage.
829 /// May cause the removal of nodes too, if this was their last channel.
830 /// If not permanent, makes channels unavailable for routing.
831 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
833 if let Some(chan) = self.channels.remove(&short_channel_id) {
834 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
837 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
838 if let Some(one_to_two) = chan.one_to_two.as_mut() {
839 one_to_two.enabled = false;
841 if let Some(two_to_one) = chan.two_to_one.as_mut() {
842 two_to_one.enabled = false;
848 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
850 // TODO: Wholly remove the node
852 // TODO: downgrade the node
856 /// For an already known (from announcement) channel, update info about one of the directions
859 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
860 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
861 /// routing messages from a source using a protocol other than the lightning P2P protocol.
862 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
863 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
866 /// For an already known (from announcement) channel, update info about one of the directions
867 /// of the channel without verifying the associated signatures. Because we aren't given the
868 /// associated signatures here we cannot relay the channel update to any of our peers.
869 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
870 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
873 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> {
875 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
876 let chan_was_enabled;
878 match self.channels.get_mut(&msg.short_channel_id) {
879 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
881 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
882 if htlc_maximum_msat > MAX_VALUE_MSAT {
883 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
886 if let Some(capacity_sats) = channel.capacity_sats {
887 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
888 // Don't query UTXO set here to reduce DoS risks.
889 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
890 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
894 macro_rules! maybe_update_channel_info {
895 ( $target: expr, $src_node: expr) => {
896 if let Some(existing_chan_info) = $target.as_ref() {
897 if existing_chan_info.last_update >= msg.timestamp {
898 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
900 chan_was_enabled = existing_chan_info.enabled;
902 chan_was_enabled = false;
905 let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
907 let updated_channel_dir_info = DirectionalChannelInfo {
908 enabled: chan_enabled,
909 last_update: msg.timestamp,
910 cltv_expiry_delta: msg.cltv_expiry_delta,
911 htlc_minimum_msat: msg.htlc_minimum_msat,
912 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
914 base_msat: msg.fee_base_msat,
915 proportional_millionths: msg.fee_proportional_millionths,
919 $target = Some(updated_channel_dir_info);
923 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
924 if msg.flags & 1 == 1 {
925 dest_node_id = channel.node_one.clone();
926 if let Some((sig, ctx)) = sig_info {
927 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
929 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
931 dest_node_id = channel.node_two.clone();
932 if let Some((sig, ctx)) = sig_info {
933 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
935 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
941 let node = self.nodes.get_mut(&dest_node_id).unwrap();
942 let mut base_msat = msg.fee_base_msat;
943 let mut proportional_millionths = msg.fee_proportional_millionths;
944 if let Some(fees) = node.lowest_inbound_channel_fees {
945 base_msat = cmp::min(base_msat, fees.base_msat);
946 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
948 node.lowest_inbound_channel_fees = Some(RoutingFees {
950 proportional_millionths
952 } else if chan_was_enabled {
953 let node = self.nodes.get_mut(&dest_node_id).unwrap();
954 let mut lowest_inbound_channel_fees = None;
956 for chan_id in node.channels.iter() {
957 let chan = self.channels.get(chan_id).unwrap();
959 if chan.node_one == dest_node_id {
960 chan_info_opt = chan.two_to_one.as_ref();
962 chan_info_opt = chan.one_to_two.as_ref();
964 if let Some(chan_info) = chan_info_opt {
965 if chan_info.enabled {
966 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
967 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
968 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
969 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
974 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
980 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
981 macro_rules! remove_from_node {
982 ($node_id: expr) => {
983 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
984 entry.get_mut().channels.retain(|chan_id| {
985 short_channel_id != *chan_id
987 if entry.get().channels.is_empty() {
988 entry.remove_entry();
991 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
996 remove_from_node!(chan.node_one);
997 remove_from_node!(chan.node_two);
1004 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1005 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
1006 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1007 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1008 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1009 use util::test_utils;
1010 use util::logger::Logger;
1011 use util::ser::{Readable, Writeable};
1012 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1014 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1015 use bitcoin::hashes::Hash;
1016 use bitcoin::network::constants::Network;
1017 use bitcoin::blockdata::constants::genesis_block;
1018 use bitcoin::blockdata::script::Builder;
1019 use bitcoin::blockdata::transaction::TxOut;
1020 use bitcoin::blockdata::opcodes;
1024 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1025 use bitcoin::secp256k1::{All, Secp256k1};
1029 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1030 let secp_ctx = Secp256k1::new();
1031 let logger = Arc::new(test_utils::TestLogger::new());
1032 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1033 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1034 (secp_ctx, net_graph_msg_handler)
1038 fn request_full_sync_finite_times() {
1039 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1040 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1042 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1043 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1044 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1045 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1046 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1047 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1051 fn handling_node_announcements() {
1052 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1054 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1055 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1056 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1057 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1058 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1059 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1060 let zero_hash = Sha256dHash::hash(&[0; 32]);
1061 let first_announcement_time = 500;
1063 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1064 features: NodeFeatures::known(),
1065 timestamp: first_announcement_time,
1069 addresses: Vec::new(),
1070 excess_address_data: Vec::new(),
1071 excess_data: Vec::new(),
1073 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1074 let valid_announcement = NodeAnnouncement {
1075 signature: secp_ctx.sign(&msghash, node_1_privkey),
1076 contents: unsigned_announcement.clone()
1079 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1081 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1085 // Announce a channel to add a corresponding node.
1086 let unsigned_announcement = UnsignedChannelAnnouncement {
1087 features: ChannelFeatures::known(),
1088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1089 short_channel_id: 0,
1092 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1093 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1094 excess_data: Vec::new(),
1097 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1098 let valid_announcement = ChannelAnnouncement {
1099 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1100 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1101 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1102 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1103 contents: unsigned_announcement.clone(),
1105 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1106 Ok(res) => assert!(res),
1111 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1112 Ok(res) => assert!(res),
1116 let fake_msghash = hash_to_message!(&zero_hash);
1117 match net_graph_msg_handler.handle_node_announcement(
1119 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1120 contents: unsigned_announcement.clone()
1123 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1126 unsigned_announcement.timestamp += 1000;
1127 unsigned_announcement.excess_data.push(1);
1128 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1129 let announcement_with_data = NodeAnnouncement {
1130 signature: secp_ctx.sign(&msghash, node_1_privkey),
1131 contents: unsigned_announcement.clone()
1133 // Return false because contains excess data.
1134 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1135 Ok(res) => assert!(!res),
1138 unsigned_announcement.excess_data = Vec::new();
1140 // Even though previous announcement was not relayed further, we still accepted it,
1141 // so we now won't accept announcements before the previous one.
1142 unsigned_announcement.timestamp -= 10;
1143 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1144 let outdated_announcement = NodeAnnouncement {
1145 signature: secp_ctx.sign(&msghash, node_1_privkey),
1146 contents: unsigned_announcement.clone()
1148 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1150 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1155 fn handling_channel_announcements() {
1156 let secp_ctx = Secp256k1::new();
1157 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1159 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1160 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1161 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1162 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1163 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1164 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1166 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1167 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1168 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1169 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1170 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1173 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1174 features: ChannelFeatures::known(),
1175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1176 short_channel_id: 0,
1179 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1180 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1181 excess_data: Vec::new(),
1184 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1185 let valid_announcement = ChannelAnnouncement {
1186 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1187 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1188 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1189 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1190 contents: unsigned_announcement.clone(),
1193 // Test if the UTXO lookups were not supported
1194 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1195 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1196 Ok(res) => assert!(res),
1201 let network = net_graph_msg_handler.network_graph.read().unwrap();
1202 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1208 // If we receive announcement for the same channel (with UTXO lookups disabled),
1209 // drop new one on the floor, since we can't see any changes.
1210 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1212 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1215 // Test if an associated transaction were not on-chain (or not confirmed).
1216 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1217 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1218 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1219 unsigned_announcement.short_channel_id += 1;
1221 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1222 let valid_announcement = ChannelAnnouncement {
1223 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1224 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1225 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1226 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1227 contents: unsigned_announcement.clone(),
1230 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1232 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1235 // Now test if the transaction is found in the UTXO set and the script is correct.
1236 unsigned_announcement.short_channel_id += 1;
1237 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1239 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1240 let valid_announcement = ChannelAnnouncement {
1241 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1242 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1243 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1244 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1245 contents: unsigned_announcement.clone(),
1247 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1248 Ok(res) => assert!(res),
1253 let network = net_graph_msg_handler.network_graph.read().unwrap();
1254 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1260 // If we receive announcement for the same channel (but TX is not confirmed),
1261 // drop new one on the floor, since we can't see any changes.
1262 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1263 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1265 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1268 // But if it is confirmed, replace the channel
1269 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1270 unsigned_announcement.features = ChannelFeatures::empty();
1271 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1272 let valid_announcement = ChannelAnnouncement {
1273 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1274 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1275 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1276 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1277 contents: unsigned_announcement.clone(),
1279 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1280 Ok(res) => assert!(res),
1284 let network = net_graph_msg_handler.network_graph.read().unwrap();
1285 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1286 Some(channel_entry) => {
1287 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1293 // Don't relay valid channels with excess data
1294 unsigned_announcement.short_channel_id += 1;
1295 unsigned_announcement.excess_data.push(1);
1296 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1297 let valid_announcement = ChannelAnnouncement {
1298 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1299 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1300 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1301 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1302 contents: unsigned_announcement.clone(),
1304 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1305 Ok(res) => assert!(!res),
1309 unsigned_announcement.excess_data = Vec::new();
1310 let invalid_sig_announcement = ChannelAnnouncement {
1311 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1312 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1313 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1314 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1315 contents: unsigned_announcement.clone(),
1317 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1319 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1322 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1323 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1324 let channel_to_itself_announcement = ChannelAnnouncement {
1325 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1326 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1327 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1328 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1329 contents: unsigned_announcement.clone(),
1331 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1333 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1338 fn handling_channel_update() {
1339 let secp_ctx = Secp256k1::new();
1340 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1341 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1342 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1344 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1345 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1346 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1347 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1348 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1349 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1351 let zero_hash = Sha256dHash::hash(&[0; 32]);
1352 let short_channel_id = 0;
1353 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1354 let amount_sats = 1000_000;
1357 // Announce a channel we will update
1358 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1359 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1360 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1361 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1362 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1363 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1364 let unsigned_announcement = UnsignedChannelAnnouncement {
1365 features: ChannelFeatures::empty(),
1370 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1371 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1372 excess_data: Vec::new(),
1375 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1376 let valid_channel_announcement = ChannelAnnouncement {
1377 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1378 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1379 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1380 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1381 contents: unsigned_announcement.clone(),
1383 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1390 let mut unsigned_channel_update = UnsignedChannelUpdate {
1395 cltv_expiry_delta: 144,
1396 htlc_minimum_msat: 1000000,
1397 htlc_maximum_msat: OptionalField::Absent,
1398 fee_base_msat: 10000,
1399 fee_proportional_millionths: 20,
1400 excess_data: Vec::new()
1402 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1403 let valid_channel_update = ChannelUpdate {
1404 signature: secp_ctx.sign(&msghash, node_1_privkey),
1405 contents: unsigned_channel_update.clone()
1408 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1409 Ok(res) => assert!(res),
1414 let network = net_graph_msg_handler.network_graph.read().unwrap();
1415 match network.get_channels().get(&short_channel_id) {
1417 Some(channel_info) => {
1418 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1419 assert!(channel_info.two_to_one.is_none());
1424 unsigned_channel_update.timestamp += 100;
1425 unsigned_channel_update.excess_data.push(1);
1426 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1427 let valid_channel_update = ChannelUpdate {
1428 signature: secp_ctx.sign(&msghash, node_1_privkey),
1429 contents: unsigned_channel_update.clone()
1431 // Return false because contains excess data
1432 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1433 Ok(res) => assert!(!res),
1436 unsigned_channel_update.timestamp += 10;
1438 unsigned_channel_update.short_channel_id += 1;
1439 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1440 let valid_channel_update = ChannelUpdate {
1441 signature: secp_ctx.sign(&msghash, node_1_privkey),
1442 contents: unsigned_channel_update.clone()
1445 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1447 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1449 unsigned_channel_update.short_channel_id = short_channel_id;
1451 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1452 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1453 let valid_channel_update = ChannelUpdate {
1454 signature: secp_ctx.sign(&msghash, node_1_privkey),
1455 contents: unsigned_channel_update.clone()
1458 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1460 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1462 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1464 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1465 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1466 let valid_channel_update = ChannelUpdate {
1467 signature: secp_ctx.sign(&msghash, node_1_privkey),
1468 contents: unsigned_channel_update.clone()
1471 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1473 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1475 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1477 // Even though previous update was not relayed further, we still accepted it,
1478 // so we now won't accept update before the previous one.
1479 unsigned_channel_update.timestamp -= 10;
1480 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1481 let valid_channel_update = ChannelUpdate {
1482 signature: secp_ctx.sign(&msghash, node_1_privkey),
1483 contents: unsigned_channel_update.clone()
1486 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1488 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1490 unsigned_channel_update.timestamp += 500;
1492 let fake_msghash = hash_to_message!(&zero_hash);
1493 let invalid_sig_channel_update = ChannelUpdate {
1494 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1495 contents: unsigned_channel_update.clone()
1498 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1500 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1506 fn handling_htlc_fail_channel_update() {
1507 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1508 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1509 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1510 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1511 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1512 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1513 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1515 let short_channel_id = 0;
1516 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1519 // There is no nodes in the table at the beginning.
1520 let network = net_graph_msg_handler.network_graph.read().unwrap();
1521 assert_eq!(network.get_nodes().len(), 0);
1525 // Announce a channel we will update
1526 let unsigned_announcement = UnsignedChannelAnnouncement {
1527 features: ChannelFeatures::empty(),
1532 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1533 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1534 excess_data: Vec::new(),
1537 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1538 let valid_channel_announcement = ChannelAnnouncement {
1539 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1540 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1541 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1542 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1543 contents: unsigned_announcement.clone(),
1545 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1550 let unsigned_channel_update = UnsignedChannelUpdate {
1555 cltv_expiry_delta: 144,
1556 htlc_minimum_msat: 1000000,
1557 htlc_maximum_msat: OptionalField::Absent,
1558 fee_base_msat: 10000,
1559 fee_proportional_millionths: 20,
1560 excess_data: Vec::new()
1562 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1563 let valid_channel_update = ChannelUpdate {
1564 signature: secp_ctx.sign(&msghash, node_1_privkey),
1565 contents: unsigned_channel_update.clone()
1568 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1569 Ok(res) => assert!(res),
1574 // Non-permanent closing just disables a channel
1576 let network = net_graph_msg_handler.network_graph.read().unwrap();
1577 match network.get_channels().get(&short_channel_id) {
1579 Some(channel_info) => {
1580 assert!(channel_info.one_to_two.is_some());
1585 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1590 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1592 // Non-permanent closing just disables a channel
1594 let network = net_graph_msg_handler.network_graph.read().unwrap();
1595 match network.get_channels().get(&short_channel_id) {
1597 Some(channel_info) => {
1598 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1603 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1608 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1610 // Permanent closing deletes a channel
1612 let network = net_graph_msg_handler.network_graph.read().unwrap();
1613 assert_eq!(network.get_channels().len(), 0);
1614 // Nodes are also deleted because there are no associated channels anymore
1615 assert_eq!(network.get_nodes().len(), 0);
1617 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1621 fn getting_next_channel_announcements() {
1622 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1623 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1624 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1625 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1626 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1627 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1628 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1630 let short_channel_id = 1;
1631 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1633 // Channels were not announced yet.
1634 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1635 assert_eq!(channels_with_announcements.len(), 0);
1638 // Announce a channel we will update
1639 let unsigned_announcement = UnsignedChannelAnnouncement {
1640 features: ChannelFeatures::empty(),
1645 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1646 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1647 excess_data: Vec::new(),
1650 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1651 let valid_channel_announcement = ChannelAnnouncement {
1652 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1653 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1654 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1655 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1656 contents: unsigned_announcement.clone(),
1658 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1664 // Contains initial channel announcement now.
1665 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1666 assert_eq!(channels_with_announcements.len(), 1);
1667 if let Some(channel_announcements) = channels_with_announcements.first() {
1668 let &(_, ref update_1, ref update_2) = channel_announcements;
1669 assert_eq!(update_1, &None);
1670 assert_eq!(update_2, &None);
1677 // Valid channel update
1678 let unsigned_channel_update = UnsignedChannelUpdate {
1683 cltv_expiry_delta: 144,
1684 htlc_minimum_msat: 1000000,
1685 htlc_maximum_msat: OptionalField::Absent,
1686 fee_base_msat: 10000,
1687 fee_proportional_millionths: 20,
1688 excess_data: Vec::new()
1690 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1691 let valid_channel_update = ChannelUpdate {
1692 signature: secp_ctx.sign(&msghash, node_1_privkey),
1693 contents: unsigned_channel_update.clone()
1695 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1701 // Now contains an initial announcement and an update.
1702 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1703 assert_eq!(channels_with_announcements.len(), 1);
1704 if let Some(channel_announcements) = channels_with_announcements.first() {
1705 let &(_, ref update_1, ref update_2) = channel_announcements;
1706 assert_ne!(update_1, &None);
1707 assert_eq!(update_2, &None);
1714 // Channel update with excess data.
1715 let unsigned_channel_update = UnsignedChannelUpdate {
1720 cltv_expiry_delta: 144,
1721 htlc_minimum_msat: 1000000,
1722 htlc_maximum_msat: OptionalField::Absent,
1723 fee_base_msat: 10000,
1724 fee_proportional_millionths: 20,
1725 excess_data: [1; 3].to_vec()
1727 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1728 let valid_channel_update = ChannelUpdate {
1729 signature: secp_ctx.sign(&msghash, node_1_privkey),
1730 contents: unsigned_channel_update.clone()
1732 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1738 // Test that announcements with excess data won't be returned
1739 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1740 assert_eq!(channels_with_announcements.len(), 1);
1741 if let Some(channel_announcements) = channels_with_announcements.first() {
1742 let &(_, ref update_1, ref update_2) = channel_announcements;
1743 assert_eq!(update_1, &None);
1744 assert_eq!(update_2, &None);
1749 // Further starting point have no channels after it
1750 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1751 assert_eq!(channels_with_announcements.len(), 0);
1755 fn getting_next_node_announcements() {
1756 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1757 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1758 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1759 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1760 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1761 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1762 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1764 let short_channel_id = 1;
1765 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1768 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1769 assert_eq!(next_announcements.len(), 0);
1772 // Announce a channel to add 2 nodes
1773 let unsigned_announcement = UnsignedChannelAnnouncement {
1774 features: ChannelFeatures::empty(),
1779 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1780 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1781 excess_data: Vec::new(),
1784 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1785 let valid_channel_announcement = ChannelAnnouncement {
1786 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1787 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1788 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1789 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1790 contents: unsigned_announcement.clone(),
1792 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1799 // Nodes were never announced
1800 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1801 assert_eq!(next_announcements.len(), 0);
1804 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1805 features: NodeFeatures::known(),
1810 addresses: Vec::new(),
1811 excess_address_data: Vec::new(),
1812 excess_data: Vec::new(),
1814 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1815 let valid_announcement = NodeAnnouncement {
1816 signature: secp_ctx.sign(&msghash, node_1_privkey),
1817 contents: unsigned_announcement.clone()
1819 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1824 unsigned_announcement.node_id = node_id_2;
1825 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1826 let valid_announcement = NodeAnnouncement {
1827 signature: secp_ctx.sign(&msghash, node_2_privkey),
1828 contents: unsigned_announcement.clone()
1831 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1837 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1838 assert_eq!(next_announcements.len(), 2);
1840 // Skip the first node.
1841 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1842 assert_eq!(next_announcements.len(), 1);
1845 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1846 let unsigned_announcement = UnsignedNodeAnnouncement {
1847 features: NodeFeatures::known(),
1852 addresses: Vec::new(),
1853 excess_address_data: Vec::new(),
1854 excess_data: [1; 3].to_vec(),
1856 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1857 let valid_announcement = NodeAnnouncement {
1858 signature: secp_ctx.sign(&msghash, node_2_privkey),
1859 contents: unsigned_announcement.clone()
1861 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1862 Ok(res) => assert!(!res),
1867 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1868 assert_eq!(next_announcements.len(), 0);
1872 fn network_graph_serialization() {
1873 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1875 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1876 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1877 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1878 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1880 // Announce a channel to add a corresponding node.
1881 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1882 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1883 let unsigned_announcement = UnsignedChannelAnnouncement {
1884 features: ChannelFeatures::known(),
1885 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1886 short_channel_id: 0,
1889 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1890 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1891 excess_data: Vec::new(),
1894 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1895 let valid_announcement = ChannelAnnouncement {
1896 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1897 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1898 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1899 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1900 contents: unsigned_announcement.clone(),
1902 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1903 Ok(res) => assert!(res),
1908 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1909 let unsigned_announcement = UnsignedNodeAnnouncement {
1910 features: NodeFeatures::known(),
1915 addresses: Vec::new(),
1916 excess_address_data: Vec::new(),
1917 excess_data: Vec::new(),
1919 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1920 let valid_announcement = NodeAnnouncement {
1921 signature: secp_ctx.sign(&msghash, node_1_privkey),
1922 contents: unsigned_announcement.clone()
1925 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1930 let network = net_graph_msg_handler.network_graph.write().unwrap();
1931 let mut w = test_utils::TestVecWriter(Vec::new());
1932 assert!(!network.get_nodes().is_empty());
1933 assert!(!network.get_channels().is_empty());
1934 network.write(&mut w).unwrap();
1935 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1939 fn calling_sync_routing_table() {
1940 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1941 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1942 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
1944 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1945 let first_blocknum = 0;
1946 let number_of_blocks = 0xffff_ffff;
1948 // It should ignore if gossip_queries feature is not enabled
1950 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
1951 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1952 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1953 assert_eq!(events.len(), 0);
1956 // It should send a query_channel_message with the correct information
1958 let init_msg = Init { features: InitFeatures::known() };
1959 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1960 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1961 assert_eq!(events.len(), 1);
1963 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
1964 assert_eq!(node_id, &node_id_1);
1965 assert_eq!(msg.chain_hash, chain_hash);
1966 assert_eq!(msg.first_blocknum, first_blocknum);
1967 assert_eq!(msg.number_of_blocks, number_of_blocks);
1969 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
1973 // It should not enqueue a query when should_request_full_sync return false.
1974 // The initial implementation allows syncing with the first 5 peers after
1975 // which should_request_full_sync will return false
1977 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1978 let init_msg = Init { features: InitFeatures::known() };
1980 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
1981 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1982 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
1983 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1985 assert_eq!(events.len(), 1);
1987 assert_eq!(events.len(), 0);
1995 fn handling_reply_channel_range() {
1996 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1997 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1998 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2000 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2002 // Test receipt of a single reply that should enqueue an SCID query
2003 // matching the SCIDs in the reply
2005 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2007 sync_complete: true,
2009 number_of_blocks: 2000,
2010 short_channel_ids: vec![
2011 0x0003e0_000000_0000, // 992x0x0
2012 0x0003e8_000000_0000, // 1000x0x0
2013 0x0003e9_000000_0000, // 1001x0x0
2014 0x0003f0_000000_0000, // 1008x0x0
2015 0x00044c_000000_0000, // 1100x0x0
2016 0x0006e0_000000_0000, // 1760x0x0
2019 assert!(result.is_ok());
2021 // We expect to emit a query_short_channel_ids message with the received scids
2022 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2023 assert_eq!(events.len(), 1);
2025 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2026 assert_eq!(node_id, &node_id_1);
2027 assert_eq!(msg.chain_hash, chain_hash);
2028 assert_eq!(msg.short_channel_ids, vec![
2029 0x0003e0_000000_0000, // 992x0x0
2030 0x0003e8_000000_0000, // 1000x0x0
2031 0x0003e9_000000_0000, // 1001x0x0
2032 0x0003f0_000000_0000, // 1008x0x0
2033 0x00044c_000000_0000, // 1100x0x0
2034 0x0006e0_000000_0000, // 1760x0x0
2037 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2043 fn handling_reply_short_channel_ids() {
2044 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2045 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2046 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2048 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2050 // Test receipt of a successful reply
2052 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2054 full_information: true,
2056 assert!(result.is_ok());
2059 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2060 // for the chain_hash requested in the query.
2062 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2064 full_information: false,
2066 assert!(result.is_err());
2067 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2072 fn handling_query_channel_range() {
2073 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2074 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2075 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2077 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2079 let result = net_graph_msg_handler.handle_query_channel_range(&node_id, QueryChannelRange {
2082 number_of_blocks: 0xffff_ffff,
2084 assert!(result.is_err());
2088 fn handling_query_short_channel_ids() {
2089 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2090 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2091 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2093 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2095 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2097 short_channel_ids: vec![0x0003e8_000000_0000],
2099 assert!(result.is_err());