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={}, full_information={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.full_information, msg.short_channel_ids.len(),);
269 // Validate that the remote node maintains up-to-date channel
270 // information for chain_hash. Some nodes use the full_information
271 // flag to indicate multi-part messages so we must check whether
272 // we received SCIDs as well.
273 if !msg.full_information && msg.short_channel_ids.len() == 0 {
274 return Err(LightningError {
275 err: String::from("Received reply_channel_range with no information available"),
276 action: ErrorAction::IgnoreError,
280 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
281 let mut pending_events = self.pending_events.lock().unwrap();
282 pending_events.push(MessageSendEvent::SendShortIdsQuery {
283 node_id: their_node_id.clone(),
284 msg: QueryShortChannelIds {
285 chain_hash: msg.chain_hash,
286 short_channel_ids: msg.short_channel_ids,
293 /// When an SCID query is initiated the remote peer will begin streaming
294 /// gossip messages. In the event of a failure, we may have received
295 /// some channel information. Before trying with another peer, the
296 /// caller should update its set of SCIDs that need to be queried.
297 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
298 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
300 // If the remote node does not have up-to-date information for the
301 // chain_hash they will set full_information=false. We can fail
302 // the result and try again with a different peer.
303 if !msg.full_information {
304 return Err(LightningError {
305 err: String::from("Received reply_short_channel_ids_end with no information"),
306 action: ErrorAction::IgnoreError
313 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: QueryChannelRange) -> Result<(), LightningError> {
316 err: String::from("Not implemented"),
317 action: ErrorAction::IgnoreError,
321 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
324 err: String::from("Not implemented"),
325 action: ErrorAction::IgnoreError,
330 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
332 C::Target: chain::Access,
335 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
336 let mut ret = Vec::new();
337 let mut pending_events = self.pending_events.lock().unwrap();
338 std::mem::swap(&mut ret, &mut pending_events);
343 #[derive(PartialEq, Debug)]
344 /// Details about one direction of a channel. Received
345 /// within a channel update.
346 pub struct DirectionalChannelInfo {
347 /// When the last update to the channel direction was issued.
348 /// Value is opaque, as set in the announcement.
349 pub last_update: u32,
350 /// Whether the channel can be currently used for payments (in this one direction).
352 /// The difference in CLTV values that you must have when routing through this channel.
353 pub cltv_expiry_delta: u16,
354 /// The minimum value, which must be relayed to the next hop via the channel
355 pub htlc_minimum_msat: u64,
356 /// The maximum value which may be relayed to the next hop via the channel.
357 pub htlc_maximum_msat: Option<u64>,
358 /// Fees charged when the channel is used for routing
359 pub fees: RoutingFees,
360 /// Most recent update for the channel received from the network
361 /// Mostly redundant with the data we store in fields explicitly.
362 /// Everything else is useful only for sending out for initial routing sync.
363 /// Not stored if contains excess data to prevent DoS.
364 pub last_update_message: Option<ChannelUpdate>,
367 impl fmt::Display for DirectionalChannelInfo {
368 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
369 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)?;
374 impl_writeable!(DirectionalChannelInfo, 0, {
385 /// Details about a channel (both directions).
386 /// Received within a channel announcement.
387 pub struct ChannelInfo {
388 /// Protocol features of a channel communicated during its announcement
389 pub features: ChannelFeatures,
390 /// Source node of the first direction of a channel
391 pub node_one: PublicKey,
392 /// Details about the first direction of a channel
393 pub one_to_two: Option<DirectionalChannelInfo>,
394 /// Source node of the second direction of a channel
395 pub node_two: PublicKey,
396 /// Details about the second direction of a channel
397 pub two_to_one: Option<DirectionalChannelInfo>,
398 /// The channel capacity as seen on-chain, if chain lookup is available.
399 pub capacity_sats: Option<u64>,
400 /// An initial announcement of the channel
401 /// Mostly redundant with the data we store in fields explicitly.
402 /// Everything else is useful only for sending out for initial routing sync.
403 /// Not stored if contains excess data to prevent DoS.
404 pub announcement_message: Option<ChannelAnnouncement>,
407 impl fmt::Display for ChannelInfo {
408 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
409 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
410 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
415 impl_writeable!(ChannelInfo, 0, {
426 /// Fees for routing via a given channel or a node
427 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
428 pub struct RoutingFees {
429 /// Flat routing fee in satoshis
431 /// Liquidity-based routing fee in millionths of a routed amount.
432 /// In other words, 10000 is 1%.
433 pub proportional_millionths: u32,
436 impl Readable for RoutingFees{
437 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
438 let base_msat: u32 = Readable::read(reader)?;
439 let proportional_millionths: u32 = Readable::read(reader)?;
442 proportional_millionths,
447 impl Writeable for RoutingFees {
448 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
449 self.base_msat.write(writer)?;
450 self.proportional_millionths.write(writer)?;
455 #[derive(PartialEq, Debug)]
456 /// Information received in the latest node_announcement from this node.
457 pub struct NodeAnnouncementInfo {
458 /// Protocol features the node announced support for
459 pub features: NodeFeatures,
460 /// When the last known update to the node state was issued.
461 /// Value is opaque, as set in the announcement.
462 pub last_update: u32,
463 /// Color assigned to the node
465 /// Moniker assigned to the node.
466 /// May be invalid or malicious (eg control chars),
467 /// should not be exposed to the user.
469 /// Internet-level addresses via which one can connect to the node
470 pub addresses: Vec<NetAddress>,
471 /// An initial announcement of the node
472 /// Mostly redundant with the data we store in fields explicitly.
473 /// Everything else is useful only for sending out for initial routing sync.
474 /// Not stored if contains excess data to prevent DoS.
475 pub announcement_message: Option<NodeAnnouncement>
478 impl Writeable for NodeAnnouncementInfo {
479 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
480 self.features.write(writer)?;
481 self.last_update.write(writer)?;
482 self.rgb.write(writer)?;
483 self.alias.write(writer)?;
484 (self.addresses.len() as u64).write(writer)?;
485 for ref addr in &self.addresses {
488 self.announcement_message.write(writer)?;
493 impl Readable for NodeAnnouncementInfo {
494 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
495 let features = Readable::read(reader)?;
496 let last_update = Readable::read(reader)?;
497 let rgb = Readable::read(reader)?;
498 let alias = Readable::read(reader)?;
499 let addresses_count: u64 = Readable::read(reader)?;
500 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
501 for _ in 0..addresses_count {
502 match Readable::read(reader) {
503 Ok(Ok(addr)) => { addresses.push(addr); },
504 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
505 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
509 let announcement_message = Readable::read(reader)?;
510 Ok(NodeAnnouncementInfo {
522 /// Details about a node in the network, known from the network announcement.
523 pub struct NodeInfo {
524 /// All valid channels a node has announced
525 pub channels: Vec<u64>,
526 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
527 /// The two fields (flat and proportional fee) are independent,
528 /// meaning they don't have to refer to the same channel.
529 pub lowest_inbound_channel_fees: Option<RoutingFees>,
530 /// More information about a node from node_announcement.
531 /// Optional because we store a Node entry after learning about it from
532 /// a channel announcement, but before receiving a node announcement.
533 pub announcement_info: Option<NodeAnnouncementInfo>
536 impl fmt::Display for NodeInfo {
537 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
538 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
539 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
544 impl Writeable for NodeInfo {
545 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
546 (self.channels.len() as u64).write(writer)?;
547 for ref chan in self.channels.iter() {
550 self.lowest_inbound_channel_fees.write(writer)?;
551 self.announcement_info.write(writer)?;
556 const MAX_ALLOC_SIZE: u64 = 64*1024;
558 impl Readable for NodeInfo {
559 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
560 let channels_count: u64 = Readable::read(reader)?;
561 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
562 for _ in 0..channels_count {
563 channels.push(Readable::read(reader)?);
565 let lowest_inbound_channel_fees = Readable::read(reader)?;
566 let announcement_info = Readable::read(reader)?;
569 lowest_inbound_channel_fees,
575 impl Writeable for NetworkGraph {
576 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
577 self.genesis_hash.write(writer)?;
578 (self.channels.len() as u64).write(writer)?;
579 for (ref chan_id, ref chan_info) in self.channels.iter() {
580 (*chan_id).write(writer)?;
581 chan_info.write(writer)?;
583 (self.nodes.len() as u64).write(writer)?;
584 for (ref node_id, ref node_info) in self.nodes.iter() {
585 node_id.write(writer)?;
586 node_info.write(writer)?;
592 impl Readable for NetworkGraph {
593 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
594 let genesis_hash: BlockHash = Readable::read(reader)?;
595 let channels_count: u64 = Readable::read(reader)?;
596 let mut channels = BTreeMap::new();
597 for _ in 0..channels_count {
598 let chan_id: u64 = Readable::read(reader)?;
599 let chan_info = Readable::read(reader)?;
600 channels.insert(chan_id, chan_info);
602 let nodes_count: u64 = Readable::read(reader)?;
603 let mut nodes = BTreeMap::new();
604 for _ in 0..nodes_count {
605 let node_id = Readable::read(reader)?;
606 let node_info = Readable::read(reader)?;
607 nodes.insert(node_id, node_info);
617 impl fmt::Display for NetworkGraph {
618 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
619 writeln!(f, "Network map\n[Channels]")?;
620 for (key, val) in self.channels.iter() {
621 writeln!(f, " {}: {}", key, val)?;
623 writeln!(f, "[Nodes]")?;
624 for (key, val) in self.nodes.iter() {
625 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
632 /// Returns all known valid channels' short ids along with announced channel info.
634 /// (C-not exported) because we have no mapping for `BTreeMap`s
635 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
636 /// Returns all known nodes' public keys along with announced node info.
638 /// (C-not exported) because we have no mapping for `BTreeMap`s
639 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
641 /// Get network addresses by node id.
642 /// Returns None if the requested node is completely unknown,
643 /// or if node announcement for the node was never received.
645 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
646 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
647 if let Some(node) = self.nodes.get(pubkey) {
648 if let Some(node_info) = node.announcement_info.as_ref() {
649 return Some(&node_info.addresses)
655 /// Creates a new, empty, network graph.
656 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
659 channels: BTreeMap::new(),
660 nodes: BTreeMap::new(),
664 /// For an already known node (from channel announcements), update its stored properties from a
665 /// given node announcement.
667 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
668 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
669 /// routing messages from a source using a protocol other than the lightning P2P protocol.
670 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
671 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
672 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
673 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
676 /// For an already known node (from channel announcements), update its stored properties from a
677 /// given node announcement without verifying the associated signatures. Because we aren't
678 /// given the associated signatures here we cannot relay the node announcement to any of our
680 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
681 self.update_node_from_announcement_intern(msg, None)
684 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
685 match self.nodes.get_mut(&msg.node_id) {
686 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
688 if let Some(node_info) = node.announcement_info.as_ref() {
689 if node_info.last_update >= msg.timestamp {
690 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
694 let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
695 node.announcement_info = Some(NodeAnnouncementInfo {
696 features: msg.features.clone(),
697 last_update: msg.timestamp,
700 addresses: msg.addresses.clone(),
701 announcement_message: if should_relay { full_msg.cloned() } else { None },
709 /// Store or update channel info from a channel announcement.
711 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
712 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
713 /// routing messages from a source using a protocol other than the lightning P2P protocol.
715 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
716 /// the corresponding UTXO exists on chain and is correctly-formatted.
717 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
718 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
719 -> Result<(), LightningError>
720 where C::Target: chain::Access {
721 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
722 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
723 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
724 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
725 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
726 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
729 /// Store or update channel info from a channel announcement without verifying the associated
730 /// signatures. Because we aren't given the associated signatures here we cannot relay the
731 /// channel announcement to any of our peers.
733 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
734 /// the corresponding UTXO exists on chain and is correctly-formatted.
735 pub fn update_channel_from_unsigned_announcement<C: Deref>
736 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
737 -> Result<(), LightningError>
738 where C::Target: chain::Access {
739 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
742 fn update_channel_from_unsigned_announcement_intern<C: Deref>
743 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
744 -> Result<(), LightningError>
745 where C::Target: chain::Access {
746 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
747 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
750 let utxo_value = match &chain_access {
752 // Tentatively accept, potentially exposing us to DoS attacks
755 &Some(ref chain_access) => {
756 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
757 Ok(TxOut { value, script_pubkey }) => {
758 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
759 .push_slice(&msg.bitcoin_key_1.serialize())
760 .push_slice(&msg.bitcoin_key_2.serialize())
761 .push_opcode(opcodes::all::OP_PUSHNUM_2)
762 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
763 if script_pubkey != expected_script {
764 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});
766 //TODO: Check if value is worth storing, use it to inform routing, and compare it
767 //to the new HTLC max field in channel_update
770 Err(chain::AccessError::UnknownChain) => {
771 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
773 Err(chain::AccessError::UnknownTx) => {
774 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
780 let chan_info = ChannelInfo {
781 features: msg.features.clone(),
782 node_one: msg.node_id_1.clone(),
784 node_two: msg.node_id_2.clone(),
786 capacity_sats: utxo_value,
787 announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
790 match self.channels.entry(msg.short_channel_id) {
791 BtreeEntry::Occupied(mut entry) => {
792 //TODO: because asking the blockchain if short_channel_id is valid is only optional
793 //in the blockchain API, we need to handle it smartly here, though it's unclear
795 if utxo_value.is_some() {
796 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
797 // only sometimes returns results. In any case remove the previous entry. Note
798 // that the spec expects us to "blacklist" the node_ids involved, but we can't
800 // a) we don't *require* a UTXO provider that always returns results.
801 // b) we don't track UTXOs of channels we know about and remove them if they
803 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
804 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
805 *entry.get_mut() = chan_info;
807 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
810 BtreeEntry::Vacant(entry) => {
811 entry.insert(chan_info);
815 macro_rules! add_channel_to_node {
816 ( $node_id: expr ) => {
817 match self.nodes.entry($node_id) {
818 BtreeEntry::Occupied(node_entry) => {
819 node_entry.into_mut().channels.push(msg.short_channel_id);
821 BtreeEntry::Vacant(node_entry) => {
822 node_entry.insert(NodeInfo {
823 channels: vec!(msg.short_channel_id),
824 lowest_inbound_channel_fees: None,
825 announcement_info: None,
832 add_channel_to_node!(msg.node_id_1);
833 add_channel_to_node!(msg.node_id_2);
838 /// Close a channel if a corresponding HTLC fail was sent.
839 /// If permanent, removes a channel from the local storage.
840 /// May cause the removal of nodes too, if this was their last channel.
841 /// If not permanent, makes channels unavailable for routing.
842 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
844 if let Some(chan) = self.channels.remove(&short_channel_id) {
845 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
848 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
849 if let Some(one_to_two) = chan.one_to_two.as_mut() {
850 one_to_two.enabled = false;
852 if let Some(two_to_one) = chan.two_to_one.as_mut() {
853 two_to_one.enabled = false;
859 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
861 // TODO: Wholly remove the node
863 // TODO: downgrade the node
867 /// For an already known (from announcement) channel, update info about one of the directions
870 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
871 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
872 /// routing messages from a source using a protocol other than the lightning P2P protocol.
873 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
874 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
877 /// For an already known (from announcement) channel, update info about one of the directions
878 /// of the channel without verifying the associated signatures. Because we aren't given the
879 /// associated signatures here we cannot relay the channel update to any of our peers.
880 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
881 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
884 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> {
886 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
887 let chan_was_enabled;
889 match self.channels.get_mut(&msg.short_channel_id) {
890 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
892 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
893 if htlc_maximum_msat > MAX_VALUE_MSAT {
894 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
897 if let Some(capacity_sats) = channel.capacity_sats {
898 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
899 // Don't query UTXO set here to reduce DoS risks.
900 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
901 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
905 macro_rules! maybe_update_channel_info {
906 ( $target: expr, $src_node: expr) => {
907 if let Some(existing_chan_info) = $target.as_ref() {
908 if existing_chan_info.last_update >= msg.timestamp {
909 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
911 chan_was_enabled = existing_chan_info.enabled;
913 chan_was_enabled = false;
916 let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
918 let updated_channel_dir_info = DirectionalChannelInfo {
919 enabled: chan_enabled,
920 last_update: msg.timestamp,
921 cltv_expiry_delta: msg.cltv_expiry_delta,
922 htlc_minimum_msat: msg.htlc_minimum_msat,
923 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
925 base_msat: msg.fee_base_msat,
926 proportional_millionths: msg.fee_proportional_millionths,
930 $target = Some(updated_channel_dir_info);
934 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
935 if msg.flags & 1 == 1 {
936 dest_node_id = channel.node_one.clone();
937 if let Some((sig, ctx)) = sig_info {
938 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
940 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
942 dest_node_id = channel.node_two.clone();
943 if let Some((sig, ctx)) = sig_info {
944 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
946 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
952 let node = self.nodes.get_mut(&dest_node_id).unwrap();
953 let mut base_msat = msg.fee_base_msat;
954 let mut proportional_millionths = msg.fee_proportional_millionths;
955 if let Some(fees) = node.lowest_inbound_channel_fees {
956 base_msat = cmp::min(base_msat, fees.base_msat);
957 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
959 node.lowest_inbound_channel_fees = Some(RoutingFees {
961 proportional_millionths
963 } else if chan_was_enabled {
964 let node = self.nodes.get_mut(&dest_node_id).unwrap();
965 let mut lowest_inbound_channel_fees = None;
967 for chan_id in node.channels.iter() {
968 let chan = self.channels.get(chan_id).unwrap();
970 if chan.node_one == dest_node_id {
971 chan_info_opt = chan.two_to_one.as_ref();
973 chan_info_opt = chan.one_to_two.as_ref();
975 if let Some(chan_info) = chan_info_opt {
976 if chan_info.enabled {
977 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
978 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
979 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
980 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
985 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
991 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
992 macro_rules! remove_from_node {
993 ($node_id: expr) => {
994 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
995 entry.get_mut().channels.retain(|chan_id| {
996 short_channel_id != *chan_id
998 if entry.get().channels.is_empty() {
999 entry.remove_entry();
1002 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1007 remove_from_node!(chan.node_one);
1008 remove_from_node!(chan.node_two);
1015 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1016 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
1017 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1018 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1019 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1020 use util::test_utils;
1021 use util::logger::Logger;
1022 use util::ser::{Readable, Writeable};
1023 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1025 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1026 use bitcoin::hashes::Hash;
1027 use bitcoin::network::constants::Network;
1028 use bitcoin::blockdata::constants::genesis_block;
1029 use bitcoin::blockdata::script::Builder;
1030 use bitcoin::blockdata::transaction::TxOut;
1031 use bitcoin::blockdata::opcodes;
1035 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1036 use bitcoin::secp256k1::{All, Secp256k1};
1040 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1041 let secp_ctx = Secp256k1::new();
1042 let logger = Arc::new(test_utils::TestLogger::new());
1043 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1044 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1045 (secp_ctx, net_graph_msg_handler)
1049 fn request_full_sync_finite_times() {
1050 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1051 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1053 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1054 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1055 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1056 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1057 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1058 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1062 fn handling_node_announcements() {
1063 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1065 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1066 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1067 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1068 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1069 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1070 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1071 let zero_hash = Sha256dHash::hash(&[0; 32]);
1072 let first_announcement_time = 500;
1074 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1075 features: NodeFeatures::known(),
1076 timestamp: first_announcement_time,
1080 addresses: Vec::new(),
1081 excess_address_data: Vec::new(),
1082 excess_data: Vec::new(),
1084 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1085 let valid_announcement = NodeAnnouncement {
1086 signature: secp_ctx.sign(&msghash, node_1_privkey),
1087 contents: unsigned_announcement.clone()
1090 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1092 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1096 // Announce a channel to add a corresponding node.
1097 let unsigned_announcement = UnsignedChannelAnnouncement {
1098 features: ChannelFeatures::known(),
1099 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1100 short_channel_id: 0,
1103 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1104 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1105 excess_data: Vec::new(),
1108 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1109 let valid_announcement = ChannelAnnouncement {
1110 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1111 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1112 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1113 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1114 contents: unsigned_announcement.clone(),
1116 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1117 Ok(res) => assert!(res),
1122 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1123 Ok(res) => assert!(res),
1127 let fake_msghash = hash_to_message!(&zero_hash);
1128 match net_graph_msg_handler.handle_node_announcement(
1130 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1131 contents: unsigned_announcement.clone()
1134 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1137 unsigned_announcement.timestamp += 1000;
1138 unsigned_announcement.excess_data.push(1);
1139 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1140 let announcement_with_data = NodeAnnouncement {
1141 signature: secp_ctx.sign(&msghash, node_1_privkey),
1142 contents: unsigned_announcement.clone()
1144 // Return false because contains excess data.
1145 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1146 Ok(res) => assert!(!res),
1149 unsigned_announcement.excess_data = Vec::new();
1151 // Even though previous announcement was not relayed further, we still accepted it,
1152 // so we now won't accept announcements before the previous one.
1153 unsigned_announcement.timestamp -= 10;
1154 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1155 let outdated_announcement = NodeAnnouncement {
1156 signature: secp_ctx.sign(&msghash, node_1_privkey),
1157 contents: unsigned_announcement.clone()
1159 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1161 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1166 fn handling_channel_announcements() {
1167 let secp_ctx = Secp256k1::new();
1168 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1170 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1171 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1172 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1173 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1174 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1175 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1177 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1178 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1179 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1180 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1181 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1184 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1185 features: ChannelFeatures::known(),
1186 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1187 short_channel_id: 0,
1190 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1191 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1192 excess_data: Vec::new(),
1195 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1196 let valid_announcement = ChannelAnnouncement {
1197 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1198 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1199 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1200 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1201 contents: unsigned_announcement.clone(),
1204 // Test if the UTXO lookups were not supported
1205 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1206 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1207 Ok(res) => assert!(res),
1212 let network = net_graph_msg_handler.network_graph.read().unwrap();
1213 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1219 // If we receive announcement for the same channel (with UTXO lookups disabled),
1220 // drop new one on the floor, since we can't see any changes.
1221 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1223 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1226 // Test if an associated transaction were not on-chain (or not confirmed).
1227 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1228 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1229 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1230 unsigned_announcement.short_channel_id += 1;
1232 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1233 let valid_announcement = ChannelAnnouncement {
1234 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1235 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1236 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1237 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1238 contents: unsigned_announcement.clone(),
1241 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1243 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1246 // Now test if the transaction is found in the UTXO set and the script is correct.
1247 unsigned_announcement.short_channel_id += 1;
1248 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1250 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1251 let valid_announcement = ChannelAnnouncement {
1252 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1253 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1254 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1255 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1256 contents: unsigned_announcement.clone(),
1258 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1259 Ok(res) => assert!(res),
1264 let network = net_graph_msg_handler.network_graph.read().unwrap();
1265 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1271 // If we receive announcement for the same channel (but TX is not confirmed),
1272 // drop new one on the floor, since we can't see any changes.
1273 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1274 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1276 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1279 // But if it is confirmed, replace the channel
1280 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1281 unsigned_announcement.features = ChannelFeatures::empty();
1282 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1283 let valid_announcement = ChannelAnnouncement {
1284 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1285 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1286 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1287 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1288 contents: unsigned_announcement.clone(),
1290 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1291 Ok(res) => assert!(res),
1295 let network = net_graph_msg_handler.network_graph.read().unwrap();
1296 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1297 Some(channel_entry) => {
1298 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1304 // Don't relay valid channels with excess data
1305 unsigned_announcement.short_channel_id += 1;
1306 unsigned_announcement.excess_data.push(1);
1307 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1308 let valid_announcement = ChannelAnnouncement {
1309 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1310 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1311 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1312 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1313 contents: unsigned_announcement.clone(),
1315 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1316 Ok(res) => assert!(!res),
1320 unsigned_announcement.excess_data = Vec::new();
1321 let invalid_sig_announcement = ChannelAnnouncement {
1322 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1323 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1324 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1325 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1326 contents: unsigned_announcement.clone(),
1328 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1330 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1333 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1334 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1335 let channel_to_itself_announcement = ChannelAnnouncement {
1336 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1337 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1338 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1339 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1340 contents: unsigned_announcement.clone(),
1342 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1344 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1349 fn handling_channel_update() {
1350 let secp_ctx = Secp256k1::new();
1351 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1352 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1353 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1355 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1356 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1357 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1358 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1359 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1360 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1362 let zero_hash = Sha256dHash::hash(&[0; 32]);
1363 let short_channel_id = 0;
1364 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1365 let amount_sats = 1000_000;
1368 // Announce a channel we will update
1369 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1370 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1371 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1372 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1373 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1374 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1375 let unsigned_announcement = UnsignedChannelAnnouncement {
1376 features: ChannelFeatures::empty(),
1381 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1382 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1383 excess_data: Vec::new(),
1386 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1387 let valid_channel_announcement = ChannelAnnouncement {
1388 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1389 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1390 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1391 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1392 contents: unsigned_announcement.clone(),
1394 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1401 let mut unsigned_channel_update = UnsignedChannelUpdate {
1406 cltv_expiry_delta: 144,
1407 htlc_minimum_msat: 1000000,
1408 htlc_maximum_msat: OptionalField::Absent,
1409 fee_base_msat: 10000,
1410 fee_proportional_millionths: 20,
1411 excess_data: Vec::new()
1413 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1414 let valid_channel_update = ChannelUpdate {
1415 signature: secp_ctx.sign(&msghash, node_1_privkey),
1416 contents: unsigned_channel_update.clone()
1419 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1420 Ok(res) => assert!(res),
1425 let network = net_graph_msg_handler.network_graph.read().unwrap();
1426 match network.get_channels().get(&short_channel_id) {
1428 Some(channel_info) => {
1429 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1430 assert!(channel_info.two_to_one.is_none());
1435 unsigned_channel_update.timestamp += 100;
1436 unsigned_channel_update.excess_data.push(1);
1437 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1438 let valid_channel_update = ChannelUpdate {
1439 signature: secp_ctx.sign(&msghash, node_1_privkey),
1440 contents: unsigned_channel_update.clone()
1442 // Return false because contains excess data
1443 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1444 Ok(res) => assert!(!res),
1447 unsigned_channel_update.timestamp += 10;
1449 unsigned_channel_update.short_channel_id += 1;
1450 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1451 let valid_channel_update = ChannelUpdate {
1452 signature: secp_ctx.sign(&msghash, node_1_privkey),
1453 contents: unsigned_channel_update.clone()
1456 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1458 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1460 unsigned_channel_update.short_channel_id = short_channel_id;
1462 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1463 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1464 let valid_channel_update = ChannelUpdate {
1465 signature: secp_ctx.sign(&msghash, node_1_privkey),
1466 contents: unsigned_channel_update.clone()
1469 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1471 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1473 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1475 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1476 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1477 let valid_channel_update = ChannelUpdate {
1478 signature: secp_ctx.sign(&msghash, node_1_privkey),
1479 contents: unsigned_channel_update.clone()
1482 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1484 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1486 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1488 // Even though previous update was not relayed further, we still accepted it,
1489 // so we now won't accept update before the previous one.
1490 unsigned_channel_update.timestamp -= 10;
1491 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1492 let valid_channel_update = ChannelUpdate {
1493 signature: secp_ctx.sign(&msghash, node_1_privkey),
1494 contents: unsigned_channel_update.clone()
1497 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1499 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1501 unsigned_channel_update.timestamp += 500;
1503 let fake_msghash = hash_to_message!(&zero_hash);
1504 let invalid_sig_channel_update = ChannelUpdate {
1505 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1506 contents: unsigned_channel_update.clone()
1509 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1511 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1517 fn handling_htlc_fail_channel_update() {
1518 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1519 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1520 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1521 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1522 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1523 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1524 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1526 let short_channel_id = 0;
1527 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1530 // There is no nodes in the table at the beginning.
1531 let network = net_graph_msg_handler.network_graph.read().unwrap();
1532 assert_eq!(network.get_nodes().len(), 0);
1536 // Announce a channel we will update
1537 let unsigned_announcement = UnsignedChannelAnnouncement {
1538 features: ChannelFeatures::empty(),
1543 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1544 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1545 excess_data: Vec::new(),
1548 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1549 let valid_channel_announcement = ChannelAnnouncement {
1550 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1551 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1552 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1553 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1554 contents: unsigned_announcement.clone(),
1556 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1561 let unsigned_channel_update = UnsignedChannelUpdate {
1566 cltv_expiry_delta: 144,
1567 htlc_minimum_msat: 1000000,
1568 htlc_maximum_msat: OptionalField::Absent,
1569 fee_base_msat: 10000,
1570 fee_proportional_millionths: 20,
1571 excess_data: Vec::new()
1573 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1574 let valid_channel_update = ChannelUpdate {
1575 signature: secp_ctx.sign(&msghash, node_1_privkey),
1576 contents: unsigned_channel_update.clone()
1579 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1580 Ok(res) => assert!(res),
1585 // Non-permanent closing just disables a channel
1587 let network = net_graph_msg_handler.network_graph.read().unwrap();
1588 match network.get_channels().get(&short_channel_id) {
1590 Some(channel_info) => {
1591 assert!(channel_info.one_to_two.is_some());
1596 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1601 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1603 // Non-permanent closing just disables a channel
1605 let network = net_graph_msg_handler.network_graph.read().unwrap();
1606 match network.get_channels().get(&short_channel_id) {
1608 Some(channel_info) => {
1609 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1614 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1619 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1621 // Permanent closing deletes a channel
1623 let network = net_graph_msg_handler.network_graph.read().unwrap();
1624 assert_eq!(network.get_channels().len(), 0);
1625 // Nodes are also deleted because there are no associated channels anymore
1626 assert_eq!(network.get_nodes().len(), 0);
1628 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1632 fn getting_next_channel_announcements() {
1633 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1634 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1635 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1636 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1637 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1638 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1639 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1641 let short_channel_id = 1;
1642 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1644 // Channels were not announced yet.
1645 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1646 assert_eq!(channels_with_announcements.len(), 0);
1649 // Announce a channel we will update
1650 let unsigned_announcement = UnsignedChannelAnnouncement {
1651 features: ChannelFeatures::empty(),
1656 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1657 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1658 excess_data: Vec::new(),
1661 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1662 let valid_channel_announcement = ChannelAnnouncement {
1663 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1664 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1665 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1666 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1667 contents: unsigned_announcement.clone(),
1669 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1675 // Contains initial channel announcement now.
1676 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1677 assert_eq!(channels_with_announcements.len(), 1);
1678 if let Some(channel_announcements) = channels_with_announcements.first() {
1679 let &(_, ref update_1, ref update_2) = channel_announcements;
1680 assert_eq!(update_1, &None);
1681 assert_eq!(update_2, &None);
1688 // Valid channel update
1689 let unsigned_channel_update = UnsignedChannelUpdate {
1694 cltv_expiry_delta: 144,
1695 htlc_minimum_msat: 1000000,
1696 htlc_maximum_msat: OptionalField::Absent,
1697 fee_base_msat: 10000,
1698 fee_proportional_millionths: 20,
1699 excess_data: Vec::new()
1701 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1702 let valid_channel_update = ChannelUpdate {
1703 signature: secp_ctx.sign(&msghash, node_1_privkey),
1704 contents: unsigned_channel_update.clone()
1706 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1712 // Now contains an initial announcement and an update.
1713 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1714 assert_eq!(channels_with_announcements.len(), 1);
1715 if let Some(channel_announcements) = channels_with_announcements.first() {
1716 let &(_, ref update_1, ref update_2) = channel_announcements;
1717 assert_ne!(update_1, &None);
1718 assert_eq!(update_2, &None);
1725 // Channel update with excess data.
1726 let unsigned_channel_update = UnsignedChannelUpdate {
1731 cltv_expiry_delta: 144,
1732 htlc_minimum_msat: 1000000,
1733 htlc_maximum_msat: OptionalField::Absent,
1734 fee_base_msat: 10000,
1735 fee_proportional_millionths: 20,
1736 excess_data: [1; 3].to_vec()
1738 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1739 let valid_channel_update = ChannelUpdate {
1740 signature: secp_ctx.sign(&msghash, node_1_privkey),
1741 contents: unsigned_channel_update.clone()
1743 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1749 // Test that announcements with excess data won't be returned
1750 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1751 assert_eq!(channels_with_announcements.len(), 1);
1752 if let Some(channel_announcements) = channels_with_announcements.first() {
1753 let &(_, ref update_1, ref update_2) = channel_announcements;
1754 assert_eq!(update_1, &None);
1755 assert_eq!(update_2, &None);
1760 // Further starting point have no channels after it
1761 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1762 assert_eq!(channels_with_announcements.len(), 0);
1766 fn getting_next_node_announcements() {
1767 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1768 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1769 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1770 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1771 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1772 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1773 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1775 let short_channel_id = 1;
1776 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1779 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1780 assert_eq!(next_announcements.len(), 0);
1783 // Announce a channel to add 2 nodes
1784 let unsigned_announcement = UnsignedChannelAnnouncement {
1785 features: ChannelFeatures::empty(),
1790 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1791 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1792 excess_data: Vec::new(),
1795 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1796 let valid_channel_announcement = ChannelAnnouncement {
1797 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1798 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1799 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1800 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1801 contents: unsigned_announcement.clone(),
1803 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1810 // Nodes were never announced
1811 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1812 assert_eq!(next_announcements.len(), 0);
1815 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1816 features: NodeFeatures::known(),
1821 addresses: Vec::new(),
1822 excess_address_data: Vec::new(),
1823 excess_data: Vec::new(),
1825 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1826 let valid_announcement = NodeAnnouncement {
1827 signature: secp_ctx.sign(&msghash, node_1_privkey),
1828 contents: unsigned_announcement.clone()
1830 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1835 unsigned_announcement.node_id = node_id_2;
1836 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1837 let valid_announcement = NodeAnnouncement {
1838 signature: secp_ctx.sign(&msghash, node_2_privkey),
1839 contents: unsigned_announcement.clone()
1842 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1848 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1849 assert_eq!(next_announcements.len(), 2);
1851 // Skip the first node.
1852 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1853 assert_eq!(next_announcements.len(), 1);
1856 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1857 let unsigned_announcement = UnsignedNodeAnnouncement {
1858 features: NodeFeatures::known(),
1863 addresses: Vec::new(),
1864 excess_address_data: Vec::new(),
1865 excess_data: [1; 3].to_vec(),
1867 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1868 let valid_announcement = NodeAnnouncement {
1869 signature: secp_ctx.sign(&msghash, node_2_privkey),
1870 contents: unsigned_announcement.clone()
1872 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1873 Ok(res) => assert!(!res),
1878 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1879 assert_eq!(next_announcements.len(), 0);
1883 fn network_graph_serialization() {
1884 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1886 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1887 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1888 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1889 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1891 // Announce a channel to add a corresponding node.
1892 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1893 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1894 let unsigned_announcement = UnsignedChannelAnnouncement {
1895 features: ChannelFeatures::known(),
1896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1897 short_channel_id: 0,
1900 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1901 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1902 excess_data: Vec::new(),
1905 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1906 let valid_announcement = ChannelAnnouncement {
1907 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1908 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1909 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1910 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1911 contents: unsigned_announcement.clone(),
1913 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1914 Ok(res) => assert!(res),
1919 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1920 let unsigned_announcement = UnsignedNodeAnnouncement {
1921 features: NodeFeatures::known(),
1926 addresses: Vec::new(),
1927 excess_address_data: Vec::new(),
1928 excess_data: Vec::new(),
1930 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1931 let valid_announcement = NodeAnnouncement {
1932 signature: secp_ctx.sign(&msghash, node_1_privkey),
1933 contents: unsigned_announcement.clone()
1936 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1941 let network = net_graph_msg_handler.network_graph.write().unwrap();
1942 let mut w = test_utils::TestVecWriter(Vec::new());
1943 assert!(!network.get_nodes().is_empty());
1944 assert!(!network.get_channels().is_empty());
1945 network.write(&mut w).unwrap();
1946 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1950 fn calling_sync_routing_table() {
1951 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1952 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1953 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
1955 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1956 let first_blocknum = 0;
1957 let number_of_blocks = 0xffff_ffff;
1959 // It should ignore if gossip_queries feature is not enabled
1961 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
1962 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1963 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1964 assert_eq!(events.len(), 0);
1967 // It should send a query_channel_message with the correct information
1969 let init_msg = Init { features: InitFeatures::known() };
1970 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1971 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1972 assert_eq!(events.len(), 1);
1974 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
1975 assert_eq!(node_id, &node_id_1);
1976 assert_eq!(msg.chain_hash, chain_hash);
1977 assert_eq!(msg.first_blocknum, first_blocknum);
1978 assert_eq!(msg.number_of_blocks, number_of_blocks);
1980 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
1984 // It should not enqueue a query when should_request_full_sync return false.
1985 // The initial implementation allows syncing with the first 5 peers after
1986 // which should_request_full_sync will return false
1988 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1989 let init_msg = Init { features: InitFeatures::known() };
1991 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
1992 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1993 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
1994 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1996 assert_eq!(events.len(), 1);
1998 assert_eq!(events.len(), 0);
2006 fn handling_reply_channel_range() {
2007 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2008 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2009 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2011 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2013 // Test receipt of a single reply that should enqueue an SCID query
2014 // matching the SCIDs in the reply
2016 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2018 full_information: true,
2020 number_of_blocks: 2000,
2021 short_channel_ids: vec![
2022 0x0003e0_000000_0000, // 992x0x0
2023 0x0003e8_000000_0000, // 1000x0x0
2024 0x0003e9_000000_0000, // 1001x0x0
2025 0x0003f0_000000_0000, // 1008x0x0
2026 0x00044c_000000_0000, // 1100x0x0
2027 0x0006e0_000000_0000, // 1760x0x0
2030 assert!(result.is_ok());
2032 // We expect to emit a query_short_channel_ids message with the received scids
2033 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2034 assert_eq!(events.len(), 1);
2036 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2037 assert_eq!(node_id, &node_id_1);
2038 assert_eq!(msg.chain_hash, chain_hash);
2039 assert_eq!(msg.short_channel_ids, vec![
2040 0x0003e0_000000_0000, // 992x0x0
2041 0x0003e8_000000_0000, // 1000x0x0
2042 0x0003e9_000000_0000, // 1001x0x0
2043 0x0003f0_000000_0000, // 1008x0x0
2044 0x00044c_000000_0000, // 1100x0x0
2045 0x0006e0_000000_0000, // 1760x0x0
2048 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2052 // Test receipt of a reply that indicates the remote node does not maintain up-to-date
2053 // information for the chain_hash. Because of discrepancies in implementation we use
2054 // full_information=false and short_channel_ids=[] as the signal.
2056 // Handle the reply indicating the peer was unable to fulfill our request.
2057 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2059 full_information: false,
2060 first_blocknum: 1000,
2061 number_of_blocks: 100,
2062 short_channel_ids: vec![],
2064 assert!(result.is_err());
2065 assert_eq!(result.err().unwrap().err, "Received reply_channel_range with no information available");
2070 fn handling_reply_short_channel_ids() {
2071 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2072 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2073 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2075 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2077 // Test receipt of a successful reply
2079 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2081 full_information: true,
2083 assert!(result.is_ok());
2086 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2087 // for the chain_hash requested in the query.
2089 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2091 full_information: false,
2093 assert!(result.is_err());
2094 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2099 fn handling_query_channel_range() {
2100 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2101 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2102 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2104 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2106 let result = net_graph_msg_handler.handle_query_channel_range(&node_id, QueryChannelRange {
2109 number_of_blocks: 0xffff_ffff,
2111 assert!(result.is_err());
2115 fn handling_query_short_channel_ids() {
2116 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2117 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2118 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2120 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2122 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2124 short_channel_ids: vec![0x0003e8_000000_0000],
2126 assert!(result.is_err());