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;
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<events::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 /// Adds a provider used to check new announcements. Does not affect
102 /// existing announcements unless they are updated.
103 /// Add, update or remove the provider would replace the current one.
104 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
105 self.chain_access = chain_access;
108 /// Take a read lock on the network_graph and return it in the C-bindings
109 /// newtype helper. This is likely only useful when called via the C
110 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
112 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
113 LockedNetworkGraph(self.network_graph.read().unwrap())
116 /// Returns true when a full routing table sync should be performed with a peer.
117 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
118 //TODO: Determine whether to request a full sync based on the network map.
119 const FULL_SYNCS_TO_REQUEST: usize = 5;
120 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
121 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
129 impl<'a> LockedNetworkGraph<'a> {
130 /// Get a reference to the NetworkGraph which this read-lock contains.
131 pub fn graph(&self) -> &NetworkGraph {
137 macro_rules! secp_verify_sig {
138 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
139 match $secp_ctx.verify($msg, $sig, $pubkey) {
141 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
146 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
147 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
148 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
149 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty())
152 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
153 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
154 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 { "" });
155 Ok(msg.contents.excess_data.is_empty())
158 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
160 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
161 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
163 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
164 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
166 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
167 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
172 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
173 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
174 Ok(msg.contents.excess_data.is_empty())
177 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
178 let network_graph = self.network_graph.read().unwrap();
179 let mut result = Vec::with_capacity(batch_amount as usize);
180 let mut iter = network_graph.get_channels().range(starting_point..);
181 while result.len() < batch_amount as usize {
182 if let Some((_, ref chan)) = iter.next() {
183 if chan.announcement_message.is_some() {
184 let chan_announcement = chan.announcement_message.clone().unwrap();
185 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
186 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
187 if let Some(one_to_two) = chan.one_to_two.as_ref() {
188 one_to_two_announcement = one_to_two.last_update_message.clone();
190 if let Some(two_to_one) = chan.two_to_one.as_ref() {
191 two_to_one_announcement = two_to_one.last_update_message.clone();
193 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
195 // TODO: We may end up sending un-announced channel_updates if we are sending
196 // initial sync data while receiving announce/updates for this channel.
205 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
206 let network_graph = self.network_graph.read().unwrap();
207 let mut result = Vec::with_capacity(batch_amount as usize);
208 let mut iter = if let Some(pubkey) = starting_point {
209 let mut iter = network_graph.get_nodes().range((*pubkey)..);
213 network_graph.get_nodes().range(..)
215 while result.len() < batch_amount as usize {
216 if let Some((_, ref node)) = iter.next() {
217 if let Some(node_info) = node.announcement_info.as_ref() {
218 if node_info.announcement_message.is_some() {
219 result.push(node_info.announcement_message.clone().unwrap());
229 /// Initiates a stateless sync of routing gossip information with a peer
230 /// using gossip_queries. The default strategy used by this implementation
231 /// is to sync the full block range with several peers.
233 /// We should expect one or more reply_channel_range messages in response
234 /// to our query_channel_range. Each reply will enqueue a query_scid message
235 /// to request gossip messages for each channel. The sync is considered complete
236 /// when the final reply_scids_end message is received, though we are not
237 /// tracking this directly.
238 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
240 // We will only perform a sync with peers that support gossip_queries.
241 if !init_msg.features.supports_gossip_queries() {
245 // Check if we need to perform a full synchronization with this peer
246 if !self.should_request_full_sync(their_node_id) {
250 let first_blocknum = 0;
251 let number_of_blocks = 0xffffffff;
252 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
253 let mut pending_events = self.pending_events.lock().unwrap();
254 pending_events.push(events::MessageSendEvent::SendChannelRangeQuery {
255 node_id: their_node_id.clone(),
256 msg: QueryChannelRange {
257 chain_hash: self.network_graph.read().unwrap().genesis_hash,
264 /// Statelessly processes a reply to a channel range query by immediately
265 /// sending an SCID query with SCIDs in the reply. To keep this handler
266 /// stateless, it does not validate the sequencing of replies for multi-
267 /// reply ranges. It does not validate whether the reply(ies) cover the
268 /// queried range. It also does not filter SCIDs to only those in the
269 /// original query range. We also do not validate that the chain_hash
270 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
271 /// does not match our chain_hash will be rejected when the announcement is
273 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
274 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(),);
276 // Validate that the remote node maintains up-to-date channel
277 // information for chain_hash. Some nodes use the full_information
278 // flag to indicate multi-part messages so we must check whether
279 // we received SCIDs as well.
280 if !msg.full_information && msg.short_channel_ids.len() == 0 {
281 return Err(LightningError {
282 err: String::from("Received reply_channel_range with no information available"),
283 action: ErrorAction::IgnoreError,
287 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
288 let mut pending_events = self.pending_events.lock().unwrap();
289 pending_events.push(events::MessageSendEvent::SendShortIdsQuery {
290 node_id: their_node_id.clone(),
291 msg: QueryShortChannelIds {
292 chain_hash: msg.chain_hash,
293 short_channel_ids: msg.short_channel_ids,
300 /// When an SCID query is initiated the remote peer will begin streaming
301 /// gossip messages. In the event of a failure, we may have received
302 /// some channel information. Before trying with another peer, the
303 /// caller should update its set of SCIDs that need to be queried.
304 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
305 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
307 // If the remote node does not have up-to-date information for the
308 // chain_hash they will set full_information=false. We can fail
309 // the result and try again with a different peer.
310 if !msg.full_information {
311 return Err(LightningError {
312 err: String::from("Received reply_short_channel_ids_end with no information"),
313 action: ErrorAction::IgnoreError
320 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: QueryChannelRange) -> Result<(), LightningError> {
323 err: String::from("Not implemented"),
324 action: ErrorAction::IgnoreError,
328 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
331 err: String::from("Not implemented"),
332 action: ErrorAction::IgnoreError,
337 impl<C: Deref, L: Deref> events::MessageSendEventsProvider for NetGraphMsgHandler<C, L>
339 C::Target: chain::Access,
342 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
343 let mut ret = Vec::new();
344 let mut pending_events = self.pending_events.lock().unwrap();
345 std::mem::swap(&mut ret, &mut pending_events);
350 #[derive(PartialEq, Debug)]
351 /// Details about one direction of a channel. Received
352 /// within a channel update.
353 pub struct DirectionalChannelInfo {
354 /// When the last update to the channel direction was issued.
355 /// Value is opaque, as set in the announcement.
356 pub last_update: u32,
357 /// Whether the channel can be currently used for payments (in this one direction).
359 /// The difference in CLTV values that you must have when routing through this channel.
360 pub cltv_expiry_delta: u16,
361 /// The minimum value, which must be relayed to the next hop via the channel
362 pub htlc_minimum_msat: u64,
363 /// The maximum value which may be relayed to the next hop via the channel.
364 pub htlc_maximum_msat: Option<u64>,
365 /// Fees charged when the channel is used for routing
366 pub fees: RoutingFees,
367 /// Most recent update for the channel received from the network
368 /// Mostly redundant with the data we store in fields explicitly.
369 /// Everything else is useful only for sending out for initial routing sync.
370 /// Not stored if contains excess data to prevent DoS.
371 pub last_update_message: Option<ChannelUpdate>,
374 impl fmt::Display for DirectionalChannelInfo {
375 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
376 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)?;
381 impl_writeable!(DirectionalChannelInfo, 0, {
392 /// Details about a channel (both directions).
393 /// Received within a channel announcement.
394 pub struct ChannelInfo {
395 /// Protocol features of a channel communicated during its announcement
396 pub features: ChannelFeatures,
397 /// Source node of the first direction of a channel
398 pub node_one: PublicKey,
399 /// Details about the first direction of a channel
400 pub one_to_two: Option<DirectionalChannelInfo>,
401 /// Source node of the second direction of a channel
402 pub node_two: PublicKey,
403 /// Details about the second direction of a channel
404 pub two_to_one: Option<DirectionalChannelInfo>,
405 /// The channel capacity as seen on-chain, if chain lookup is available.
406 pub capacity_sats: Option<u64>,
407 /// An initial announcement of the channel
408 /// Mostly redundant with the data we store in fields explicitly.
409 /// Everything else is useful only for sending out for initial routing sync.
410 /// Not stored if contains excess data to prevent DoS.
411 pub announcement_message: Option<ChannelAnnouncement>,
414 impl fmt::Display for ChannelInfo {
415 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
416 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
417 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
422 impl_writeable!(ChannelInfo, 0, {
433 /// Fees for routing via a given channel or a node
434 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
435 pub struct RoutingFees {
436 /// Flat routing fee in satoshis
438 /// Liquidity-based routing fee in millionths of a routed amount.
439 /// In other words, 10000 is 1%.
440 pub proportional_millionths: u32,
443 impl Readable for RoutingFees{
444 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
445 let base_msat: u32 = Readable::read(reader)?;
446 let proportional_millionths: u32 = Readable::read(reader)?;
449 proportional_millionths,
454 impl Writeable for RoutingFees {
455 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
456 self.base_msat.write(writer)?;
457 self.proportional_millionths.write(writer)?;
462 #[derive(PartialEq, Debug)]
463 /// Information received in the latest node_announcement from this node.
464 pub struct NodeAnnouncementInfo {
465 /// Protocol features the node announced support for
466 pub features: NodeFeatures,
467 /// When the last known update to the node state was issued.
468 /// Value is opaque, as set in the announcement.
469 pub last_update: u32,
470 /// Color assigned to the node
472 /// Moniker assigned to the node.
473 /// May be invalid or malicious (eg control chars),
474 /// should not be exposed to the user.
476 /// Internet-level addresses via which one can connect to the node
477 pub addresses: Vec<NetAddress>,
478 /// An initial announcement of the node
479 /// Mostly redundant with the data we store in fields explicitly.
480 /// Everything else is useful only for sending out for initial routing sync.
481 /// Not stored if contains excess data to prevent DoS.
482 pub announcement_message: Option<NodeAnnouncement>
485 impl Writeable for NodeAnnouncementInfo {
486 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
487 self.features.write(writer)?;
488 self.last_update.write(writer)?;
489 self.rgb.write(writer)?;
490 self.alias.write(writer)?;
491 (self.addresses.len() as u64).write(writer)?;
492 for ref addr in &self.addresses {
495 self.announcement_message.write(writer)?;
500 impl Readable for NodeAnnouncementInfo {
501 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
502 let features = Readable::read(reader)?;
503 let last_update = Readable::read(reader)?;
504 let rgb = Readable::read(reader)?;
505 let alias = Readable::read(reader)?;
506 let addresses_count: u64 = Readable::read(reader)?;
507 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
508 for _ in 0..addresses_count {
509 match Readable::read(reader) {
510 Ok(Ok(addr)) => { addresses.push(addr); },
511 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
512 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
516 let announcement_message = Readable::read(reader)?;
517 Ok(NodeAnnouncementInfo {
529 /// Details about a node in the network, known from the network announcement.
530 pub struct NodeInfo {
531 /// All valid channels a node has announced
532 pub channels: Vec<u64>,
533 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
534 /// The two fields (flat and proportional fee) are independent,
535 /// meaning they don't have to refer to the same channel.
536 pub lowest_inbound_channel_fees: Option<RoutingFees>,
537 /// More information about a node from node_announcement.
538 /// Optional because we store a Node entry after learning about it from
539 /// a channel announcement, but before receiving a node announcement.
540 pub announcement_info: Option<NodeAnnouncementInfo>
543 impl fmt::Display for NodeInfo {
544 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
545 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
546 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
551 impl Writeable for NodeInfo {
552 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
553 (self.channels.len() as u64).write(writer)?;
554 for ref chan in self.channels.iter() {
557 self.lowest_inbound_channel_fees.write(writer)?;
558 self.announcement_info.write(writer)?;
563 const MAX_ALLOC_SIZE: u64 = 64*1024;
565 impl Readable for NodeInfo {
566 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
567 let channels_count: u64 = Readable::read(reader)?;
568 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
569 for _ in 0..channels_count {
570 channels.push(Readable::read(reader)?);
572 let lowest_inbound_channel_fees = Readable::read(reader)?;
573 let announcement_info = Readable::read(reader)?;
576 lowest_inbound_channel_fees,
582 impl Writeable for NetworkGraph {
583 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
584 self.genesis_hash.write(writer)?;
585 (self.channels.len() as u64).write(writer)?;
586 for (ref chan_id, ref chan_info) in self.channels.iter() {
587 (*chan_id).write(writer)?;
588 chan_info.write(writer)?;
590 (self.nodes.len() as u64).write(writer)?;
591 for (ref node_id, ref node_info) in self.nodes.iter() {
592 node_id.write(writer)?;
593 node_info.write(writer)?;
599 impl Readable for NetworkGraph {
600 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
601 let genesis_hash: BlockHash = Readable::read(reader)?;
602 let channels_count: u64 = Readable::read(reader)?;
603 let mut channels = BTreeMap::new();
604 for _ in 0..channels_count {
605 let chan_id: u64 = Readable::read(reader)?;
606 let chan_info = Readable::read(reader)?;
607 channels.insert(chan_id, chan_info);
609 let nodes_count: u64 = Readable::read(reader)?;
610 let mut nodes = BTreeMap::new();
611 for _ in 0..nodes_count {
612 let node_id = Readable::read(reader)?;
613 let node_info = Readable::read(reader)?;
614 nodes.insert(node_id, node_info);
624 impl fmt::Display for NetworkGraph {
625 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
626 writeln!(f, "Network map\n[Channels]")?;
627 for (key, val) in self.channels.iter() {
628 writeln!(f, " {}: {}", key, val)?;
630 writeln!(f, "[Nodes]")?;
631 for (key, val) in self.nodes.iter() {
632 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
639 /// Returns all known valid channels' short ids along with announced channel info.
641 /// (C-not exported) because we have no mapping for `BTreeMap`s
642 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
643 /// Returns all known nodes' public keys along with announced node info.
645 /// (C-not exported) because we have no mapping for `BTreeMap`s
646 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
648 /// Get network addresses by node id.
649 /// Returns None if the requested node is completely unknown,
650 /// or if node announcement for the node was never received.
652 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
653 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
654 if let Some(node) = self.nodes.get(pubkey) {
655 if let Some(node_info) = node.announcement_info.as_ref() {
656 return Some(&node_info.addresses)
662 /// Creates a new, empty, network graph.
663 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
666 channels: BTreeMap::new(),
667 nodes: BTreeMap::new(),
671 /// For an already known node (from channel announcements), update its stored properties from a
672 /// given node announcement.
674 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
675 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
676 /// routing messages from a source using a protocol other than the lightning P2P protocol.
677 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
678 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
679 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
680 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
683 /// For an already known node (from channel announcements), update its stored properties from a
684 /// given node announcement without verifying the associated signatures. Because we aren't
685 /// given the associated signatures here we cannot relay the node announcement to any of our
687 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
688 self.update_node_from_announcement_intern(msg, None)
691 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
692 match self.nodes.get_mut(&msg.node_id) {
693 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
695 if let Some(node_info) = node.announcement_info.as_ref() {
696 if node_info.last_update >= msg.timestamp {
697 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
701 let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
702 node.announcement_info = Some(NodeAnnouncementInfo {
703 features: msg.features.clone(),
704 last_update: msg.timestamp,
707 addresses: msg.addresses.clone(),
708 announcement_message: if should_relay { full_msg.cloned() } else { None },
716 /// Store or update channel info from a channel announcement.
718 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
719 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
720 /// routing messages from a source using a protocol other than the lightning P2P protocol.
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_announcement<T: secp256k1::Verification, C: Deref>
725 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
726 -> Result<(), LightningError>
727 where C::Target: chain::Access {
728 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
729 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
730 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
731 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
732 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
733 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
736 /// Store or update channel info from a channel announcement without verifying the associated
737 /// signatures. Because we aren't given the associated signatures here we cannot relay the
738 /// channel announcement to any of our peers.
740 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
741 /// the corresponding UTXO exists on chain and is correctly-formatted.
742 pub fn update_channel_from_unsigned_announcement<C: Deref>
743 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
744 -> Result<(), LightningError>
745 where C::Target: chain::Access {
746 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
749 fn update_channel_from_unsigned_announcement_intern<C: Deref>
750 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
751 -> Result<(), LightningError>
752 where C::Target: chain::Access {
753 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
754 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
757 let utxo_value = match &chain_access {
759 // Tentatively accept, potentially exposing us to DoS attacks
762 &Some(ref chain_access) => {
763 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
764 Ok(TxOut { value, script_pubkey }) => {
765 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
766 .push_slice(&msg.bitcoin_key_1.serialize())
767 .push_slice(&msg.bitcoin_key_2.serialize())
768 .push_opcode(opcodes::all::OP_PUSHNUM_2)
769 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
770 if script_pubkey != expected_script {
771 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});
773 //TODO: Check if value is worth storing, use it to inform routing, and compare it
774 //to the new HTLC max field in channel_update
777 Err(chain::AccessError::UnknownChain) => {
778 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
780 Err(chain::AccessError::UnknownTx) => {
781 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
787 let chan_info = ChannelInfo {
788 features: msg.features.clone(),
789 node_one: msg.node_id_1.clone(),
791 node_two: msg.node_id_2.clone(),
793 capacity_sats: utxo_value,
794 announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
797 match self.channels.entry(msg.short_channel_id) {
798 BtreeEntry::Occupied(mut entry) => {
799 //TODO: because asking the blockchain if short_channel_id is valid is only optional
800 //in the blockchain API, we need to handle it smartly here, though it's unclear
802 if utxo_value.is_some() {
803 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
804 // only sometimes returns results. In any case remove the previous entry. Note
805 // that the spec expects us to "blacklist" the node_ids involved, but we can't
807 // a) we don't *require* a UTXO provider that always returns results.
808 // b) we don't track UTXOs of channels we know about and remove them if they
810 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
811 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
812 *entry.get_mut() = chan_info;
814 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
817 BtreeEntry::Vacant(entry) => {
818 entry.insert(chan_info);
822 macro_rules! add_channel_to_node {
823 ( $node_id: expr ) => {
824 match self.nodes.entry($node_id) {
825 BtreeEntry::Occupied(node_entry) => {
826 node_entry.into_mut().channels.push(msg.short_channel_id);
828 BtreeEntry::Vacant(node_entry) => {
829 node_entry.insert(NodeInfo {
830 channels: vec!(msg.short_channel_id),
831 lowest_inbound_channel_fees: None,
832 announcement_info: None,
839 add_channel_to_node!(msg.node_id_1);
840 add_channel_to_node!(msg.node_id_2);
845 /// Close a channel if a corresponding HTLC fail was sent.
846 /// If permanent, removes a channel from the local storage.
847 /// May cause the removal of nodes too, if this was their last channel.
848 /// If not permanent, makes channels unavailable for routing.
849 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
851 if let Some(chan) = self.channels.remove(&short_channel_id) {
852 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
855 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
856 if let Some(one_to_two) = chan.one_to_two.as_mut() {
857 one_to_two.enabled = false;
859 if let Some(two_to_one) = chan.two_to_one.as_mut() {
860 two_to_one.enabled = false;
866 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
868 // TODO: Wholly remove the node
870 // TODO: downgrade the node
874 /// For an already known (from announcement) channel, update info about one of the directions
877 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
878 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
879 /// routing messages from a source using a protocol other than the lightning P2P protocol.
880 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
881 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
884 /// For an already known (from announcement) channel, update info about one of the directions
885 /// of the channel without verifying the associated signatures. Because we aren't given the
886 /// associated signatures here we cannot relay the channel update to any of our peers.
887 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
888 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
891 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> {
893 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
894 let chan_was_enabled;
896 match self.channels.get_mut(&msg.short_channel_id) {
897 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
899 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
900 if htlc_maximum_msat > MAX_VALUE_MSAT {
901 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
904 if let Some(capacity_sats) = channel.capacity_sats {
905 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
906 // Don't query UTXO set here to reduce DoS risks.
907 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
908 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
912 macro_rules! maybe_update_channel_info {
913 ( $target: expr, $src_node: expr) => {
914 if let Some(existing_chan_info) = $target.as_ref() {
915 if existing_chan_info.last_update >= msg.timestamp {
916 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
918 chan_was_enabled = existing_chan_info.enabled;
920 chan_was_enabled = false;
923 let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
925 let updated_channel_dir_info = DirectionalChannelInfo {
926 enabled: chan_enabled,
927 last_update: msg.timestamp,
928 cltv_expiry_delta: msg.cltv_expiry_delta,
929 htlc_minimum_msat: msg.htlc_minimum_msat,
930 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
932 base_msat: msg.fee_base_msat,
933 proportional_millionths: msg.fee_proportional_millionths,
937 $target = Some(updated_channel_dir_info);
941 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
942 if msg.flags & 1 == 1 {
943 dest_node_id = channel.node_one.clone();
944 if let Some((sig, ctx)) = sig_info {
945 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
947 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
949 dest_node_id = channel.node_two.clone();
950 if let Some((sig, ctx)) = sig_info {
951 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
953 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
959 let node = self.nodes.get_mut(&dest_node_id).unwrap();
960 let mut base_msat = msg.fee_base_msat;
961 let mut proportional_millionths = msg.fee_proportional_millionths;
962 if let Some(fees) = node.lowest_inbound_channel_fees {
963 base_msat = cmp::min(base_msat, fees.base_msat);
964 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
966 node.lowest_inbound_channel_fees = Some(RoutingFees {
968 proportional_millionths
970 } else if chan_was_enabled {
971 let node = self.nodes.get_mut(&dest_node_id).unwrap();
972 let mut lowest_inbound_channel_fees = None;
974 for chan_id in node.channels.iter() {
975 let chan = self.channels.get(chan_id).unwrap();
977 if chan.node_one == dest_node_id {
978 chan_info_opt = chan.two_to_one.as_ref();
980 chan_info_opt = chan.one_to_two.as_ref();
982 if let Some(chan_info) = chan_info_opt {
983 if chan_info.enabled {
984 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
985 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
986 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
987 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
992 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
998 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
999 macro_rules! remove_from_node {
1000 ($node_id: expr) => {
1001 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1002 entry.get_mut().channels.retain(|chan_id| {
1003 short_channel_id != *chan_id
1005 if entry.get().channels.is_empty() {
1006 entry.remove_entry();
1009 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1014 remove_from_node!(chan.node_one);
1015 remove_from_node!(chan.node_two);
1022 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1023 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
1024 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1025 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1026 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1027 use util::test_utils;
1028 use util::logger::Logger;
1029 use util::ser::{Readable, Writeable};
1030 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1032 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1033 use bitcoin::hashes::Hash;
1034 use bitcoin::network::constants::Network;
1035 use bitcoin::blockdata::constants::genesis_block;
1036 use bitcoin::blockdata::script::Builder;
1037 use bitcoin::blockdata::transaction::TxOut;
1038 use bitcoin::blockdata::opcodes;
1042 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1043 use bitcoin::secp256k1::{All, Secp256k1};
1047 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1048 let secp_ctx = Secp256k1::new();
1049 let logger = Arc::new(test_utils::TestLogger::new());
1050 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1051 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1052 (secp_ctx, net_graph_msg_handler)
1056 fn request_full_sync_finite_times() {
1057 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1058 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1060 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1061 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1062 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1063 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1064 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1065 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1069 fn handling_node_announcements() {
1070 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1072 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1073 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1074 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1075 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1076 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1077 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1078 let zero_hash = Sha256dHash::hash(&[0; 32]);
1079 let first_announcement_time = 500;
1081 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1082 features: NodeFeatures::known(),
1083 timestamp: first_announcement_time,
1087 addresses: Vec::new(),
1088 excess_address_data: Vec::new(),
1089 excess_data: Vec::new(),
1091 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1092 let valid_announcement = NodeAnnouncement {
1093 signature: secp_ctx.sign(&msghash, node_1_privkey),
1094 contents: unsigned_announcement.clone()
1097 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1099 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1103 // Announce a channel to add a corresponding node.
1104 let unsigned_announcement = UnsignedChannelAnnouncement {
1105 features: ChannelFeatures::known(),
1106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1107 short_channel_id: 0,
1110 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1111 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1112 excess_data: Vec::new(),
1115 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1116 let valid_announcement = ChannelAnnouncement {
1117 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1118 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1119 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1120 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1121 contents: unsigned_announcement.clone(),
1123 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1124 Ok(res) => assert!(res),
1129 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1130 Ok(res) => assert!(res),
1134 let fake_msghash = hash_to_message!(&zero_hash);
1135 match net_graph_msg_handler.handle_node_announcement(
1137 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1138 contents: unsigned_announcement.clone()
1141 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1144 unsigned_announcement.timestamp += 1000;
1145 unsigned_announcement.excess_data.push(1);
1146 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1147 let announcement_with_data = NodeAnnouncement {
1148 signature: secp_ctx.sign(&msghash, node_1_privkey),
1149 contents: unsigned_announcement.clone()
1151 // Return false because contains excess data.
1152 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1153 Ok(res) => assert!(!res),
1156 unsigned_announcement.excess_data = Vec::new();
1158 // Even though previous announcement was not relayed further, we still accepted it,
1159 // so we now won't accept announcements before the previous one.
1160 unsigned_announcement.timestamp -= 10;
1161 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1162 let outdated_announcement = NodeAnnouncement {
1163 signature: secp_ctx.sign(&msghash, node_1_privkey),
1164 contents: unsigned_announcement.clone()
1166 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1168 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1173 fn handling_channel_announcements() {
1174 let secp_ctx = Secp256k1::new();
1175 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1177 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1178 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1179 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1180 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1181 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1182 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1184 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1185 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1186 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1187 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1188 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1191 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1192 features: ChannelFeatures::known(),
1193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1194 short_channel_id: 0,
1197 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1198 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1199 excess_data: Vec::new(),
1202 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1203 let valid_announcement = ChannelAnnouncement {
1204 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1205 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1206 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1207 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1208 contents: unsigned_announcement.clone(),
1211 // Test if the UTXO lookups were not supported
1212 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1213 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1214 Ok(res) => assert!(res),
1219 let network = net_graph_msg_handler.network_graph.read().unwrap();
1220 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1226 // If we receive announcement for the same channel (with UTXO lookups disabled),
1227 // drop new one on the floor, since we can't see any changes.
1228 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1230 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1233 // Test if an associated transaction were not on-chain (or not confirmed).
1234 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1235 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1236 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1237 unsigned_announcement.short_channel_id += 1;
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(),
1248 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1250 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1253 // Now test if the transaction is found in the UTXO set and the script is correct.
1254 unsigned_announcement.short_channel_id += 1;
1255 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1257 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1258 let valid_announcement = ChannelAnnouncement {
1259 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1260 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1261 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1262 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1263 contents: unsigned_announcement.clone(),
1265 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1266 Ok(res) => assert!(res),
1271 let network = net_graph_msg_handler.network_graph.read().unwrap();
1272 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1278 // If we receive announcement for the same channel (but TX is not confirmed),
1279 // drop new one on the floor, since we can't see any changes.
1280 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1281 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1283 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1286 // But if it is confirmed, replace the channel
1287 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1288 unsigned_announcement.features = ChannelFeatures::empty();
1289 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1290 let valid_announcement = ChannelAnnouncement {
1291 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1292 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1293 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1294 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1295 contents: unsigned_announcement.clone(),
1297 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1298 Ok(res) => assert!(res),
1302 let network = net_graph_msg_handler.network_graph.read().unwrap();
1303 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1304 Some(channel_entry) => {
1305 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1311 // Don't relay valid channels with excess data
1312 unsigned_announcement.short_channel_id += 1;
1313 unsigned_announcement.excess_data.push(1);
1314 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1315 let valid_announcement = ChannelAnnouncement {
1316 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1317 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1318 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1319 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1320 contents: unsigned_announcement.clone(),
1322 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1323 Ok(res) => assert!(!res),
1327 unsigned_announcement.excess_data = Vec::new();
1328 let invalid_sig_announcement = ChannelAnnouncement {
1329 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1330 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1331 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1332 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1333 contents: unsigned_announcement.clone(),
1335 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1337 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1340 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1341 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1342 let channel_to_itself_announcement = ChannelAnnouncement {
1343 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1344 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1345 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1346 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1347 contents: unsigned_announcement.clone(),
1349 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1351 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1356 fn handling_channel_update() {
1357 let secp_ctx = Secp256k1::new();
1358 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1359 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1360 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1362 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1363 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1364 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1365 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1366 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1367 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1369 let zero_hash = Sha256dHash::hash(&[0; 32]);
1370 let short_channel_id = 0;
1371 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1372 let amount_sats = 1000_000;
1375 // Announce a channel we will update
1376 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1377 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1378 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1379 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1380 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1381 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1382 let unsigned_announcement = UnsignedChannelAnnouncement {
1383 features: ChannelFeatures::empty(),
1388 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1389 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1390 excess_data: Vec::new(),
1393 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1394 let valid_channel_announcement = ChannelAnnouncement {
1395 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1396 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1397 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1398 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1399 contents: unsigned_announcement.clone(),
1401 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1408 let mut unsigned_channel_update = UnsignedChannelUpdate {
1413 cltv_expiry_delta: 144,
1414 htlc_minimum_msat: 1000000,
1415 htlc_maximum_msat: OptionalField::Absent,
1416 fee_base_msat: 10000,
1417 fee_proportional_millionths: 20,
1418 excess_data: Vec::new()
1420 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1421 let valid_channel_update = ChannelUpdate {
1422 signature: secp_ctx.sign(&msghash, node_1_privkey),
1423 contents: unsigned_channel_update.clone()
1426 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1427 Ok(res) => assert!(res),
1432 let network = net_graph_msg_handler.network_graph.read().unwrap();
1433 match network.get_channels().get(&short_channel_id) {
1435 Some(channel_info) => {
1436 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1437 assert!(channel_info.two_to_one.is_none());
1442 unsigned_channel_update.timestamp += 100;
1443 unsigned_channel_update.excess_data.push(1);
1444 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1445 let valid_channel_update = ChannelUpdate {
1446 signature: secp_ctx.sign(&msghash, node_1_privkey),
1447 contents: unsigned_channel_update.clone()
1449 // Return false because contains excess data
1450 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1451 Ok(res) => assert!(!res),
1454 unsigned_channel_update.timestamp += 10;
1456 unsigned_channel_update.short_channel_id += 1;
1457 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1458 let valid_channel_update = ChannelUpdate {
1459 signature: secp_ctx.sign(&msghash, node_1_privkey),
1460 contents: unsigned_channel_update.clone()
1463 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1465 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1467 unsigned_channel_update.short_channel_id = short_channel_id;
1469 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1470 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1471 let valid_channel_update = ChannelUpdate {
1472 signature: secp_ctx.sign(&msghash, node_1_privkey),
1473 contents: unsigned_channel_update.clone()
1476 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1478 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1480 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1482 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1483 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1484 let valid_channel_update = ChannelUpdate {
1485 signature: secp_ctx.sign(&msghash, node_1_privkey),
1486 contents: unsigned_channel_update.clone()
1489 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1491 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1493 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1495 // Even though previous update was not relayed further, we still accepted it,
1496 // so we now won't accept update before the previous one.
1497 unsigned_channel_update.timestamp -= 10;
1498 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1499 let valid_channel_update = ChannelUpdate {
1500 signature: secp_ctx.sign(&msghash, node_1_privkey),
1501 contents: unsigned_channel_update.clone()
1504 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1506 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1508 unsigned_channel_update.timestamp += 500;
1510 let fake_msghash = hash_to_message!(&zero_hash);
1511 let invalid_sig_channel_update = ChannelUpdate {
1512 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1513 contents: unsigned_channel_update.clone()
1516 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1518 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1524 fn handling_htlc_fail_channel_update() {
1525 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1526 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1527 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1528 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1529 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1530 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1531 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1533 let short_channel_id = 0;
1534 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1537 // There is no nodes in the table at the beginning.
1538 let network = net_graph_msg_handler.network_graph.read().unwrap();
1539 assert_eq!(network.get_nodes().len(), 0);
1543 // Announce a channel we will update
1544 let unsigned_announcement = UnsignedChannelAnnouncement {
1545 features: ChannelFeatures::empty(),
1550 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1551 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1552 excess_data: Vec::new(),
1555 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1556 let valid_channel_announcement = ChannelAnnouncement {
1557 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1558 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1559 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1560 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1561 contents: unsigned_announcement.clone(),
1563 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1568 let unsigned_channel_update = UnsignedChannelUpdate {
1573 cltv_expiry_delta: 144,
1574 htlc_minimum_msat: 1000000,
1575 htlc_maximum_msat: OptionalField::Absent,
1576 fee_base_msat: 10000,
1577 fee_proportional_millionths: 20,
1578 excess_data: Vec::new()
1580 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1581 let valid_channel_update = ChannelUpdate {
1582 signature: secp_ctx.sign(&msghash, node_1_privkey),
1583 contents: unsigned_channel_update.clone()
1586 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1587 Ok(res) => assert!(res),
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.is_some());
1603 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1608 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1610 // Non-permanent closing just disables a channel
1612 let network = net_graph_msg_handler.network_graph.read().unwrap();
1613 match network.get_channels().get(&short_channel_id) {
1615 Some(channel_info) => {
1616 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1621 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1626 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1628 // Permanent closing deletes a channel
1630 let network = net_graph_msg_handler.network_graph.read().unwrap();
1631 assert_eq!(network.get_channels().len(), 0);
1632 // Nodes are also deleted because there are no associated channels anymore
1633 assert_eq!(network.get_nodes().len(), 0);
1635 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1639 fn getting_next_channel_announcements() {
1640 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1641 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1642 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1643 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1644 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1645 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1646 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1648 let short_channel_id = 1;
1649 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1651 // Channels were not announced yet.
1652 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1653 assert_eq!(channels_with_announcements.len(), 0);
1656 // Announce a channel we will update
1657 let unsigned_announcement = UnsignedChannelAnnouncement {
1658 features: ChannelFeatures::empty(),
1663 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1664 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1665 excess_data: Vec::new(),
1668 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1669 let valid_channel_announcement = ChannelAnnouncement {
1670 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1671 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1672 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1673 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1674 contents: unsigned_announcement.clone(),
1676 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1682 // Contains initial channel announcement now.
1683 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1684 assert_eq!(channels_with_announcements.len(), 1);
1685 if let Some(channel_announcements) = channels_with_announcements.first() {
1686 let &(_, ref update_1, ref update_2) = channel_announcements;
1687 assert_eq!(update_1, &None);
1688 assert_eq!(update_2, &None);
1695 // Valid channel update
1696 let unsigned_channel_update = UnsignedChannelUpdate {
1701 cltv_expiry_delta: 144,
1702 htlc_minimum_msat: 1000000,
1703 htlc_maximum_msat: OptionalField::Absent,
1704 fee_base_msat: 10000,
1705 fee_proportional_millionths: 20,
1706 excess_data: Vec::new()
1708 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1709 let valid_channel_update = ChannelUpdate {
1710 signature: secp_ctx.sign(&msghash, node_1_privkey),
1711 contents: unsigned_channel_update.clone()
1713 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1719 // Now contains an initial announcement and an update.
1720 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1721 assert_eq!(channels_with_announcements.len(), 1);
1722 if let Some(channel_announcements) = channels_with_announcements.first() {
1723 let &(_, ref update_1, ref update_2) = channel_announcements;
1724 assert_ne!(update_1, &None);
1725 assert_eq!(update_2, &None);
1732 // Channel update with excess data.
1733 let unsigned_channel_update = UnsignedChannelUpdate {
1738 cltv_expiry_delta: 144,
1739 htlc_minimum_msat: 1000000,
1740 htlc_maximum_msat: OptionalField::Absent,
1741 fee_base_msat: 10000,
1742 fee_proportional_millionths: 20,
1743 excess_data: [1; 3].to_vec()
1745 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1746 let valid_channel_update = ChannelUpdate {
1747 signature: secp_ctx.sign(&msghash, node_1_privkey),
1748 contents: unsigned_channel_update.clone()
1750 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1756 // Test that announcements with excess data won't be returned
1757 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1758 assert_eq!(channels_with_announcements.len(), 1);
1759 if let Some(channel_announcements) = channels_with_announcements.first() {
1760 let &(_, ref update_1, ref update_2) = channel_announcements;
1761 assert_eq!(update_1, &None);
1762 assert_eq!(update_2, &None);
1767 // Further starting point have no channels after it
1768 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1769 assert_eq!(channels_with_announcements.len(), 0);
1773 fn getting_next_node_announcements() {
1774 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1775 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1776 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1777 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1778 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1779 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1780 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1782 let short_channel_id = 1;
1783 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1786 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1787 assert_eq!(next_announcements.len(), 0);
1790 // Announce a channel to add 2 nodes
1791 let unsigned_announcement = UnsignedChannelAnnouncement {
1792 features: ChannelFeatures::empty(),
1797 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1798 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1799 excess_data: Vec::new(),
1802 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1803 let valid_channel_announcement = ChannelAnnouncement {
1804 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1805 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1806 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1807 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1808 contents: unsigned_announcement.clone(),
1810 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1817 // Nodes were never announced
1818 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1819 assert_eq!(next_announcements.len(), 0);
1822 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1823 features: NodeFeatures::known(),
1828 addresses: Vec::new(),
1829 excess_address_data: Vec::new(),
1830 excess_data: Vec::new(),
1832 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1833 let valid_announcement = NodeAnnouncement {
1834 signature: secp_ctx.sign(&msghash, node_1_privkey),
1835 contents: unsigned_announcement.clone()
1837 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1842 unsigned_announcement.node_id = node_id_2;
1843 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1844 let valid_announcement = NodeAnnouncement {
1845 signature: secp_ctx.sign(&msghash, node_2_privkey),
1846 contents: unsigned_announcement.clone()
1849 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1855 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1856 assert_eq!(next_announcements.len(), 2);
1858 // Skip the first node.
1859 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1860 assert_eq!(next_announcements.len(), 1);
1863 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1864 let unsigned_announcement = UnsignedNodeAnnouncement {
1865 features: NodeFeatures::known(),
1870 addresses: Vec::new(),
1871 excess_address_data: Vec::new(),
1872 excess_data: [1; 3].to_vec(),
1874 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1875 let valid_announcement = NodeAnnouncement {
1876 signature: secp_ctx.sign(&msghash, node_2_privkey),
1877 contents: unsigned_announcement.clone()
1879 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1880 Ok(res) => assert!(!res),
1885 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1886 assert_eq!(next_announcements.len(), 0);
1890 fn network_graph_serialization() {
1891 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1893 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1894 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1895 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1896 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1898 // Announce a channel to add a corresponding node.
1899 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1900 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1901 let unsigned_announcement = UnsignedChannelAnnouncement {
1902 features: ChannelFeatures::known(),
1903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1904 short_channel_id: 0,
1907 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1908 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1909 excess_data: Vec::new(),
1912 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1913 let valid_announcement = ChannelAnnouncement {
1914 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1915 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1916 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1917 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1918 contents: unsigned_announcement.clone(),
1920 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1921 Ok(res) => assert!(res),
1926 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1927 let unsigned_announcement = UnsignedNodeAnnouncement {
1928 features: NodeFeatures::known(),
1933 addresses: Vec::new(),
1934 excess_address_data: Vec::new(),
1935 excess_data: Vec::new(),
1937 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1938 let valid_announcement = NodeAnnouncement {
1939 signature: secp_ctx.sign(&msghash, node_1_privkey),
1940 contents: unsigned_announcement.clone()
1943 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1948 let network = net_graph_msg_handler.network_graph.write().unwrap();
1949 let mut w = test_utils::TestVecWriter(Vec::new());
1950 assert!(!network.get_nodes().is_empty());
1951 assert!(!network.get_channels().is_empty());
1952 network.write(&mut w).unwrap();
1953 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1957 fn calling_sync_routing_table() {
1958 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1959 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1960 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
1962 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1963 let first_blocknum = 0;
1964 let number_of_blocks = 0xffff_ffff;
1966 // It should ignore if gossip_queries feature is not enabled
1968 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
1969 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1970 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1971 assert_eq!(events.len(), 0);
1974 // It should send a query_channel_message with the correct information
1976 let init_msg = Init { features: InitFeatures::known() };
1977 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1978 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1979 assert_eq!(events.len(), 1);
1981 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
1982 assert_eq!(node_id, &node_id_1);
1983 assert_eq!(msg.chain_hash, chain_hash);
1984 assert_eq!(msg.first_blocknum, first_blocknum);
1985 assert_eq!(msg.number_of_blocks, number_of_blocks);
1987 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
1991 // It should not enqueue a query when should_request_full_sync return false.
1992 // The initial implementation allows syncing with the first 5 peers after
1993 // which should_request_full_sync will return false
1995 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1996 let init_msg = Init { features: InitFeatures::known() };
1998 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
1999 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2000 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2001 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2003 assert_eq!(events.len(), 1);
2005 assert_eq!(events.len(), 0);
2013 fn handling_reply_channel_range() {
2014 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2015 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2016 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2018 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2020 // Test receipt of a single reply that should enqueue an SCID query
2021 // matching the SCIDs in the reply
2023 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2025 full_information: true,
2027 number_of_blocks: 2000,
2028 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 assert!(result.is_ok());
2039 // We expect to emit a query_short_channel_ids message with the received scids
2040 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2041 assert_eq!(events.len(), 1);
2043 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2044 assert_eq!(node_id, &node_id_1);
2045 assert_eq!(msg.chain_hash, chain_hash);
2046 assert_eq!(msg.short_channel_ids, vec![
2047 0x0003e0_000000_0000, // 992x0x0
2048 0x0003e8_000000_0000, // 1000x0x0
2049 0x0003e9_000000_0000, // 1001x0x0
2050 0x0003f0_000000_0000, // 1008x0x0
2051 0x00044c_000000_0000, // 1100x0x0
2052 0x0006e0_000000_0000, // 1760x0x0
2055 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2059 // Test receipt of a reply that indicates the remote node does not maintain up-to-date
2060 // information for the chain_hash. Because of discrepancies in implementation we use
2061 // full_information=false and short_channel_ids=[] as the signal.
2063 // Handle the reply indicating the peer was unable to fulfill our request.
2064 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2066 full_information: false,
2067 first_blocknum: 1000,
2068 number_of_blocks: 100,
2069 short_channel_ids: vec![],
2071 assert!(result.is_err());
2072 assert_eq!(result.err().unwrap().err, "Received reply_channel_range with no information available");
2077 fn handling_reply_short_channel_ids() {
2078 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2079 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2080 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2082 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2084 // Test receipt of a successful reply
2086 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2088 full_information: true,
2090 assert!(result.is_ok());
2093 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2094 // for the chain_hash requested in the query.
2096 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2098 full_information: false,
2100 assert!(result.is_err());
2101 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2106 fn handling_query_channel_range() {
2107 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2108 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2109 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2111 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2113 let result = net_graph_msg_handler.handle_query_channel_range(&node_id, QueryChannelRange {
2116 number_of_blocks: 0xffff_ffff,
2118 assert!(result.is_err());
2122 fn handling_query_short_channel_ids() {
2123 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2124 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2125 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2127 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2129 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2131 short_channel_ids: vec![0x0003e8_000000_0000],
2133 assert!(result.is_err());