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 /// using gossip_queries. The default strategy used by this implementation
223 /// is to sync the full block range with several peers.
225 /// We should expect one or more reply_channel_range messages in response
226 /// to our query_channel_range. Each reply will enqueue a query_scid message
227 /// to request gossip messages for each channel. The sync is considered complete
228 /// when the final reply_scids_end message is received, though we are not
229 /// tracking this directly.
230 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
232 // We will only perform a sync with peers that support gossip_queries.
233 if !init_msg.features.supports_gossip_queries() {
237 // Check if we need to perform a full synchronization with this peer
238 if !self.should_request_full_sync(their_node_id) {
242 let first_blocknum = 0;
243 let number_of_blocks = 0xffffffff;
244 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
245 let mut pending_events = self.pending_events.lock().unwrap();
246 pending_events.push(events::MessageSendEvent::SendChannelRangeQuery {
247 node_id: their_node_id.clone(),
248 msg: QueryChannelRange {
249 chain_hash: self.network_graph.read().unwrap().genesis_hash,
256 /// Statelessly processes a reply to a channel range query by immediately
257 /// sending an SCID query with SCIDs in the reply. To keep this handler
258 /// stateless, it does not validate the sequencing of replies for multi-
259 /// reply ranges. It does not validate whether the reply(ies) cover the
260 /// queried range. It also does not filter SCIDs to only those in the
261 /// original query range. We also do not validate that the chain_hash
262 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
263 /// does not match our chain_hash will be rejected when the announcement is
265 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
266 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(),);
268 // Validate that the remote node maintains up-to-date channel
269 // information for chain_hash. Some nodes use the full_information
270 // flag to indicate multi-part messages so we must check whether
271 // we received SCIDs as well.
272 if !msg.full_information && msg.short_channel_ids.len() == 0 {
273 return Err(LightningError {
274 err: String::from("Received reply_channel_range with no information available"),
275 action: ErrorAction::IgnoreError,
279 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
280 let mut pending_events = self.pending_events.lock().unwrap();
281 pending_events.push(events::MessageSendEvent::SendShortIdsQuery {
282 node_id: their_node_id.clone(),
283 msg: QueryShortChannelIds {
284 chain_hash: msg.chain_hash,
285 short_channel_ids: msg.short_channel_ids,
292 /// When an SCID query is initiated the remote peer will begin streaming
293 /// gossip messages. In the event of a failure, we may have received
294 /// some channel information. Before trying with another peer, the
295 /// caller should update its set of SCIDs that need to be queried.
296 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
297 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
299 // If the remote node does not have up-to-date information for the
300 // chain_hash they will set full_information=false. We can fail
301 // the result and try again with a different peer.
302 if !msg.full_information {
303 return Err(LightningError {
304 err: String::from("Received reply_short_channel_ids_end with no information"),
305 action: ErrorAction::IgnoreError
312 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: QueryChannelRange) -> Result<(), LightningError> {
315 err: String::from("Not implemented"),
316 action: ErrorAction::IgnoreError,
320 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
323 err: String::from("Not implemented"),
324 action: ErrorAction::IgnoreError,
329 impl<C: Deref, L: Deref> events::MessageSendEventsProvider for NetGraphMsgHandler<C, L>
331 C::Target: chain::Access,
334 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
335 let mut ret = Vec::new();
336 let mut pending_events = self.pending_events.lock().unwrap();
337 std::mem::swap(&mut ret, &mut pending_events);
342 #[derive(PartialEq, Debug)]
343 /// Details about one direction of a channel. Received
344 /// within a channel update.
345 pub struct DirectionalChannelInfo {
346 /// When the last update to the channel direction was issued.
347 /// Value is opaque, as set in the announcement.
348 pub last_update: u32,
349 /// Whether the channel can be currently used for payments (in this one direction).
351 /// The difference in CLTV values that you must have when routing through this channel.
352 pub cltv_expiry_delta: u16,
353 /// The minimum value, which must be relayed to the next hop via the channel
354 pub htlc_minimum_msat: u64,
355 /// The maximum value which may be relayed to the next hop via the channel.
356 pub htlc_maximum_msat: Option<u64>,
357 /// Fees charged when the channel is used for routing
358 pub fees: RoutingFees,
359 /// Most recent update for the channel received from the network
360 /// Mostly redundant with the data we store in fields explicitly.
361 /// Everything else is useful only for sending out for initial routing sync.
362 /// Not stored if contains excess data to prevent DoS.
363 pub last_update_message: Option<ChannelUpdate>,
366 impl fmt::Display for DirectionalChannelInfo {
367 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
368 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)?;
373 impl_writeable!(DirectionalChannelInfo, 0, {
384 /// Details about a channel (both directions).
385 /// Received within a channel announcement.
386 pub struct ChannelInfo {
387 /// Protocol features of a channel communicated during its announcement
388 pub features: ChannelFeatures,
389 /// Source node of the first direction of a channel
390 pub node_one: PublicKey,
391 /// Details about the first direction of a channel
392 pub one_to_two: Option<DirectionalChannelInfo>,
393 /// Source node of the second direction of a channel
394 pub node_two: PublicKey,
395 /// Details about the second direction of a channel
396 pub two_to_one: Option<DirectionalChannelInfo>,
397 /// The channel capacity as seen on-chain, if chain lookup is available.
398 pub capacity_sats: Option<u64>,
399 /// An initial announcement of the channel
400 /// Mostly redundant with the data we store in fields explicitly.
401 /// Everything else is useful only for sending out for initial routing sync.
402 /// Not stored if contains excess data to prevent DoS.
403 pub announcement_message: Option<ChannelAnnouncement>,
406 impl fmt::Display for ChannelInfo {
407 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
408 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
409 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
414 impl_writeable!(ChannelInfo, 0, {
425 /// Fees for routing via a given channel or a node
426 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
427 pub struct RoutingFees {
428 /// Flat routing fee in satoshis
430 /// Liquidity-based routing fee in millionths of a routed amount.
431 /// In other words, 10000 is 1%.
432 pub proportional_millionths: u32,
435 impl Readable for RoutingFees{
436 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
437 let base_msat: u32 = Readable::read(reader)?;
438 let proportional_millionths: u32 = Readable::read(reader)?;
441 proportional_millionths,
446 impl Writeable for RoutingFees {
447 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
448 self.base_msat.write(writer)?;
449 self.proportional_millionths.write(writer)?;
454 #[derive(PartialEq, Debug)]
455 /// Information received in the latest node_announcement from this node.
456 pub struct NodeAnnouncementInfo {
457 /// Protocol features the node announced support for
458 pub features: NodeFeatures,
459 /// When the last known update to the node state was issued.
460 /// Value is opaque, as set in the announcement.
461 pub last_update: u32,
462 /// Color assigned to the node
464 /// Moniker assigned to the node.
465 /// May be invalid or malicious (eg control chars),
466 /// should not be exposed to the user.
468 /// Internet-level addresses via which one can connect to the node
469 pub addresses: Vec<NetAddress>,
470 /// An initial announcement of the node
471 /// Mostly redundant with the data we store in fields explicitly.
472 /// Everything else is useful only for sending out for initial routing sync.
473 /// Not stored if contains excess data to prevent DoS.
474 pub announcement_message: Option<NodeAnnouncement>
477 impl Writeable for NodeAnnouncementInfo {
478 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
479 self.features.write(writer)?;
480 self.last_update.write(writer)?;
481 self.rgb.write(writer)?;
482 self.alias.write(writer)?;
483 (self.addresses.len() as u64).write(writer)?;
484 for ref addr in &self.addresses {
487 self.announcement_message.write(writer)?;
492 impl Readable for NodeAnnouncementInfo {
493 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
494 let features = Readable::read(reader)?;
495 let last_update = Readable::read(reader)?;
496 let rgb = Readable::read(reader)?;
497 let alias = Readable::read(reader)?;
498 let addresses_count: u64 = Readable::read(reader)?;
499 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
500 for _ in 0..addresses_count {
501 match Readable::read(reader) {
502 Ok(Ok(addr)) => { addresses.push(addr); },
503 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
504 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
508 let announcement_message = Readable::read(reader)?;
509 Ok(NodeAnnouncementInfo {
521 /// Details about a node in the network, known from the network announcement.
522 pub struct NodeInfo {
523 /// All valid channels a node has announced
524 pub channels: Vec<u64>,
525 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
526 /// The two fields (flat and proportional fee) are independent,
527 /// meaning they don't have to refer to the same channel.
528 pub lowest_inbound_channel_fees: Option<RoutingFees>,
529 /// More information about a node from node_announcement.
530 /// Optional because we store a Node entry after learning about it from
531 /// a channel announcement, but before receiving a node announcement.
532 pub announcement_info: Option<NodeAnnouncementInfo>
535 impl fmt::Display for NodeInfo {
536 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
537 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
538 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
543 impl Writeable for NodeInfo {
544 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
545 (self.channels.len() as u64).write(writer)?;
546 for ref chan in self.channels.iter() {
549 self.lowest_inbound_channel_fees.write(writer)?;
550 self.announcement_info.write(writer)?;
555 const MAX_ALLOC_SIZE: u64 = 64*1024;
557 impl Readable for NodeInfo {
558 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
559 let channels_count: u64 = Readable::read(reader)?;
560 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
561 for _ in 0..channels_count {
562 channels.push(Readable::read(reader)?);
564 let lowest_inbound_channel_fees = Readable::read(reader)?;
565 let announcement_info = Readable::read(reader)?;
568 lowest_inbound_channel_fees,
574 impl Writeable for NetworkGraph {
575 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
576 self.genesis_hash.write(writer)?;
577 (self.channels.len() as u64).write(writer)?;
578 for (ref chan_id, ref chan_info) in self.channels.iter() {
579 (*chan_id).write(writer)?;
580 chan_info.write(writer)?;
582 (self.nodes.len() as u64).write(writer)?;
583 for (ref node_id, ref node_info) in self.nodes.iter() {
584 node_id.write(writer)?;
585 node_info.write(writer)?;
591 impl Readable for NetworkGraph {
592 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
593 let genesis_hash: BlockHash = Readable::read(reader)?;
594 let channels_count: u64 = Readable::read(reader)?;
595 let mut channels = BTreeMap::new();
596 for _ in 0..channels_count {
597 let chan_id: u64 = Readable::read(reader)?;
598 let chan_info = Readable::read(reader)?;
599 channels.insert(chan_id, chan_info);
601 let nodes_count: u64 = Readable::read(reader)?;
602 let mut nodes = BTreeMap::new();
603 for _ in 0..nodes_count {
604 let node_id = Readable::read(reader)?;
605 let node_info = Readable::read(reader)?;
606 nodes.insert(node_id, node_info);
616 impl fmt::Display for NetworkGraph {
617 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
618 writeln!(f, "Network map\n[Channels]")?;
619 for (key, val) in self.channels.iter() {
620 writeln!(f, " {}: {}", key, val)?;
622 writeln!(f, "[Nodes]")?;
623 for (key, val) in self.nodes.iter() {
624 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
631 /// Returns all known valid channels' short ids along with announced channel info.
633 /// (C-not exported) because we have no mapping for `BTreeMap`s
634 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
635 /// Returns all known nodes' public keys along with announced node info.
637 /// (C-not exported) because we have no mapping for `BTreeMap`s
638 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
640 /// Get network addresses by node id.
641 /// Returns None if the requested node is completely unknown,
642 /// or if node announcement for the node was never received.
644 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
645 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
646 if let Some(node) = self.nodes.get(pubkey) {
647 if let Some(node_info) = node.announcement_info.as_ref() {
648 return Some(&node_info.addresses)
654 /// Creates a new, empty, network graph.
655 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
658 channels: BTreeMap::new(),
659 nodes: BTreeMap::new(),
663 /// For an already known node (from channel announcements), update its stored properties from a
664 /// given node announcement.
666 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
667 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
668 /// routing messages from a source using a protocol other than the lightning P2P protocol.
669 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
670 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
671 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
672 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
675 /// For an already known node (from channel announcements), update its stored properties from a
676 /// given node announcement without verifying the associated signatures. Because we aren't
677 /// given the associated signatures here we cannot relay the node announcement to any of our
679 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
680 self.update_node_from_announcement_intern(msg, None)
683 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
684 match self.nodes.get_mut(&msg.node_id) {
685 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
687 if let Some(node_info) = node.announcement_info.as_ref() {
688 if node_info.last_update >= msg.timestamp {
689 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
693 let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
694 node.announcement_info = Some(NodeAnnouncementInfo {
695 features: msg.features.clone(),
696 last_update: msg.timestamp,
699 addresses: msg.addresses.clone(),
700 announcement_message: if should_relay { full_msg.cloned() } else { None },
708 /// Store or update channel info from a channel announcement.
710 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
711 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
712 /// routing messages from a source using a protocol other than the lightning P2P protocol.
714 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
715 /// the corresponding UTXO exists on chain and is correctly-formatted.
716 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
717 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
718 -> Result<(), LightningError>
719 where C::Target: chain::Access {
720 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
721 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
722 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
723 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
724 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
725 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
728 /// Store or update channel info from a channel announcement without verifying the associated
729 /// signatures. Because we aren't given the associated signatures here we cannot relay the
730 /// channel announcement to any of our peers.
732 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
733 /// the corresponding UTXO exists on chain and is correctly-formatted.
734 pub fn update_channel_from_unsigned_announcement<C: Deref>
735 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
736 -> Result<(), LightningError>
737 where C::Target: chain::Access {
738 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
741 fn update_channel_from_unsigned_announcement_intern<C: Deref>
742 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
743 -> Result<(), LightningError>
744 where C::Target: chain::Access {
745 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
746 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
749 let utxo_value = match &chain_access {
751 // Tentatively accept, potentially exposing us to DoS attacks
754 &Some(ref chain_access) => {
755 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
756 Ok(TxOut { value, script_pubkey }) => {
757 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
758 .push_slice(&msg.bitcoin_key_1.serialize())
759 .push_slice(&msg.bitcoin_key_2.serialize())
760 .push_opcode(opcodes::all::OP_PUSHNUM_2)
761 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
762 if script_pubkey != expected_script {
763 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});
765 //TODO: Check if value is worth storing, use it to inform routing, and compare it
766 //to the new HTLC max field in channel_update
769 Err(chain::AccessError::UnknownChain) => {
770 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
772 Err(chain::AccessError::UnknownTx) => {
773 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
779 let chan_info = ChannelInfo {
780 features: msg.features.clone(),
781 node_one: msg.node_id_1.clone(),
783 node_two: msg.node_id_2.clone(),
785 capacity_sats: utxo_value,
786 announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
789 match self.channels.entry(msg.short_channel_id) {
790 BtreeEntry::Occupied(mut entry) => {
791 //TODO: because asking the blockchain if short_channel_id is valid is only optional
792 //in the blockchain API, we need to handle it smartly here, though it's unclear
794 if utxo_value.is_some() {
795 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
796 // only sometimes returns results. In any case remove the previous entry. Note
797 // that the spec expects us to "blacklist" the node_ids involved, but we can't
799 // a) we don't *require* a UTXO provider that always returns results.
800 // b) we don't track UTXOs of channels we know about and remove them if they
802 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
803 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
804 *entry.get_mut() = chan_info;
806 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
809 BtreeEntry::Vacant(entry) => {
810 entry.insert(chan_info);
814 macro_rules! add_channel_to_node {
815 ( $node_id: expr ) => {
816 match self.nodes.entry($node_id) {
817 BtreeEntry::Occupied(node_entry) => {
818 node_entry.into_mut().channels.push(msg.short_channel_id);
820 BtreeEntry::Vacant(node_entry) => {
821 node_entry.insert(NodeInfo {
822 channels: vec!(msg.short_channel_id),
823 lowest_inbound_channel_fees: None,
824 announcement_info: None,
831 add_channel_to_node!(msg.node_id_1);
832 add_channel_to_node!(msg.node_id_2);
837 /// Close a channel if a corresponding HTLC fail was sent.
838 /// If permanent, removes a channel from the local storage.
839 /// May cause the removal of nodes too, if this was their last channel.
840 /// If not permanent, makes channels unavailable for routing.
841 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
843 if let Some(chan) = self.channels.remove(&short_channel_id) {
844 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
847 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
848 if let Some(one_to_two) = chan.one_to_two.as_mut() {
849 one_to_two.enabled = false;
851 if let Some(two_to_one) = chan.two_to_one.as_mut() {
852 two_to_one.enabled = false;
858 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
860 // TODO: Wholly remove the node
862 // TODO: downgrade the node
866 /// For an already known (from announcement) channel, update info about one of the directions
869 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
870 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
871 /// routing messages from a source using a protocol other than the lightning P2P protocol.
872 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
873 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
876 /// For an already known (from announcement) channel, update info about one of the directions
877 /// of the channel without verifying the associated signatures. Because we aren't given the
878 /// associated signatures here we cannot relay the channel update to any of our peers.
879 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
880 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
883 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> {
885 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
886 let chan_was_enabled;
888 match self.channels.get_mut(&msg.short_channel_id) {
889 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
891 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
892 if htlc_maximum_msat > MAX_VALUE_MSAT {
893 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
896 if let Some(capacity_sats) = channel.capacity_sats {
897 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
898 // Don't query UTXO set here to reduce DoS risks.
899 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
900 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
904 macro_rules! maybe_update_channel_info {
905 ( $target: expr, $src_node: expr) => {
906 if let Some(existing_chan_info) = $target.as_ref() {
907 if existing_chan_info.last_update >= msg.timestamp {
908 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
910 chan_was_enabled = existing_chan_info.enabled;
912 chan_was_enabled = false;
915 let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
917 let updated_channel_dir_info = DirectionalChannelInfo {
918 enabled: chan_enabled,
919 last_update: msg.timestamp,
920 cltv_expiry_delta: msg.cltv_expiry_delta,
921 htlc_minimum_msat: msg.htlc_minimum_msat,
922 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
924 base_msat: msg.fee_base_msat,
925 proportional_millionths: msg.fee_proportional_millionths,
929 $target = Some(updated_channel_dir_info);
933 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
934 if msg.flags & 1 == 1 {
935 dest_node_id = channel.node_one.clone();
936 if let Some((sig, ctx)) = sig_info {
937 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
939 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
941 dest_node_id = channel.node_two.clone();
942 if let Some((sig, ctx)) = sig_info {
943 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
945 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
951 let node = self.nodes.get_mut(&dest_node_id).unwrap();
952 let mut base_msat = msg.fee_base_msat;
953 let mut proportional_millionths = msg.fee_proportional_millionths;
954 if let Some(fees) = node.lowest_inbound_channel_fees {
955 base_msat = cmp::min(base_msat, fees.base_msat);
956 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
958 node.lowest_inbound_channel_fees = Some(RoutingFees {
960 proportional_millionths
962 } else if chan_was_enabled {
963 let node = self.nodes.get_mut(&dest_node_id).unwrap();
964 let mut lowest_inbound_channel_fees = None;
966 for chan_id in node.channels.iter() {
967 let chan = self.channels.get(chan_id).unwrap();
969 if chan.node_one == dest_node_id {
970 chan_info_opt = chan.two_to_one.as_ref();
972 chan_info_opt = chan.one_to_two.as_ref();
974 if let Some(chan_info) = chan_info_opt {
975 if chan_info.enabled {
976 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
977 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
978 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
979 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
984 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
990 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
991 macro_rules! remove_from_node {
992 ($node_id: expr) => {
993 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
994 entry.get_mut().channels.retain(|chan_id| {
995 short_channel_id != *chan_id
997 if entry.get().channels.is_empty() {
998 entry.remove_entry();
1001 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1006 remove_from_node!(chan.node_one);
1007 remove_from_node!(chan.node_two);
1014 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1015 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
1016 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1017 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1018 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1019 use util::test_utils;
1020 use util::logger::Logger;
1021 use util::ser::{Readable, Writeable};
1022 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1024 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1025 use bitcoin::hashes::Hash;
1026 use bitcoin::network::constants::Network;
1027 use bitcoin::blockdata::constants::genesis_block;
1028 use bitcoin::blockdata::script::Builder;
1029 use bitcoin::blockdata::transaction::TxOut;
1030 use bitcoin::blockdata::opcodes;
1034 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1035 use bitcoin::secp256k1::{All, Secp256k1};
1039 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1040 let secp_ctx = Secp256k1::new();
1041 let logger = Arc::new(test_utils::TestLogger::new());
1042 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1043 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1044 (secp_ctx, net_graph_msg_handler)
1048 fn request_full_sync_finite_times() {
1049 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1050 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1052 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1053 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1054 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1055 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1056 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1057 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1061 fn handling_node_announcements() {
1062 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1064 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1065 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1066 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1067 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1068 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1069 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1070 let zero_hash = Sha256dHash::hash(&[0; 32]);
1071 let first_announcement_time = 500;
1073 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1074 features: NodeFeatures::known(),
1075 timestamp: first_announcement_time,
1079 addresses: Vec::new(),
1080 excess_address_data: Vec::new(),
1081 excess_data: Vec::new(),
1083 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1084 let valid_announcement = NodeAnnouncement {
1085 signature: secp_ctx.sign(&msghash, node_1_privkey),
1086 contents: unsigned_announcement.clone()
1089 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1091 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1095 // Announce a channel to add a corresponding node.
1096 let unsigned_announcement = UnsignedChannelAnnouncement {
1097 features: ChannelFeatures::known(),
1098 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1099 short_channel_id: 0,
1102 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1103 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1104 excess_data: Vec::new(),
1107 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1108 let valid_announcement = ChannelAnnouncement {
1109 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1110 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1111 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1112 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1113 contents: unsigned_announcement.clone(),
1115 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1116 Ok(res) => assert!(res),
1121 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1122 Ok(res) => assert!(res),
1126 let fake_msghash = hash_to_message!(&zero_hash);
1127 match net_graph_msg_handler.handle_node_announcement(
1129 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1130 contents: unsigned_announcement.clone()
1133 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1136 unsigned_announcement.timestamp += 1000;
1137 unsigned_announcement.excess_data.push(1);
1138 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1139 let announcement_with_data = NodeAnnouncement {
1140 signature: secp_ctx.sign(&msghash, node_1_privkey),
1141 contents: unsigned_announcement.clone()
1143 // Return false because contains excess data.
1144 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1145 Ok(res) => assert!(!res),
1148 unsigned_announcement.excess_data = Vec::new();
1150 // Even though previous announcement was not relayed further, we still accepted it,
1151 // so we now won't accept announcements before the previous one.
1152 unsigned_announcement.timestamp -= 10;
1153 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1154 let outdated_announcement = NodeAnnouncement {
1155 signature: secp_ctx.sign(&msghash, node_1_privkey),
1156 contents: unsigned_announcement.clone()
1158 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1160 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1165 fn handling_channel_announcements() {
1166 let secp_ctx = Secp256k1::new();
1167 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1169 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1170 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1171 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1172 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1173 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1174 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1176 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1177 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1178 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1179 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1180 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1183 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1184 features: ChannelFeatures::known(),
1185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1186 short_channel_id: 0,
1189 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1190 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1191 excess_data: Vec::new(),
1194 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1195 let valid_announcement = ChannelAnnouncement {
1196 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1197 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1198 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1199 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1200 contents: unsigned_announcement.clone(),
1203 // Test if the UTXO lookups were not supported
1204 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1205 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1206 Ok(res) => assert!(res),
1211 let network = net_graph_msg_handler.network_graph.read().unwrap();
1212 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1218 // If we receive announcement for the same channel (with UTXO lookups disabled),
1219 // drop new one on the floor, since we can't see any changes.
1220 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1222 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1225 // Test if an associated transaction were not on-chain (or not confirmed).
1226 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1227 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1228 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1229 unsigned_announcement.short_channel_id += 1;
1231 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1232 let valid_announcement = ChannelAnnouncement {
1233 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1234 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1235 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1236 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1237 contents: unsigned_announcement.clone(),
1240 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1242 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1245 // Now test if the transaction is found in the UTXO set and the script is correct.
1246 unsigned_announcement.short_channel_id += 1;
1247 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1249 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1250 let valid_announcement = ChannelAnnouncement {
1251 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1252 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1253 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1254 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1255 contents: unsigned_announcement.clone(),
1257 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1258 Ok(res) => assert!(res),
1263 let network = net_graph_msg_handler.network_graph.read().unwrap();
1264 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1270 // If we receive announcement for the same channel (but TX is not confirmed),
1271 // drop new one on the floor, since we can't see any changes.
1272 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1273 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1275 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1278 // But if it is confirmed, replace the channel
1279 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1280 unsigned_announcement.features = ChannelFeatures::empty();
1281 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1282 let valid_announcement = ChannelAnnouncement {
1283 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1284 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1285 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1286 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1287 contents: unsigned_announcement.clone(),
1289 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1290 Ok(res) => assert!(res),
1294 let network = net_graph_msg_handler.network_graph.read().unwrap();
1295 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1296 Some(channel_entry) => {
1297 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1303 // Don't relay valid channels with excess data
1304 unsigned_announcement.short_channel_id += 1;
1305 unsigned_announcement.excess_data.push(1);
1306 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1307 let valid_announcement = ChannelAnnouncement {
1308 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1309 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1310 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1311 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1312 contents: unsigned_announcement.clone(),
1314 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1315 Ok(res) => assert!(!res),
1319 unsigned_announcement.excess_data = Vec::new();
1320 let invalid_sig_announcement = ChannelAnnouncement {
1321 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1322 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1323 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1324 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1325 contents: unsigned_announcement.clone(),
1327 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1329 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1332 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1333 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1334 let channel_to_itself_announcement = ChannelAnnouncement {
1335 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1336 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1337 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1338 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1339 contents: unsigned_announcement.clone(),
1341 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1343 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1348 fn handling_channel_update() {
1349 let secp_ctx = Secp256k1::new();
1350 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1351 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1352 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1354 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1355 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1356 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1357 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1358 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1359 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1361 let zero_hash = Sha256dHash::hash(&[0; 32]);
1362 let short_channel_id = 0;
1363 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1364 let amount_sats = 1000_000;
1367 // Announce a channel we will update
1368 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1369 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1370 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1371 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1372 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1373 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1374 let unsigned_announcement = UnsignedChannelAnnouncement {
1375 features: ChannelFeatures::empty(),
1380 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1381 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1382 excess_data: Vec::new(),
1385 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1386 let valid_channel_announcement = ChannelAnnouncement {
1387 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1388 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1389 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1390 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1391 contents: unsigned_announcement.clone(),
1393 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1400 let mut unsigned_channel_update = UnsignedChannelUpdate {
1405 cltv_expiry_delta: 144,
1406 htlc_minimum_msat: 1000000,
1407 htlc_maximum_msat: OptionalField::Absent,
1408 fee_base_msat: 10000,
1409 fee_proportional_millionths: 20,
1410 excess_data: Vec::new()
1412 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1413 let valid_channel_update = ChannelUpdate {
1414 signature: secp_ctx.sign(&msghash, node_1_privkey),
1415 contents: unsigned_channel_update.clone()
1418 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1419 Ok(res) => assert!(res),
1424 let network = net_graph_msg_handler.network_graph.read().unwrap();
1425 match network.get_channels().get(&short_channel_id) {
1427 Some(channel_info) => {
1428 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1429 assert!(channel_info.two_to_one.is_none());
1434 unsigned_channel_update.timestamp += 100;
1435 unsigned_channel_update.excess_data.push(1);
1436 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1437 let valid_channel_update = ChannelUpdate {
1438 signature: secp_ctx.sign(&msghash, node_1_privkey),
1439 contents: unsigned_channel_update.clone()
1441 // Return false because contains excess data
1442 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1443 Ok(res) => assert!(!res),
1446 unsigned_channel_update.timestamp += 10;
1448 unsigned_channel_update.short_channel_id += 1;
1449 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1450 let valid_channel_update = ChannelUpdate {
1451 signature: secp_ctx.sign(&msghash, node_1_privkey),
1452 contents: unsigned_channel_update.clone()
1455 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1457 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1459 unsigned_channel_update.short_channel_id = short_channel_id;
1461 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1462 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1463 let valid_channel_update = ChannelUpdate {
1464 signature: secp_ctx.sign(&msghash, node_1_privkey),
1465 contents: unsigned_channel_update.clone()
1468 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1470 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1472 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1474 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1475 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1476 let valid_channel_update = ChannelUpdate {
1477 signature: secp_ctx.sign(&msghash, node_1_privkey),
1478 contents: unsigned_channel_update.clone()
1481 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1483 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1485 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1487 // Even though previous update was not relayed further, we still accepted it,
1488 // so we now won't accept update before the previous one.
1489 unsigned_channel_update.timestamp -= 10;
1490 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1491 let valid_channel_update = ChannelUpdate {
1492 signature: secp_ctx.sign(&msghash, node_1_privkey),
1493 contents: unsigned_channel_update.clone()
1496 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1498 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1500 unsigned_channel_update.timestamp += 500;
1502 let fake_msghash = hash_to_message!(&zero_hash);
1503 let invalid_sig_channel_update = ChannelUpdate {
1504 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1505 contents: unsigned_channel_update.clone()
1508 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1510 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1516 fn handling_htlc_fail_channel_update() {
1517 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1518 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1519 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1520 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1521 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1522 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1523 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1525 let short_channel_id = 0;
1526 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1529 // There is no nodes in the table at the beginning.
1530 let network = net_graph_msg_handler.network_graph.read().unwrap();
1531 assert_eq!(network.get_nodes().len(), 0);
1535 // Announce a channel we will update
1536 let unsigned_announcement = UnsignedChannelAnnouncement {
1537 features: ChannelFeatures::empty(),
1542 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1543 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1544 excess_data: Vec::new(),
1547 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1548 let valid_channel_announcement = ChannelAnnouncement {
1549 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1550 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1551 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1552 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1553 contents: unsigned_announcement.clone(),
1555 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1560 let unsigned_channel_update = UnsignedChannelUpdate {
1565 cltv_expiry_delta: 144,
1566 htlc_minimum_msat: 1000000,
1567 htlc_maximum_msat: OptionalField::Absent,
1568 fee_base_msat: 10000,
1569 fee_proportional_millionths: 20,
1570 excess_data: Vec::new()
1572 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1573 let valid_channel_update = ChannelUpdate {
1574 signature: secp_ctx.sign(&msghash, node_1_privkey),
1575 contents: unsigned_channel_update.clone()
1578 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1579 Ok(res) => assert!(res),
1584 // Non-permanent closing just disables a channel
1586 let network = net_graph_msg_handler.network_graph.read().unwrap();
1587 match network.get_channels().get(&short_channel_id) {
1589 Some(channel_info) => {
1590 assert!(channel_info.one_to_two.is_some());
1595 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1600 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1602 // Non-permanent closing just disables a channel
1604 let network = net_graph_msg_handler.network_graph.read().unwrap();
1605 match network.get_channels().get(&short_channel_id) {
1607 Some(channel_info) => {
1608 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1613 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1618 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1620 // Permanent closing deletes a channel
1622 let network = net_graph_msg_handler.network_graph.read().unwrap();
1623 assert_eq!(network.get_channels().len(), 0);
1624 // Nodes are also deleted because there are no associated channels anymore
1625 assert_eq!(network.get_nodes().len(), 0);
1627 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1631 fn getting_next_channel_announcements() {
1632 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1633 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1634 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1635 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1636 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1637 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1638 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1640 let short_channel_id = 1;
1641 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1643 // Channels were not announced yet.
1644 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1645 assert_eq!(channels_with_announcements.len(), 0);
1648 // Announce a channel we will update
1649 let unsigned_announcement = UnsignedChannelAnnouncement {
1650 features: ChannelFeatures::empty(),
1655 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1656 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1657 excess_data: Vec::new(),
1660 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1661 let valid_channel_announcement = ChannelAnnouncement {
1662 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1663 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1664 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1665 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1666 contents: unsigned_announcement.clone(),
1668 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1674 // Contains initial channel announcement now.
1675 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1676 assert_eq!(channels_with_announcements.len(), 1);
1677 if let Some(channel_announcements) = channels_with_announcements.first() {
1678 let &(_, ref update_1, ref update_2) = channel_announcements;
1679 assert_eq!(update_1, &None);
1680 assert_eq!(update_2, &None);
1687 // Valid channel update
1688 let unsigned_channel_update = UnsignedChannelUpdate {
1693 cltv_expiry_delta: 144,
1694 htlc_minimum_msat: 1000000,
1695 htlc_maximum_msat: OptionalField::Absent,
1696 fee_base_msat: 10000,
1697 fee_proportional_millionths: 20,
1698 excess_data: Vec::new()
1700 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1701 let valid_channel_update = ChannelUpdate {
1702 signature: secp_ctx.sign(&msghash, node_1_privkey),
1703 contents: unsigned_channel_update.clone()
1705 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1711 // Now contains an initial announcement and an update.
1712 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1713 assert_eq!(channels_with_announcements.len(), 1);
1714 if let Some(channel_announcements) = channels_with_announcements.first() {
1715 let &(_, ref update_1, ref update_2) = channel_announcements;
1716 assert_ne!(update_1, &None);
1717 assert_eq!(update_2, &None);
1724 // Channel update with excess data.
1725 let unsigned_channel_update = UnsignedChannelUpdate {
1730 cltv_expiry_delta: 144,
1731 htlc_minimum_msat: 1000000,
1732 htlc_maximum_msat: OptionalField::Absent,
1733 fee_base_msat: 10000,
1734 fee_proportional_millionths: 20,
1735 excess_data: [1; 3].to_vec()
1737 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1738 let valid_channel_update = ChannelUpdate {
1739 signature: secp_ctx.sign(&msghash, node_1_privkey),
1740 contents: unsigned_channel_update.clone()
1742 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1748 // Test that announcements with excess data won't be returned
1749 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1750 assert_eq!(channels_with_announcements.len(), 1);
1751 if let Some(channel_announcements) = channels_with_announcements.first() {
1752 let &(_, ref update_1, ref update_2) = channel_announcements;
1753 assert_eq!(update_1, &None);
1754 assert_eq!(update_2, &None);
1759 // Further starting point have no channels after it
1760 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1761 assert_eq!(channels_with_announcements.len(), 0);
1765 fn getting_next_node_announcements() {
1766 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1767 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1768 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1769 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1770 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1771 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1772 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1774 let short_channel_id = 1;
1775 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1778 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1779 assert_eq!(next_announcements.len(), 0);
1782 // Announce a channel to add 2 nodes
1783 let unsigned_announcement = UnsignedChannelAnnouncement {
1784 features: ChannelFeatures::empty(),
1789 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1790 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1791 excess_data: Vec::new(),
1794 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1795 let valid_channel_announcement = ChannelAnnouncement {
1796 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1797 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1798 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1799 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1800 contents: unsigned_announcement.clone(),
1802 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1809 // Nodes were never announced
1810 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1811 assert_eq!(next_announcements.len(), 0);
1814 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1815 features: NodeFeatures::known(),
1820 addresses: Vec::new(),
1821 excess_address_data: Vec::new(),
1822 excess_data: Vec::new(),
1824 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1825 let valid_announcement = NodeAnnouncement {
1826 signature: secp_ctx.sign(&msghash, node_1_privkey),
1827 contents: unsigned_announcement.clone()
1829 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1834 unsigned_announcement.node_id = node_id_2;
1835 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1836 let valid_announcement = NodeAnnouncement {
1837 signature: secp_ctx.sign(&msghash, node_2_privkey),
1838 contents: unsigned_announcement.clone()
1841 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1847 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1848 assert_eq!(next_announcements.len(), 2);
1850 // Skip the first node.
1851 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1852 assert_eq!(next_announcements.len(), 1);
1855 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1856 let unsigned_announcement = UnsignedNodeAnnouncement {
1857 features: NodeFeatures::known(),
1862 addresses: Vec::new(),
1863 excess_address_data: Vec::new(),
1864 excess_data: [1; 3].to_vec(),
1866 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1867 let valid_announcement = NodeAnnouncement {
1868 signature: secp_ctx.sign(&msghash, node_2_privkey),
1869 contents: unsigned_announcement.clone()
1871 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1872 Ok(res) => assert!(!res),
1877 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1878 assert_eq!(next_announcements.len(), 0);
1882 fn network_graph_serialization() {
1883 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1885 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1886 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1887 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1888 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1890 // Announce a channel to add a corresponding node.
1891 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1892 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1893 let unsigned_announcement = UnsignedChannelAnnouncement {
1894 features: ChannelFeatures::known(),
1895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1896 short_channel_id: 0,
1899 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1900 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1901 excess_data: Vec::new(),
1904 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1905 let valid_announcement = ChannelAnnouncement {
1906 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1907 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1908 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1909 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1910 contents: unsigned_announcement.clone(),
1912 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1913 Ok(res) => assert!(res),
1918 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1919 let unsigned_announcement = UnsignedNodeAnnouncement {
1920 features: NodeFeatures::known(),
1925 addresses: Vec::new(),
1926 excess_address_data: Vec::new(),
1927 excess_data: Vec::new(),
1929 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1930 let valid_announcement = NodeAnnouncement {
1931 signature: secp_ctx.sign(&msghash, node_1_privkey),
1932 contents: unsigned_announcement.clone()
1935 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1940 let network = net_graph_msg_handler.network_graph.write().unwrap();
1941 let mut w = test_utils::TestVecWriter(Vec::new());
1942 assert!(!network.get_nodes().is_empty());
1943 assert!(!network.get_channels().is_empty());
1944 network.write(&mut w).unwrap();
1945 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1949 fn calling_sync_routing_table() {
1950 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1951 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1952 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
1954 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1955 let first_blocknum = 0;
1956 let number_of_blocks = 0xffff_ffff;
1958 // It should ignore if gossip_queries feature is not enabled
1960 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
1961 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1962 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1963 assert_eq!(events.len(), 0);
1966 // It should send a query_channel_message with the correct information
1968 let init_msg = Init { features: InitFeatures::known() };
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(), 1);
1973 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
1974 assert_eq!(node_id, &node_id_1);
1975 assert_eq!(msg.chain_hash, chain_hash);
1976 assert_eq!(msg.first_blocknum, first_blocknum);
1977 assert_eq!(msg.number_of_blocks, number_of_blocks);
1979 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
1983 // It should not enqueue a query when should_request_full_sync return false.
1984 // The initial implementation allows syncing with the first 5 peers after
1985 // which should_request_full_sync will return false
1987 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1988 let init_msg = Init { features: InitFeatures::known() };
1990 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
1991 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1992 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
1993 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1995 assert_eq!(events.len(), 1);
1997 assert_eq!(events.len(), 0);
2005 fn handling_reply_channel_range() {
2006 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2007 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2008 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2010 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2012 // Test receipt of a single reply that should enqueue an SCID query
2013 // matching the SCIDs in the reply
2015 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2017 full_information: true,
2019 number_of_blocks: 2000,
2020 short_channel_ids: vec![
2021 0x0003e0_000000_0000, // 992x0x0
2022 0x0003e8_000000_0000, // 1000x0x0
2023 0x0003e9_000000_0000, // 1001x0x0
2024 0x0003f0_000000_0000, // 1008x0x0
2025 0x00044c_000000_0000, // 1100x0x0
2026 0x0006e0_000000_0000, // 1760x0x0
2029 assert!(result.is_ok());
2031 // We expect to emit a query_short_channel_ids message with the received scids
2032 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2033 assert_eq!(events.len(), 1);
2035 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2036 assert_eq!(node_id, &node_id_1);
2037 assert_eq!(msg.chain_hash, chain_hash);
2038 assert_eq!(msg.short_channel_ids, vec![
2039 0x0003e0_000000_0000, // 992x0x0
2040 0x0003e8_000000_0000, // 1000x0x0
2041 0x0003e9_000000_0000, // 1001x0x0
2042 0x0003f0_000000_0000, // 1008x0x0
2043 0x00044c_000000_0000, // 1100x0x0
2044 0x0006e0_000000_0000, // 1760x0x0
2047 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2051 // Test receipt of a reply that indicates the remote node does not maintain up-to-date
2052 // information for the chain_hash. Because of discrepancies in implementation we use
2053 // full_information=false and short_channel_ids=[] as the signal.
2055 // Handle the reply indicating the peer was unable to fulfill our request.
2056 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2058 full_information: false,
2059 first_blocknum: 1000,
2060 number_of_blocks: 100,
2061 short_channel_ids: vec![],
2063 assert!(result.is_err());
2064 assert_eq!(result.err().unwrap().err, "Received reply_channel_range with no information available");
2069 fn handling_reply_short_channel_ids() {
2070 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2071 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2072 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2074 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2076 // Test receipt of a successful reply
2078 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2080 full_information: true,
2082 assert!(result.is_ok());
2085 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2086 // for the chain_hash requested in the query.
2088 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2090 full_information: false,
2092 assert!(result.is_err());
2093 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2098 fn handling_query_channel_range() {
2099 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2100 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2101 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2103 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2105 let result = net_graph_msg_handler.handle_query_channel_range(&node_id, QueryChannelRange {
2108 number_of_blocks: 0xffff_ffff,
2110 assert!(result.is_err());
2114 fn handling_query_short_channel_ids() {
2115 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2116 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2117 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2119 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2121 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2123 short_channel_ids: vec![0x0003e8_000000_0000],
2125 assert!(result.is_err());