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 /// 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())
110 impl<'a> LockedNetworkGraph<'a> {
111 /// Get a reference to the NetworkGraph which this read-lock contains.
112 pub fn graph(&self) -> &NetworkGraph {
118 macro_rules! secp_verify_sig {
119 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
120 match $secp_ctx.verify($msg, $sig, $pubkey) {
122 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
127 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
128 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
129 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
130 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty())
133 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
134 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
135 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 { "" });
136 Ok(msg.contents.excess_data.is_empty())
139 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
141 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
142 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
144 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
145 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
147 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
148 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
153 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
154 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
155 Ok(msg.contents.excess_data.is_empty())
158 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
159 let network_graph = self.network_graph.read().unwrap();
160 let mut result = Vec::with_capacity(batch_amount as usize);
161 let mut iter = network_graph.get_channels().range(starting_point..);
162 while result.len() < batch_amount as usize {
163 if let Some((_, ref chan)) = iter.next() {
164 if chan.announcement_message.is_some() {
165 let chan_announcement = chan.announcement_message.clone().unwrap();
166 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
167 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
168 if let Some(one_to_two) = chan.one_to_two.as_ref() {
169 one_to_two_announcement = one_to_two.last_update_message.clone();
171 if let Some(two_to_one) = chan.two_to_one.as_ref() {
172 two_to_one_announcement = two_to_one.last_update_message.clone();
174 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
176 // TODO: We may end up sending un-announced channel_updates if we are sending
177 // initial sync data while receiving announce/updates for this channel.
186 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
187 let network_graph = self.network_graph.read().unwrap();
188 let mut result = Vec::with_capacity(batch_amount as usize);
189 let mut iter = if let Some(pubkey) = starting_point {
190 let mut iter = network_graph.get_nodes().range((*pubkey)..);
194 network_graph.get_nodes().range(..)
196 while result.len() < batch_amount as usize {
197 if let Some((_, ref node)) = iter.next() {
198 if let Some(node_info) = node.announcement_info.as_ref() {
199 if node_info.announcement_message.is_some() {
200 result.push(node_info.announcement_message.clone().unwrap());
210 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
211 //TODO: Determine whether to request a full sync based on the network map.
212 const FULL_SYNCS_TO_REQUEST: usize = 5;
213 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
214 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
221 /// Initiates a stateless sync of routing gossip information with a peer
222 /// by calling query_channel_range. The default strategy used by this
223 /// implementation is to sync for the full block range with several peers.
224 /// We should expect one or more reply_channel_range messages in response
225 /// to our query. Each reply will enqueue a query_scid message to request
226 /// gossip messages for each channel. The sync is considered complete when
227 /// the final reply_scids_end message is received, though we are not
228 /// tracking this directly.
229 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
230 if !init_msg.features.supports_gossip_queries() {
233 let first_blocknum = 0;
234 let number_of_blocks = 0xffffffff;
235 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
236 let mut pending_events = self.pending_events.lock().unwrap();
237 pending_events.push(events::MessageSendEvent::SendChannelRangeQuery {
238 node_id: their_node_id.clone(),
239 msg: QueryChannelRange {
240 chain_hash: self.network_graph.read().unwrap().genesis_hash,
247 /// Statelessly processes a reply to a channel range query by immediately
248 /// sending an SCID query with SCIDs in the reply. To keep this handler
249 /// stateless, it does not validate the sequencing of replies for multi-
250 /// reply ranges. It does not validate whether the reply(ies) cover the
251 /// queried range. It also does not filter SCIDs to only those in the
252 /// original query range.
253 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
254 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(),);
256 // Validate that the remote node maintains up-to-date channel
257 // information for chain_hash. Some nodes use the full_information
258 // flag to indicate multi-part messages so we must check whether
259 // we received SCIDs as well.
260 if !msg.full_information && msg.short_channel_ids.len() == 0 {
261 return Err(LightningError {
262 err: String::from("Received reply_channel_range with no information available"),
263 action: ErrorAction::IgnoreError,
267 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
268 let mut pending_events = self.pending_events.lock().unwrap();
269 pending_events.push(events::MessageSendEvent::SendShortIdsQuery {
270 node_id: their_node_id.clone(),
271 msg: QueryShortChannelIds {
272 chain_hash: msg.chain_hash,
273 short_channel_ids: msg.short_channel_ids,
280 /// When an SCID query is initiated the remote peer will begin streaming
281 /// gossip messages. In the event of a failure, we may have received
282 /// some channel information. Before trying with another peer, the
283 /// caller should update its set of SCIDs that need to be queried.
284 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
285 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
287 // If the remote node does not have up-to-date information for the
288 // chain_hash they will set full_information=false. We can fail
289 // the result and try again with a different peer.
290 if !msg.full_information {
291 return Err(LightningError {
292 err: String::from("Received reply_short_channel_ids_end with no information"),
293 action: ErrorAction::IgnoreError
300 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: QueryChannelRange) -> Result<(), LightningError> {
303 err: String::from("Not implemented"),
304 action: ErrorAction::IgnoreError,
308 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
311 err: String::from("Not implemented"),
312 action: ErrorAction::IgnoreError,
317 impl<C: Deref, L: Deref> events::MessageSendEventsProvider for NetGraphMsgHandler<C, L>
319 C::Target: chain::Access,
322 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
323 let mut ret = Vec::new();
324 let mut pending_events = self.pending_events.lock().unwrap();
325 std::mem::swap(&mut ret, &mut pending_events);
330 #[derive(PartialEq, Debug)]
331 /// Details about one direction of a channel. Received
332 /// within a channel update.
333 pub struct DirectionalChannelInfo {
334 /// When the last update to the channel direction was issued.
335 /// Value is opaque, as set in the announcement.
336 pub last_update: u32,
337 /// Whether the channel can be currently used for payments (in this one direction).
339 /// The difference in CLTV values that you must have when routing through this channel.
340 pub cltv_expiry_delta: u16,
341 /// The minimum value, which must be relayed to the next hop via the channel
342 pub htlc_minimum_msat: u64,
343 /// The maximum value which may be relayed to the next hop via the channel.
344 pub htlc_maximum_msat: Option<u64>,
345 /// Fees charged when the channel is used for routing
346 pub fees: RoutingFees,
347 /// Most recent update for the channel received from the network
348 /// Mostly redundant with the data we store in fields explicitly.
349 /// Everything else is useful only for sending out for initial routing sync.
350 /// Not stored if contains excess data to prevent DoS.
351 pub last_update_message: Option<ChannelUpdate>,
354 impl fmt::Display for DirectionalChannelInfo {
355 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
356 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)?;
361 impl_writeable!(DirectionalChannelInfo, 0, {
372 /// Details about a channel (both directions).
373 /// Received within a channel announcement.
374 pub struct ChannelInfo {
375 /// Protocol features of a channel communicated during its announcement
376 pub features: ChannelFeatures,
377 /// Source node of the first direction of a channel
378 pub node_one: PublicKey,
379 /// Details about the first direction of a channel
380 pub one_to_two: Option<DirectionalChannelInfo>,
381 /// Source node of the second direction of a channel
382 pub node_two: PublicKey,
383 /// Details about the second direction of a channel
384 pub two_to_one: Option<DirectionalChannelInfo>,
385 /// The channel capacity as seen on-chain, if chain lookup is available.
386 pub capacity_sats: Option<u64>,
387 /// An initial announcement of the channel
388 /// Mostly redundant with the data we store in fields explicitly.
389 /// Everything else is useful only for sending out for initial routing sync.
390 /// Not stored if contains excess data to prevent DoS.
391 pub announcement_message: Option<ChannelAnnouncement>,
394 impl fmt::Display for ChannelInfo {
395 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
396 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
397 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
402 impl_writeable!(ChannelInfo, 0, {
413 /// Fees for routing via a given channel or a node
414 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
415 pub struct RoutingFees {
416 /// Flat routing fee in satoshis
418 /// Liquidity-based routing fee in millionths of a routed amount.
419 /// In other words, 10000 is 1%.
420 pub proportional_millionths: u32,
423 impl Readable for RoutingFees{
424 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
425 let base_msat: u32 = Readable::read(reader)?;
426 let proportional_millionths: u32 = Readable::read(reader)?;
429 proportional_millionths,
434 impl Writeable for RoutingFees {
435 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
436 self.base_msat.write(writer)?;
437 self.proportional_millionths.write(writer)?;
442 #[derive(PartialEq, Debug)]
443 /// Information received in the latest node_announcement from this node.
444 pub struct NodeAnnouncementInfo {
445 /// Protocol features the node announced support for
446 pub features: NodeFeatures,
447 /// When the last known update to the node state was issued.
448 /// Value is opaque, as set in the announcement.
449 pub last_update: u32,
450 /// Color assigned to the node
452 /// Moniker assigned to the node.
453 /// May be invalid or malicious (eg control chars),
454 /// should not be exposed to the user.
456 /// Internet-level addresses via which one can connect to the node
457 pub addresses: Vec<NetAddress>,
458 /// An initial announcement of the node
459 /// Mostly redundant with the data we store in fields explicitly.
460 /// Everything else is useful only for sending out for initial routing sync.
461 /// Not stored if contains excess data to prevent DoS.
462 pub announcement_message: Option<NodeAnnouncement>
465 impl Writeable for NodeAnnouncementInfo {
466 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
467 self.features.write(writer)?;
468 self.last_update.write(writer)?;
469 self.rgb.write(writer)?;
470 self.alias.write(writer)?;
471 (self.addresses.len() as u64).write(writer)?;
472 for ref addr in &self.addresses {
475 self.announcement_message.write(writer)?;
480 impl Readable for NodeAnnouncementInfo {
481 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
482 let features = Readable::read(reader)?;
483 let last_update = Readable::read(reader)?;
484 let rgb = Readable::read(reader)?;
485 let alias = Readable::read(reader)?;
486 let addresses_count: u64 = Readable::read(reader)?;
487 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
488 for _ in 0..addresses_count {
489 match Readable::read(reader) {
490 Ok(Ok(addr)) => { addresses.push(addr); },
491 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
492 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
496 let announcement_message = Readable::read(reader)?;
497 Ok(NodeAnnouncementInfo {
509 /// Details about a node in the network, known from the network announcement.
510 pub struct NodeInfo {
511 /// All valid channels a node has announced
512 pub channels: Vec<u64>,
513 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
514 /// The two fields (flat and proportional fee) are independent,
515 /// meaning they don't have to refer to the same channel.
516 pub lowest_inbound_channel_fees: Option<RoutingFees>,
517 /// More information about a node from node_announcement.
518 /// Optional because we store a Node entry after learning about it from
519 /// a channel announcement, but before receiving a node announcement.
520 pub announcement_info: Option<NodeAnnouncementInfo>
523 impl fmt::Display for NodeInfo {
524 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
525 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
526 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
531 impl Writeable for NodeInfo {
532 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
533 (self.channels.len() as u64).write(writer)?;
534 for ref chan in self.channels.iter() {
537 self.lowest_inbound_channel_fees.write(writer)?;
538 self.announcement_info.write(writer)?;
543 const MAX_ALLOC_SIZE: u64 = 64*1024;
545 impl Readable for NodeInfo {
546 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
547 let channels_count: u64 = Readable::read(reader)?;
548 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
549 for _ in 0..channels_count {
550 channels.push(Readable::read(reader)?);
552 let lowest_inbound_channel_fees = Readable::read(reader)?;
553 let announcement_info = Readable::read(reader)?;
556 lowest_inbound_channel_fees,
562 impl Writeable for NetworkGraph {
563 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
564 self.genesis_hash.write(writer)?;
565 (self.channels.len() as u64).write(writer)?;
566 for (ref chan_id, ref chan_info) in self.channels.iter() {
567 (*chan_id).write(writer)?;
568 chan_info.write(writer)?;
570 (self.nodes.len() as u64).write(writer)?;
571 for (ref node_id, ref node_info) in self.nodes.iter() {
572 node_id.write(writer)?;
573 node_info.write(writer)?;
579 impl Readable for NetworkGraph {
580 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
581 let genesis_hash: BlockHash = Readable::read(reader)?;
582 let channels_count: u64 = Readable::read(reader)?;
583 let mut channels = BTreeMap::new();
584 for _ in 0..channels_count {
585 let chan_id: u64 = Readable::read(reader)?;
586 let chan_info = Readable::read(reader)?;
587 channels.insert(chan_id, chan_info);
589 let nodes_count: u64 = Readable::read(reader)?;
590 let mut nodes = BTreeMap::new();
591 for _ in 0..nodes_count {
592 let node_id = Readable::read(reader)?;
593 let node_info = Readable::read(reader)?;
594 nodes.insert(node_id, node_info);
604 impl fmt::Display for NetworkGraph {
605 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
606 writeln!(f, "Network map\n[Channels]")?;
607 for (key, val) in self.channels.iter() {
608 writeln!(f, " {}: {}", key, val)?;
610 writeln!(f, "[Nodes]")?;
611 for (key, val) in self.nodes.iter() {
612 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
619 /// Returns all known valid channels' short ids along with announced channel info.
621 /// (C-not exported) because we have no mapping for `BTreeMap`s
622 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
623 /// Returns all known nodes' public keys along with announced node info.
625 /// (C-not exported) because we have no mapping for `BTreeMap`s
626 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
628 /// Get network addresses by node id.
629 /// Returns None if the requested node is completely unknown,
630 /// or if node announcement for the node was never received.
632 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
633 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
634 if let Some(node) = self.nodes.get(pubkey) {
635 if let Some(node_info) = node.announcement_info.as_ref() {
636 return Some(&node_info.addresses)
642 /// Creates a new, empty, network graph.
643 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
646 channels: BTreeMap::new(),
647 nodes: BTreeMap::new(),
651 /// For an already known node (from channel announcements), update its stored properties from a
652 /// given node announcement.
654 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
655 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
656 /// routing messages from a source using a protocol other than the lightning P2P protocol.
657 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
658 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
659 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
660 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
663 /// For an already known node (from channel announcements), update its stored properties from a
664 /// given node announcement without verifying the associated signatures. Because we aren't
665 /// given the associated signatures here we cannot relay the node announcement to any of our
667 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
668 self.update_node_from_announcement_intern(msg, None)
671 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
672 match self.nodes.get_mut(&msg.node_id) {
673 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
675 if let Some(node_info) = node.announcement_info.as_ref() {
676 if node_info.last_update >= msg.timestamp {
677 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
681 let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
682 node.announcement_info = Some(NodeAnnouncementInfo {
683 features: msg.features.clone(),
684 last_update: msg.timestamp,
687 addresses: msg.addresses.clone(),
688 announcement_message: if should_relay { full_msg.cloned() } else { None },
696 /// Store or update channel info from a channel announcement.
698 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
699 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
700 /// routing messages from a source using a protocol other than the lightning P2P protocol.
702 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
703 /// the corresponding UTXO exists on chain and is correctly-formatted.
704 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
705 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
706 -> Result<(), LightningError>
707 where C::Target: chain::Access {
708 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
709 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
710 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
711 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
712 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
713 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
716 /// Store or update channel info from a channel announcement without verifying the associated
717 /// signatures. Because we aren't given the associated signatures here we cannot relay the
718 /// channel announcement to any of our peers.
720 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
721 /// the corresponding UTXO exists on chain and is correctly-formatted.
722 pub fn update_channel_from_unsigned_announcement<C: Deref>
723 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
724 -> Result<(), LightningError>
725 where C::Target: chain::Access {
726 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
729 fn update_channel_from_unsigned_announcement_intern<C: Deref>
730 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
731 -> Result<(), LightningError>
732 where C::Target: chain::Access {
733 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
734 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
737 let utxo_value = match &chain_access {
739 // Tentatively accept, potentially exposing us to DoS attacks
742 &Some(ref chain_access) => {
743 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
744 Ok(TxOut { value, script_pubkey }) => {
745 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
746 .push_slice(&msg.bitcoin_key_1.serialize())
747 .push_slice(&msg.bitcoin_key_2.serialize())
748 .push_opcode(opcodes::all::OP_PUSHNUM_2)
749 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
750 if script_pubkey != expected_script {
751 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});
753 //TODO: Check if value is worth storing, use it to inform routing, and compare it
754 //to the new HTLC max field in channel_update
757 Err(chain::AccessError::UnknownChain) => {
758 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
760 Err(chain::AccessError::UnknownTx) => {
761 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
767 let chan_info = ChannelInfo {
768 features: msg.features.clone(),
769 node_one: msg.node_id_1.clone(),
771 node_two: msg.node_id_2.clone(),
773 capacity_sats: utxo_value,
774 announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
777 match self.channels.entry(msg.short_channel_id) {
778 BtreeEntry::Occupied(mut entry) => {
779 //TODO: because asking the blockchain if short_channel_id is valid is only optional
780 //in the blockchain API, we need to handle it smartly here, though it's unclear
782 if utxo_value.is_some() {
783 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
784 // only sometimes returns results. In any case remove the previous entry. Note
785 // that the spec expects us to "blacklist" the node_ids involved, but we can't
787 // a) we don't *require* a UTXO provider that always returns results.
788 // b) we don't track UTXOs of channels we know about and remove them if they
790 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
791 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
792 *entry.get_mut() = chan_info;
794 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
797 BtreeEntry::Vacant(entry) => {
798 entry.insert(chan_info);
802 macro_rules! add_channel_to_node {
803 ( $node_id: expr ) => {
804 match self.nodes.entry($node_id) {
805 BtreeEntry::Occupied(node_entry) => {
806 node_entry.into_mut().channels.push(msg.short_channel_id);
808 BtreeEntry::Vacant(node_entry) => {
809 node_entry.insert(NodeInfo {
810 channels: vec!(msg.short_channel_id),
811 lowest_inbound_channel_fees: None,
812 announcement_info: None,
819 add_channel_to_node!(msg.node_id_1);
820 add_channel_to_node!(msg.node_id_2);
825 /// Close a channel if a corresponding HTLC fail was sent.
826 /// If permanent, removes a channel from the local storage.
827 /// May cause the removal of nodes too, if this was their last channel.
828 /// If not permanent, makes channels unavailable for routing.
829 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
831 if let Some(chan) = self.channels.remove(&short_channel_id) {
832 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
835 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
836 if let Some(one_to_two) = chan.one_to_two.as_mut() {
837 one_to_two.enabled = false;
839 if let Some(two_to_one) = chan.two_to_one.as_mut() {
840 two_to_one.enabled = false;
846 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
848 // TODO: Wholly remove the node
850 // TODO: downgrade the node
854 /// For an already known (from announcement) channel, update info about one of the directions
857 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
858 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
859 /// routing messages from a source using a protocol other than the lightning P2P protocol.
860 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
861 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
864 /// For an already known (from announcement) channel, update info about one of the directions
865 /// of the channel without verifying the associated signatures. Because we aren't given the
866 /// associated signatures here we cannot relay the channel update to any of our peers.
867 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
868 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
871 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> {
873 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
874 let chan_was_enabled;
876 match self.channels.get_mut(&msg.short_channel_id) {
877 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
879 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
880 if htlc_maximum_msat > MAX_VALUE_MSAT {
881 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
884 if let Some(capacity_sats) = channel.capacity_sats {
885 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
886 // Don't query UTXO set here to reduce DoS risks.
887 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
888 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
892 macro_rules! maybe_update_channel_info {
893 ( $target: expr, $src_node: expr) => {
894 if let Some(existing_chan_info) = $target.as_ref() {
895 if existing_chan_info.last_update >= msg.timestamp {
896 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
898 chan_was_enabled = existing_chan_info.enabled;
900 chan_was_enabled = false;
903 let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
905 let updated_channel_dir_info = DirectionalChannelInfo {
906 enabled: chan_enabled,
907 last_update: msg.timestamp,
908 cltv_expiry_delta: msg.cltv_expiry_delta,
909 htlc_minimum_msat: msg.htlc_minimum_msat,
910 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
912 base_msat: msg.fee_base_msat,
913 proportional_millionths: msg.fee_proportional_millionths,
917 $target = Some(updated_channel_dir_info);
921 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
922 if msg.flags & 1 == 1 {
923 dest_node_id = channel.node_one.clone();
924 if let Some((sig, ctx)) = sig_info {
925 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
927 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
929 dest_node_id = channel.node_two.clone();
930 if let Some((sig, ctx)) = sig_info {
931 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
933 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
939 let node = self.nodes.get_mut(&dest_node_id).unwrap();
940 let mut base_msat = msg.fee_base_msat;
941 let mut proportional_millionths = msg.fee_proportional_millionths;
942 if let Some(fees) = node.lowest_inbound_channel_fees {
943 base_msat = cmp::min(base_msat, fees.base_msat);
944 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
946 node.lowest_inbound_channel_fees = Some(RoutingFees {
948 proportional_millionths
950 } else if chan_was_enabled {
951 let node = self.nodes.get_mut(&dest_node_id).unwrap();
952 let mut lowest_inbound_channel_fees = None;
954 for chan_id in node.channels.iter() {
955 let chan = self.channels.get(chan_id).unwrap();
957 if chan.node_one == dest_node_id {
958 chan_info_opt = chan.two_to_one.as_ref();
960 chan_info_opt = chan.one_to_two.as_ref();
962 if let Some(chan_info) = chan_info_opt {
963 if chan_info.enabled {
964 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
965 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
966 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
967 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
972 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
978 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
979 macro_rules! remove_from_node {
980 ($node_id: expr) => {
981 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
982 entry.get_mut().channels.retain(|chan_id| {
983 short_channel_id != *chan_id
985 if entry.get().channels.is_empty() {
986 entry.remove_entry();
989 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
994 remove_from_node!(chan.node_one);
995 remove_from_node!(chan.node_two);
1002 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1003 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
1004 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1005 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1006 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1007 use util::test_utils;
1008 use util::logger::Logger;
1009 use util::ser::{Readable, Writeable};
1010 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1012 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1013 use bitcoin::hashes::Hash;
1014 use bitcoin::network::constants::Network;
1015 use bitcoin::blockdata::constants::genesis_block;
1016 use bitcoin::blockdata::script::Builder;
1017 use bitcoin::blockdata::transaction::TxOut;
1018 use bitcoin::blockdata::opcodes;
1022 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1023 use bitcoin::secp256k1::{All, Secp256k1};
1027 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1028 let secp_ctx = Secp256k1::new();
1029 let logger = Arc::new(test_utils::TestLogger::new());
1030 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1031 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1032 (secp_ctx, net_graph_msg_handler)
1036 fn request_full_sync_finite_times() {
1037 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1038 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1040 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1041 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1042 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1043 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1044 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1045 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1049 fn handling_node_announcements() {
1050 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1052 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1053 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1054 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1055 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1056 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1057 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1058 let zero_hash = Sha256dHash::hash(&[0; 32]);
1059 let first_announcement_time = 500;
1061 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1062 features: NodeFeatures::known(),
1063 timestamp: first_announcement_time,
1067 addresses: Vec::new(),
1068 excess_address_data: Vec::new(),
1069 excess_data: Vec::new(),
1071 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1072 let valid_announcement = NodeAnnouncement {
1073 signature: secp_ctx.sign(&msghash, node_1_privkey),
1074 contents: unsigned_announcement.clone()
1077 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1079 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1083 // Announce a channel to add a corresponding node.
1084 let unsigned_announcement = UnsignedChannelAnnouncement {
1085 features: ChannelFeatures::known(),
1086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1087 short_channel_id: 0,
1090 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1091 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1092 excess_data: Vec::new(),
1095 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1096 let valid_announcement = ChannelAnnouncement {
1097 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1098 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1099 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1100 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1101 contents: unsigned_announcement.clone(),
1103 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1104 Ok(res) => assert!(res),
1109 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1110 Ok(res) => assert!(res),
1114 let fake_msghash = hash_to_message!(&zero_hash);
1115 match net_graph_msg_handler.handle_node_announcement(
1117 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1118 contents: unsigned_announcement.clone()
1121 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1124 unsigned_announcement.timestamp += 1000;
1125 unsigned_announcement.excess_data.push(1);
1126 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1127 let announcement_with_data = NodeAnnouncement {
1128 signature: secp_ctx.sign(&msghash, node_1_privkey),
1129 contents: unsigned_announcement.clone()
1131 // Return false because contains excess data.
1132 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1133 Ok(res) => assert!(!res),
1136 unsigned_announcement.excess_data = Vec::new();
1138 // Even though previous announcement was not relayed further, we still accepted it,
1139 // so we now won't accept announcements before the previous one.
1140 unsigned_announcement.timestamp -= 10;
1141 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1142 let outdated_announcement = NodeAnnouncement {
1143 signature: secp_ctx.sign(&msghash, node_1_privkey),
1144 contents: unsigned_announcement.clone()
1146 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1148 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1153 fn handling_channel_announcements() {
1154 let secp_ctx = Secp256k1::new();
1155 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1157 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1158 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1159 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1160 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1161 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1162 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1164 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1165 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1166 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1167 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1168 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1171 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1172 features: ChannelFeatures::known(),
1173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1174 short_channel_id: 0,
1177 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1178 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1179 excess_data: Vec::new(),
1182 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1183 let valid_announcement = ChannelAnnouncement {
1184 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1185 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1186 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1187 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1188 contents: unsigned_announcement.clone(),
1191 // Test if the UTXO lookups were not supported
1192 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1193 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1194 Ok(res) => assert!(res),
1199 let network = net_graph_msg_handler.network_graph.read().unwrap();
1200 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1206 // If we receive announcement for the same channel (with UTXO lookups disabled),
1207 // drop new one on the floor, since we can't see any changes.
1208 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1210 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1213 // Test if an associated transaction were not on-chain (or not confirmed).
1214 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1215 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1216 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1217 unsigned_announcement.short_channel_id += 1;
1219 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1220 let valid_announcement = ChannelAnnouncement {
1221 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1222 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1223 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1224 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1225 contents: unsigned_announcement.clone(),
1228 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1230 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1233 // Now test if the transaction is found in the UTXO set and the script is correct.
1234 unsigned_announcement.short_channel_id += 1;
1235 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1237 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1238 let valid_announcement = ChannelAnnouncement {
1239 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1240 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1241 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1242 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1243 contents: unsigned_announcement.clone(),
1245 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1246 Ok(res) => assert!(res),
1251 let network = net_graph_msg_handler.network_graph.read().unwrap();
1252 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1258 // If we receive announcement for the same channel (but TX is not confirmed),
1259 // drop new one on the floor, since we can't see any changes.
1260 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1261 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1263 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1266 // But if it is confirmed, replace the channel
1267 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1268 unsigned_announcement.features = ChannelFeatures::empty();
1269 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1270 let valid_announcement = ChannelAnnouncement {
1271 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1272 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1273 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1274 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1275 contents: unsigned_announcement.clone(),
1277 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1278 Ok(res) => assert!(res),
1282 let network = net_graph_msg_handler.network_graph.read().unwrap();
1283 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1284 Some(channel_entry) => {
1285 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1291 // Don't relay valid channels with excess data
1292 unsigned_announcement.short_channel_id += 1;
1293 unsigned_announcement.excess_data.push(1);
1294 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1295 let valid_announcement = ChannelAnnouncement {
1296 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1297 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1298 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1299 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1300 contents: unsigned_announcement.clone(),
1302 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1303 Ok(res) => assert!(!res),
1307 unsigned_announcement.excess_data = Vec::new();
1308 let invalid_sig_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_1_btckey),
1313 contents: unsigned_announcement.clone(),
1315 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1317 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1320 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1321 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1322 let channel_to_itself_announcement = ChannelAnnouncement {
1323 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1324 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1325 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1326 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1327 contents: unsigned_announcement.clone(),
1329 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1331 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1336 fn handling_channel_update() {
1337 let secp_ctx = Secp256k1::new();
1338 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1339 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1340 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1342 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1343 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1344 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1345 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1346 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1347 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1349 let zero_hash = Sha256dHash::hash(&[0; 32]);
1350 let short_channel_id = 0;
1351 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1352 let amount_sats = 1000_000;
1355 // Announce a channel we will update
1356 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1357 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1358 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1359 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1360 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1361 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1362 let unsigned_announcement = UnsignedChannelAnnouncement {
1363 features: ChannelFeatures::empty(),
1368 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1369 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1370 excess_data: Vec::new(),
1373 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1374 let valid_channel_announcement = ChannelAnnouncement {
1375 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1376 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1377 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1378 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1379 contents: unsigned_announcement.clone(),
1381 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1388 let mut unsigned_channel_update = UnsignedChannelUpdate {
1393 cltv_expiry_delta: 144,
1394 htlc_minimum_msat: 1000000,
1395 htlc_maximum_msat: OptionalField::Absent,
1396 fee_base_msat: 10000,
1397 fee_proportional_millionths: 20,
1398 excess_data: Vec::new()
1400 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1401 let valid_channel_update = ChannelUpdate {
1402 signature: secp_ctx.sign(&msghash, node_1_privkey),
1403 contents: unsigned_channel_update.clone()
1406 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1407 Ok(res) => assert!(res),
1412 let network = net_graph_msg_handler.network_graph.read().unwrap();
1413 match network.get_channels().get(&short_channel_id) {
1415 Some(channel_info) => {
1416 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1417 assert!(channel_info.two_to_one.is_none());
1422 unsigned_channel_update.timestamp += 100;
1423 unsigned_channel_update.excess_data.push(1);
1424 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1425 let valid_channel_update = ChannelUpdate {
1426 signature: secp_ctx.sign(&msghash, node_1_privkey),
1427 contents: unsigned_channel_update.clone()
1429 // Return false because contains excess data
1430 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1431 Ok(res) => assert!(!res),
1434 unsigned_channel_update.timestamp += 10;
1436 unsigned_channel_update.short_channel_id += 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()
1443 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1445 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1447 unsigned_channel_update.short_channel_id = short_channel_id;
1449 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 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, "htlc_maximum_msat is larger than maximum possible msats")
1460 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1462 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 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 channel capacity or capacity is bogus")
1473 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1475 // Even though previous update was not relayed further, we still accepted it,
1476 // so we now won't accept update before the previous one.
1477 unsigned_channel_update.timestamp -= 10;
1478 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1479 let valid_channel_update = ChannelUpdate {
1480 signature: secp_ctx.sign(&msghash, node_1_privkey),
1481 contents: unsigned_channel_update.clone()
1484 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1486 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1488 unsigned_channel_update.timestamp += 500;
1490 let fake_msghash = hash_to_message!(&zero_hash);
1491 let invalid_sig_channel_update = ChannelUpdate {
1492 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1493 contents: unsigned_channel_update.clone()
1496 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1498 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1504 fn handling_htlc_fail_channel_update() {
1505 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1506 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1507 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1508 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1509 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1510 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1511 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1513 let short_channel_id = 0;
1514 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1517 // There is no nodes in the table at the beginning.
1518 let network = net_graph_msg_handler.network_graph.read().unwrap();
1519 assert_eq!(network.get_nodes().len(), 0);
1523 // Announce a channel we will update
1524 let unsigned_announcement = UnsignedChannelAnnouncement {
1525 features: ChannelFeatures::empty(),
1530 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1531 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1532 excess_data: Vec::new(),
1535 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1536 let valid_channel_announcement = ChannelAnnouncement {
1537 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1538 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1539 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1540 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1541 contents: unsigned_announcement.clone(),
1543 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1548 let unsigned_channel_update = UnsignedChannelUpdate {
1553 cltv_expiry_delta: 144,
1554 htlc_minimum_msat: 1000000,
1555 htlc_maximum_msat: OptionalField::Absent,
1556 fee_base_msat: 10000,
1557 fee_proportional_millionths: 20,
1558 excess_data: Vec::new()
1560 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1561 let valid_channel_update = ChannelUpdate {
1562 signature: secp_ctx.sign(&msghash, node_1_privkey),
1563 contents: unsigned_channel_update.clone()
1566 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1567 Ok(res) => assert!(res),
1572 // Non-permanent closing just disables a channel
1574 let network = net_graph_msg_handler.network_graph.read().unwrap();
1575 match network.get_channels().get(&short_channel_id) {
1577 Some(channel_info) => {
1578 assert!(channel_info.one_to_two.is_some());
1583 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1588 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1590 // Non-permanent closing just disables a channel
1592 let network = net_graph_msg_handler.network_graph.read().unwrap();
1593 match network.get_channels().get(&short_channel_id) {
1595 Some(channel_info) => {
1596 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1601 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1606 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1608 // Permanent closing deletes a channel
1610 let network = net_graph_msg_handler.network_graph.read().unwrap();
1611 assert_eq!(network.get_channels().len(), 0);
1612 // Nodes are also deleted because there are no associated channels anymore
1613 assert_eq!(network.get_nodes().len(), 0);
1615 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1619 fn getting_next_channel_announcements() {
1620 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1621 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1622 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1623 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1624 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1625 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1626 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1628 let short_channel_id = 1;
1629 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1631 // Channels were not announced yet.
1632 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1633 assert_eq!(channels_with_announcements.len(), 0);
1636 // Announce a channel we will update
1637 let unsigned_announcement = UnsignedChannelAnnouncement {
1638 features: ChannelFeatures::empty(),
1643 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1644 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1645 excess_data: Vec::new(),
1648 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1649 let valid_channel_announcement = ChannelAnnouncement {
1650 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1651 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1652 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1653 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1654 contents: unsigned_announcement.clone(),
1656 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1662 // Contains initial channel announcement now.
1663 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1664 assert_eq!(channels_with_announcements.len(), 1);
1665 if let Some(channel_announcements) = channels_with_announcements.first() {
1666 let &(_, ref update_1, ref update_2) = channel_announcements;
1667 assert_eq!(update_1, &None);
1668 assert_eq!(update_2, &None);
1675 // Valid channel update
1676 let unsigned_channel_update = UnsignedChannelUpdate {
1681 cltv_expiry_delta: 144,
1682 htlc_minimum_msat: 1000000,
1683 htlc_maximum_msat: OptionalField::Absent,
1684 fee_base_msat: 10000,
1685 fee_proportional_millionths: 20,
1686 excess_data: Vec::new()
1688 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1689 let valid_channel_update = ChannelUpdate {
1690 signature: secp_ctx.sign(&msghash, node_1_privkey),
1691 contents: unsigned_channel_update.clone()
1693 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1699 // Now contains an initial announcement and an update.
1700 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1701 assert_eq!(channels_with_announcements.len(), 1);
1702 if let Some(channel_announcements) = channels_with_announcements.first() {
1703 let &(_, ref update_1, ref update_2) = channel_announcements;
1704 assert_ne!(update_1, &None);
1705 assert_eq!(update_2, &None);
1712 // Channel update with excess data.
1713 let unsigned_channel_update = UnsignedChannelUpdate {
1718 cltv_expiry_delta: 144,
1719 htlc_minimum_msat: 1000000,
1720 htlc_maximum_msat: OptionalField::Absent,
1721 fee_base_msat: 10000,
1722 fee_proportional_millionths: 20,
1723 excess_data: [1; 3].to_vec()
1725 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1726 let valid_channel_update = ChannelUpdate {
1727 signature: secp_ctx.sign(&msghash, node_1_privkey),
1728 contents: unsigned_channel_update.clone()
1730 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1736 // Test that announcements with excess data won't be returned
1737 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1738 assert_eq!(channels_with_announcements.len(), 1);
1739 if let Some(channel_announcements) = channels_with_announcements.first() {
1740 let &(_, ref update_1, ref update_2) = channel_announcements;
1741 assert_eq!(update_1, &None);
1742 assert_eq!(update_2, &None);
1747 // Further starting point have no channels after it
1748 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1749 assert_eq!(channels_with_announcements.len(), 0);
1753 fn getting_next_node_announcements() {
1754 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1755 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1756 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1757 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1758 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1759 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1760 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1762 let short_channel_id = 1;
1763 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1766 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1767 assert_eq!(next_announcements.len(), 0);
1770 // Announce a channel to add 2 nodes
1771 let unsigned_announcement = UnsignedChannelAnnouncement {
1772 features: ChannelFeatures::empty(),
1777 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1778 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1779 excess_data: Vec::new(),
1782 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1783 let valid_channel_announcement = ChannelAnnouncement {
1784 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1785 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1786 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1787 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1788 contents: unsigned_announcement.clone(),
1790 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1797 // Nodes were never announced
1798 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1799 assert_eq!(next_announcements.len(), 0);
1802 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1803 features: NodeFeatures::known(),
1808 addresses: Vec::new(),
1809 excess_address_data: Vec::new(),
1810 excess_data: Vec::new(),
1812 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1813 let valid_announcement = NodeAnnouncement {
1814 signature: secp_ctx.sign(&msghash, node_1_privkey),
1815 contents: unsigned_announcement.clone()
1817 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1822 unsigned_announcement.node_id = node_id_2;
1823 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1824 let valid_announcement = NodeAnnouncement {
1825 signature: secp_ctx.sign(&msghash, node_2_privkey),
1826 contents: unsigned_announcement.clone()
1829 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1835 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1836 assert_eq!(next_announcements.len(), 2);
1838 // Skip the first node.
1839 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1840 assert_eq!(next_announcements.len(), 1);
1843 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1844 let unsigned_announcement = UnsignedNodeAnnouncement {
1845 features: NodeFeatures::known(),
1850 addresses: Vec::new(),
1851 excess_address_data: Vec::new(),
1852 excess_data: [1; 3].to_vec(),
1854 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1855 let valid_announcement = NodeAnnouncement {
1856 signature: secp_ctx.sign(&msghash, node_2_privkey),
1857 contents: unsigned_announcement.clone()
1859 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1860 Ok(res) => assert!(!res),
1865 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1866 assert_eq!(next_announcements.len(), 0);
1870 fn network_graph_serialization() {
1871 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1873 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1874 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1875 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1876 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1878 // Announce a channel to add a corresponding node.
1879 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1880 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1881 let unsigned_announcement = UnsignedChannelAnnouncement {
1882 features: ChannelFeatures::known(),
1883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1884 short_channel_id: 0,
1887 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1888 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1889 excess_data: Vec::new(),
1892 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1893 let valid_announcement = ChannelAnnouncement {
1894 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1895 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1896 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1897 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1898 contents: unsigned_announcement.clone(),
1900 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1901 Ok(res) => assert!(res),
1906 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1907 let unsigned_announcement = UnsignedNodeAnnouncement {
1908 features: NodeFeatures::known(),
1913 addresses: Vec::new(),
1914 excess_address_data: Vec::new(),
1915 excess_data: Vec::new(),
1917 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1918 let valid_announcement = NodeAnnouncement {
1919 signature: secp_ctx.sign(&msghash, node_1_privkey),
1920 contents: unsigned_announcement.clone()
1923 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1928 let network = net_graph_msg_handler.network_graph.write().unwrap();
1929 let mut w = test_utils::TestVecWriter(Vec::new());
1930 assert!(!network.get_nodes().is_empty());
1931 assert!(!network.get_channels().is_empty());
1932 network.write(&mut w).unwrap();
1933 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1937 fn calling_sync_routing_table() {
1938 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1939 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1940 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
1942 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1943 let first_blocknum = 0;
1944 let number_of_blocks = 0xffff_ffff;
1946 // It should ignore if gossip_queries feature is not enabled
1948 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
1949 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1950 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1951 assert_eq!(events.len(), 0);
1954 // It should send a query_channel_message with the correct information
1956 let init_msg = Init { features: InitFeatures::known() };
1957 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1958 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1959 assert_eq!(events.len(), 1);
1961 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
1962 assert_eq!(node_id, &node_id_1);
1963 assert_eq!(msg.chain_hash, chain_hash);
1964 assert_eq!(msg.first_blocknum, first_blocknum);
1965 assert_eq!(msg.number_of_blocks, number_of_blocks);
1967 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
1973 fn handling_reply_channel_range() {
1974 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1975 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1976 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
1978 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1980 // Test receipt of a single reply that should enqueue an SCID query
1981 // matching the SCIDs in the reply
1983 // Handle a single successful reply that encompasses the queried channel range
1984 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
1986 full_information: true,
1988 number_of_blocks: 2000,
1989 short_channel_ids: vec![
1990 0x0003e0_000000_0000, // 992x0x0
1991 0x0003e8_000000_0000, // 1000x0x0
1992 0x0003e9_000000_0000, // 1001x0x0
1993 0x0003f0_000000_0000, // 1008x0x0
1994 0x00044c_000000_0000, // 1100x0x0
1995 0x0006e0_000000_0000, // 1760x0x0
1998 assert!(result.is_ok());
2000 // We expect to emit a query_short_channel_ids message with the received scids
2001 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2002 assert_eq!(events.len(), 1);
2004 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2005 assert_eq!(node_id, &node_id_1);
2006 assert_eq!(msg.chain_hash, chain_hash);
2007 assert_eq!(msg.short_channel_ids, vec![
2008 0x0003e0_000000_0000, // 992x0x0
2009 0x0003e8_000000_0000, // 1000x0x0
2010 0x0003e9_000000_0000, // 1001x0x0
2011 0x0003f0_000000_0000, // 1008x0x0
2012 0x00044c_000000_0000, // 1100x0x0
2013 0x0006e0_000000_0000, // 1760x0x0
2016 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2020 // Test receipt of a reply that indicates the remote node does not maintain up-to-date
2021 // information for the chain_hash. Because of discrepancies in implementation we use
2022 // full_information=false and short_channel_ids=[] as the signal.
2024 // Handle the reply indicating the peer was unable to fulfill our request.
2025 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2027 full_information: false,
2028 first_blocknum: 1000,
2029 number_of_blocks: 100,
2030 short_channel_ids: vec![],
2032 assert!(result.is_err());
2033 assert_eq!(result.err().unwrap().err, "Received reply_channel_range with no information available");
2038 fn handling_reply_short_channel_ids() {
2039 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2040 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2041 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2043 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2045 // Test receipt of a successful reply
2047 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2049 full_information: true,
2051 assert!(result.is_ok());
2054 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2055 // for the chain_hash requested in the query.
2057 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2059 full_information: false,
2061 assert!(result.is_err());
2062 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2067 fn handling_query_channel_range() {
2068 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2069 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2070 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2072 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2074 let result = net_graph_msg_handler.handle_query_channel_range(&node_id, QueryChannelRange {
2077 number_of_blocks: 0xffff_ffff,
2079 assert!(result.is_err());
2083 fn handling_query_short_channel_ids() {
2084 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2085 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2086 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2088 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2090 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2092 short_channel_ids: vec![0x0003e8_000000_0000],
2094 assert!(result.is_err());