1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level network map tracking logic lives here.
12 use bitcoin::secp256k1::key::PublicKey;
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::secp256k1;
16 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
17 use bitcoin::hashes::Hash;
18 use bitcoin::blockdata::script::Builder;
19 use bitcoin::blockdata::transaction::TxOut;
20 use bitcoin::blockdata::opcodes;
21 use bitcoin::hash_types::BlockHash;
25 use ln::features::{ChannelFeatures, NodeFeatures};
26 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
27 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
28 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use util::ser::{Writeable, Readable, Writer};
31 use util::logger::Logger;
32 use util::events::{MessageSendEvent, MessageSendEventsProvider};
35 use std::sync::{RwLock, RwLockReadGuard};
36 use std::sync::atomic::{AtomicUsize, Ordering};
38 use std::collections::BTreeMap;
39 use std::collections::btree_map::Entry as BtreeEntry;
41 use bitcoin::hashes::hex::ToHex;
43 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
44 /// refuse to relay the message.
45 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
47 /// Represents the network as nodes and channels between them
48 #[derive(Clone, PartialEq)]
49 pub struct NetworkGraph {
50 genesis_hash: BlockHash,
51 channels: BTreeMap<u64, ChannelInfo>,
52 nodes: BTreeMap<PublicKey, NodeInfo>,
55 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
56 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
57 /// the C bindings, as it can be done directly in Rust code.
58 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
60 /// Receives and validates network updates from peers,
61 /// stores authentic and relevant data as a network graph.
62 /// This network graph is then used for routing payments.
63 /// Provides interface to help with initial routing sync by
64 /// serving historical announcements.
65 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
66 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
67 /// Representation of the payment channel network
68 pub network_graph: RwLock<NetworkGraph>,
69 chain_access: Option<C>,
70 full_syncs_requested: AtomicUsize,
71 pending_events: Mutex<Vec<MessageSendEvent>>,
75 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
76 /// Creates a new tracker of the actual state of the network of channels and nodes,
77 /// assuming a fresh network graph.
78 /// Chain monitor is used to make sure announced channels exist on-chain,
79 /// channel data is correct, and that the announcement is signed with
80 /// channel owners' keys.
81 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
83 secp_ctx: Secp256k1::verification_only(),
84 network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
85 full_syncs_requested: AtomicUsize::new(0),
87 pending_events: Mutex::new(vec![]),
92 /// Creates a new tracker of the actual state of the network of channels and nodes,
93 /// assuming an existing Network Graph.
94 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
96 secp_ctx: Secp256k1::verification_only(),
97 network_graph: RwLock::new(network_graph),
98 full_syncs_requested: AtomicUsize::new(0),
100 pending_events: Mutex::new(vec![]),
105 /// Adds a provider used to check new announcements. Does not affect
106 /// existing announcements unless they are updated.
107 /// Add, update or remove the provider would replace the current one.
108 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
109 self.chain_access = chain_access;
112 /// Take a read lock on the network_graph and return it in the C-bindings
113 /// newtype helper. This is likely only useful when called via the C
114 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
116 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
117 LockedNetworkGraph(self.network_graph.read().unwrap())
120 /// Returns true when a full routing table sync should be performed with a peer.
121 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
122 //TODO: Determine whether to request a full sync based on the network map.
123 const FULL_SYNCS_TO_REQUEST: usize = 5;
124 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
125 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
133 impl<'a> LockedNetworkGraph<'a> {
134 /// Get a reference to the NetworkGraph which this read-lock contains.
135 pub fn graph(&self) -> &NetworkGraph {
141 macro_rules! secp_verify_sig {
142 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
143 match $secp_ctx.verify($msg, $sig, $pubkey) {
145 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
150 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
151 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
152 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
153 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
154 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
155 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
158 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
159 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
160 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 { "" });
161 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
164 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
166 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
167 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
169 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
170 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
172 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
173 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
178 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
179 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
180 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
183 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
184 let network_graph = self.network_graph.read().unwrap();
185 let mut result = Vec::with_capacity(batch_amount as usize);
186 let mut iter = network_graph.get_channels().range(starting_point..);
187 while result.len() < batch_amount as usize {
188 if let Some((_, ref chan)) = iter.next() {
189 if chan.announcement_message.is_some() {
190 let chan_announcement = chan.announcement_message.clone().unwrap();
191 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
192 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
193 if let Some(one_to_two) = chan.one_to_two.as_ref() {
194 one_to_two_announcement = one_to_two.last_update_message.clone();
196 if let Some(two_to_one) = chan.two_to_one.as_ref() {
197 two_to_one_announcement = two_to_one.last_update_message.clone();
199 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
201 // TODO: We may end up sending un-announced channel_updates if we are sending
202 // initial sync data while receiving announce/updates for this channel.
211 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
212 let network_graph = self.network_graph.read().unwrap();
213 let mut result = Vec::with_capacity(batch_amount as usize);
214 let mut iter = if let Some(pubkey) = starting_point {
215 let mut iter = network_graph.get_nodes().range((*pubkey)..);
219 network_graph.get_nodes().range(..)
221 while result.len() < batch_amount as usize {
222 if let Some((_, ref node)) = iter.next() {
223 if let Some(node_info) = node.announcement_info.as_ref() {
224 if node_info.announcement_message.is_some() {
225 result.push(node_info.announcement_message.clone().unwrap());
235 /// Initiates a stateless sync of routing gossip information with a peer
236 /// using gossip_queries. The default strategy used by this implementation
237 /// is to sync the full block range with several peers.
239 /// We should expect one or more reply_channel_range messages in response
240 /// to our query_channel_range. Each reply will enqueue a query_scid message
241 /// to request gossip messages for each channel. The sync is considered complete
242 /// when the final reply_scids_end message is received, though we are not
243 /// tracking this directly.
244 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
246 // We will only perform a sync with peers that support gossip_queries.
247 if !init_msg.features.supports_gossip_queries() {
251 // Check if we need to perform a full synchronization with this peer
252 if !self.should_request_full_sync(their_node_id) {
256 let first_blocknum = 0;
257 let number_of_blocks = 0xffffffff;
258 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
259 let mut pending_events = self.pending_events.lock().unwrap();
260 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
261 node_id: their_node_id.clone(),
262 msg: QueryChannelRange {
263 chain_hash: self.network_graph.read().unwrap().genesis_hash,
270 /// Statelessly processes a reply to a channel range query by immediately
271 /// sending an SCID query with SCIDs in the reply. To keep this handler
272 /// stateless, it does not validate the sequencing of replies for multi-
273 /// reply ranges. It does not validate whether the reply(ies) cover the
274 /// queried range. It also does not filter SCIDs to only those in the
275 /// original query range. We also do not validate that the chain_hash
276 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
277 /// does not match our chain_hash will be rejected when the announcement is
279 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
280 log_debug!(self.logger, "Handling reply_channel_range peer={}, first_blocknum={}, number_of_blocks={}, sync_complete={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.sync_complete, msg.short_channel_ids.len(),);
282 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
283 let mut pending_events = self.pending_events.lock().unwrap();
284 pending_events.push(MessageSendEvent::SendShortIdsQuery {
285 node_id: their_node_id.clone(),
286 msg: QueryShortChannelIds {
287 chain_hash: msg.chain_hash,
288 short_channel_ids: msg.short_channel_ids,
295 /// When an SCID query is initiated the remote peer will begin streaming
296 /// gossip messages. In the event of a failure, we may have received
297 /// some channel information. Before trying with another peer, the
298 /// caller should update its set of SCIDs that need to be queried.
299 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
300 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
302 // If the remote node does not have up-to-date information for the
303 // chain_hash they will set full_information=false. We can fail
304 // the result and try again with a different peer.
305 if !msg.full_information {
306 return Err(LightningError {
307 err: String::from("Received reply_short_channel_ids_end with no information"),
308 action: ErrorAction::IgnoreError
315 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: QueryChannelRange) -> Result<(), LightningError> {
318 err: String::from("Not implemented"),
319 action: ErrorAction::IgnoreError,
323 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
326 err: String::from("Not implemented"),
327 action: ErrorAction::IgnoreError,
332 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
334 C::Target: chain::Access,
337 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
338 let mut ret = Vec::new();
339 let mut pending_events = self.pending_events.lock().unwrap();
340 std::mem::swap(&mut ret, &mut pending_events);
345 #[derive(Clone, Debug, PartialEq)]
346 /// Details about one direction of a channel. Received
347 /// within a channel update.
348 pub struct DirectionalChannelInfo {
349 /// When the last update to the channel direction was issued.
350 /// Value is opaque, as set in the announcement.
351 pub last_update: u32,
352 /// Whether the channel can be currently used for payments (in this one direction).
354 /// The difference in CLTV values that you must have when routing through this channel.
355 pub cltv_expiry_delta: u16,
356 /// The minimum value, which must be relayed to the next hop via the channel
357 pub htlc_minimum_msat: u64,
358 /// The maximum value which may be relayed to the next hop via the channel.
359 pub htlc_maximum_msat: Option<u64>,
360 /// Fees charged when the channel is used for routing
361 pub fees: RoutingFees,
362 /// Most recent update for the channel received from the network
363 /// Mostly redundant with the data we store in fields explicitly.
364 /// Everything else is useful only for sending out for initial routing sync.
365 /// Not stored if contains excess data to prevent DoS.
366 pub last_update_message: Option<ChannelUpdate>,
369 impl fmt::Display for DirectionalChannelInfo {
370 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
371 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)?;
376 impl_writeable!(DirectionalChannelInfo, 0, {
386 #[derive(Clone, Debug, PartialEq)]
387 /// Details about a channel (both directions).
388 /// Received within a channel announcement.
389 pub struct ChannelInfo {
390 /// Protocol features of a channel communicated during its announcement
391 pub features: ChannelFeatures,
392 /// Source node of the first direction of a channel
393 pub node_one: PublicKey,
394 /// Details about the first direction of a channel
395 pub one_to_two: Option<DirectionalChannelInfo>,
396 /// Source node of the second direction of a channel
397 pub node_two: PublicKey,
398 /// Details about the second direction of a channel
399 pub two_to_one: Option<DirectionalChannelInfo>,
400 /// The channel capacity as seen on-chain, if chain lookup is available.
401 pub capacity_sats: Option<u64>,
402 /// An initial announcement of the channel
403 /// Mostly redundant with the data we store in fields explicitly.
404 /// Everything else is useful only for sending out for initial routing sync.
405 /// Not stored if contains excess data to prevent DoS.
406 pub announcement_message: Option<ChannelAnnouncement>,
409 impl fmt::Display for ChannelInfo {
410 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
411 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
412 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
417 impl_writeable!(ChannelInfo, 0, {
428 /// Fees for routing via a given channel or a node
429 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
430 pub struct RoutingFees {
431 /// Flat routing fee in satoshis
433 /// Liquidity-based routing fee in millionths of a routed amount.
434 /// In other words, 10000 is 1%.
435 pub proportional_millionths: u32,
438 impl Readable for RoutingFees{
439 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
440 let base_msat: u32 = Readable::read(reader)?;
441 let proportional_millionths: u32 = Readable::read(reader)?;
444 proportional_millionths,
449 impl Writeable for RoutingFees {
450 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
451 self.base_msat.write(writer)?;
452 self.proportional_millionths.write(writer)?;
457 #[derive(Clone, Debug, PartialEq)]
458 /// Information received in the latest node_announcement from this node.
459 pub struct NodeAnnouncementInfo {
460 /// Protocol features the node announced support for
461 pub features: NodeFeatures,
462 /// When the last known update to the node state was issued.
463 /// Value is opaque, as set in the announcement.
464 pub last_update: u32,
465 /// Color assigned to the node
467 /// Moniker assigned to the node.
468 /// May be invalid or malicious (eg control chars),
469 /// should not be exposed to the user.
471 /// Internet-level addresses via which one can connect to the node
472 pub addresses: Vec<NetAddress>,
473 /// An initial announcement of the node
474 /// Mostly redundant with the data we store in fields explicitly.
475 /// Everything else is useful only for sending out for initial routing sync.
476 /// Not stored if contains excess data to prevent DoS.
477 pub announcement_message: Option<NodeAnnouncement>
480 impl Writeable for NodeAnnouncementInfo {
481 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
482 self.features.write(writer)?;
483 self.last_update.write(writer)?;
484 self.rgb.write(writer)?;
485 self.alias.write(writer)?;
486 (self.addresses.len() as u64).write(writer)?;
487 for ref addr in &self.addresses {
490 self.announcement_message.write(writer)?;
495 impl Readable for NodeAnnouncementInfo {
496 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
497 let features = Readable::read(reader)?;
498 let last_update = Readable::read(reader)?;
499 let rgb = Readable::read(reader)?;
500 let alias = Readable::read(reader)?;
501 let addresses_count: u64 = Readable::read(reader)?;
502 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
503 for _ in 0..addresses_count {
504 match Readable::read(reader) {
505 Ok(Ok(addr)) => { addresses.push(addr); },
506 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
507 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
511 let announcement_message = Readable::read(reader)?;
512 Ok(NodeAnnouncementInfo {
523 #[derive(Clone, Debug, PartialEq)]
524 /// Details about a node in the network, known from the network announcement.
525 pub struct NodeInfo {
526 /// All valid channels a node has announced
527 pub channels: Vec<u64>,
528 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
529 /// The two fields (flat and proportional fee) are independent,
530 /// meaning they don't have to refer to the same channel.
531 pub lowest_inbound_channel_fees: Option<RoutingFees>,
532 /// More information about a node from node_announcement.
533 /// Optional because we store a Node entry after learning about it from
534 /// a channel announcement, but before receiving a node announcement.
535 pub announcement_info: Option<NodeAnnouncementInfo>
538 impl fmt::Display for NodeInfo {
539 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
540 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
541 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
546 impl Writeable for NodeInfo {
547 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
548 (self.channels.len() as u64).write(writer)?;
549 for ref chan in self.channels.iter() {
552 self.lowest_inbound_channel_fees.write(writer)?;
553 self.announcement_info.write(writer)?;
558 const MAX_ALLOC_SIZE: u64 = 64*1024;
560 impl Readable for NodeInfo {
561 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
562 let channels_count: u64 = Readable::read(reader)?;
563 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
564 for _ in 0..channels_count {
565 channels.push(Readable::read(reader)?);
567 let lowest_inbound_channel_fees = Readable::read(reader)?;
568 let announcement_info = Readable::read(reader)?;
571 lowest_inbound_channel_fees,
577 impl Writeable for NetworkGraph {
578 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
579 self.genesis_hash.write(writer)?;
580 (self.channels.len() as u64).write(writer)?;
581 for (ref chan_id, ref chan_info) in self.channels.iter() {
582 (*chan_id).write(writer)?;
583 chan_info.write(writer)?;
585 (self.nodes.len() as u64).write(writer)?;
586 for (ref node_id, ref node_info) in self.nodes.iter() {
587 node_id.write(writer)?;
588 node_info.write(writer)?;
594 impl Readable for NetworkGraph {
595 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
596 let genesis_hash: BlockHash = Readable::read(reader)?;
597 let channels_count: u64 = Readable::read(reader)?;
598 let mut channels = BTreeMap::new();
599 for _ in 0..channels_count {
600 let chan_id: u64 = Readable::read(reader)?;
601 let chan_info = Readable::read(reader)?;
602 channels.insert(chan_id, chan_info);
604 let nodes_count: u64 = Readable::read(reader)?;
605 let mut nodes = BTreeMap::new();
606 for _ in 0..nodes_count {
607 let node_id = Readable::read(reader)?;
608 let node_info = Readable::read(reader)?;
609 nodes.insert(node_id, node_info);
619 impl fmt::Display for NetworkGraph {
620 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
621 writeln!(f, "Network map\n[Channels]")?;
622 for (key, val) in self.channels.iter() {
623 writeln!(f, " {}: {}", key, val)?;
625 writeln!(f, "[Nodes]")?;
626 for (key, val) in self.nodes.iter() {
627 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
634 /// Returns all known valid channels' short ids along with announced channel info.
636 /// (C-not exported) because we have no mapping for `BTreeMap`s
637 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
638 /// Returns all known nodes' public keys along with announced node info.
640 /// (C-not exported) because we have no mapping for `BTreeMap`s
641 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
643 /// Get network addresses by node id.
644 /// Returns None if the requested node is completely unknown,
645 /// or if node announcement for the node was never received.
647 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
648 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
649 if let Some(node) = self.nodes.get(pubkey) {
650 if let Some(node_info) = node.announcement_info.as_ref() {
651 return Some(&node_info.addresses)
657 /// Creates a new, empty, network graph.
658 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
661 channels: BTreeMap::new(),
662 nodes: BTreeMap::new(),
666 /// For an already known node (from channel announcements), update its stored properties from a
667 /// given node announcement.
669 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
670 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
671 /// routing messages from a source using a protocol other than the lightning P2P protocol.
672 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
673 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
674 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
675 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
678 /// For an already known node (from channel announcements), update its stored properties from a
679 /// given node announcement without verifying the associated signatures. Because we aren't
680 /// given the associated signatures here we cannot relay the node announcement to any of our
682 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
683 self.update_node_from_announcement_intern(msg, None)
686 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
687 match self.nodes.get_mut(&msg.node_id) {
688 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
690 if let Some(node_info) = node.announcement_info.as_ref() {
691 if node_info.last_update >= msg.timestamp {
692 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
697 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
698 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
699 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
700 node.announcement_info = Some(NodeAnnouncementInfo {
701 features: msg.features.clone(),
702 last_update: msg.timestamp,
705 addresses: msg.addresses.clone(),
706 announcement_message: if should_relay { full_msg.cloned() } else { None },
714 /// Store or update channel info from a channel announcement.
716 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
717 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
718 /// routing messages from a source using a protocol other than the lightning P2P protocol.
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_announcement<T: secp256k1::Verification, C: Deref>
723 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
724 -> Result<(), LightningError>
725 where C::Target: chain::Access {
726 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
727 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
728 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
729 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
730 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
731 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
734 /// Store or update channel info from a channel announcement without verifying the associated
735 /// signatures. Because we aren't given the associated signatures here we cannot relay the
736 /// channel announcement to any of our peers.
738 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
739 /// the corresponding UTXO exists on chain and is correctly-formatted.
740 pub fn update_channel_from_unsigned_announcement<C: Deref>
741 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
742 -> Result<(), LightningError>
743 where C::Target: chain::Access {
744 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
747 fn update_channel_from_unsigned_announcement_intern<C: Deref>
748 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
749 -> Result<(), LightningError>
750 where C::Target: chain::Access {
751 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
752 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
755 let utxo_value = match &chain_access {
757 // Tentatively accept, potentially exposing us to DoS attacks
760 &Some(ref chain_access) => {
761 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
762 Ok(TxOut { value, script_pubkey }) => {
763 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
764 .push_slice(&msg.bitcoin_key_1.serialize())
765 .push_slice(&msg.bitcoin_key_2.serialize())
766 .push_opcode(opcodes::all::OP_PUSHNUM_2)
767 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
768 if script_pubkey != expected_script {
769 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});
771 //TODO: Check if value is worth storing, use it to inform routing, and compare it
772 //to the new HTLC max field in channel_update
775 Err(chain::AccessError::UnknownChain) => {
776 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
778 Err(chain::AccessError::UnknownTx) => {
779 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
785 let chan_info = ChannelInfo {
786 features: msg.features.clone(),
787 node_one: msg.node_id_1.clone(),
789 node_two: msg.node_id_2.clone(),
791 capacity_sats: utxo_value,
792 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
793 { full_msg.cloned() } else { None },
796 match self.channels.entry(msg.short_channel_id) {
797 BtreeEntry::Occupied(mut entry) => {
798 //TODO: because asking the blockchain if short_channel_id is valid is only optional
799 //in the blockchain API, we need to handle it smartly here, though it's unclear
801 if utxo_value.is_some() {
802 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
803 // only sometimes returns results. In any case remove the previous entry. Note
804 // that the spec expects us to "blacklist" the node_ids involved, but we can't
806 // a) we don't *require* a UTXO provider that always returns results.
807 // b) we don't track UTXOs of channels we know about and remove them if they
809 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
810 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
811 *entry.get_mut() = chan_info;
813 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
816 BtreeEntry::Vacant(entry) => {
817 entry.insert(chan_info);
821 macro_rules! add_channel_to_node {
822 ( $node_id: expr ) => {
823 match self.nodes.entry($node_id) {
824 BtreeEntry::Occupied(node_entry) => {
825 node_entry.into_mut().channels.push(msg.short_channel_id);
827 BtreeEntry::Vacant(node_entry) => {
828 node_entry.insert(NodeInfo {
829 channels: vec!(msg.short_channel_id),
830 lowest_inbound_channel_fees: None,
831 announcement_info: None,
838 add_channel_to_node!(msg.node_id_1);
839 add_channel_to_node!(msg.node_id_2);
844 /// Close a channel if a corresponding HTLC fail was sent.
845 /// If permanent, removes a channel from the local storage.
846 /// May cause the removal of nodes too, if this was their last channel.
847 /// If not permanent, makes channels unavailable for routing.
848 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
850 if let Some(chan) = self.channels.remove(&short_channel_id) {
851 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
854 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
855 if let Some(one_to_two) = chan.one_to_two.as_mut() {
856 one_to_two.enabled = false;
858 if let Some(two_to_one) = chan.two_to_one.as_mut() {
859 two_to_one.enabled = false;
865 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
867 // TODO: Wholly remove the node
869 // TODO: downgrade the node
873 /// For an already known (from announcement) channel, update info about one of the directions
876 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
877 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
878 /// routing messages from a source using a protocol other than the lightning P2P protocol.
879 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
880 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
883 /// For an already known (from announcement) channel, update info about one of the directions
884 /// of the channel without verifying the associated signatures. Because we aren't given the
885 /// associated signatures here we cannot relay the channel update to any of our peers.
886 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
887 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
890 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> {
892 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
893 let chan_was_enabled;
895 match self.channels.get_mut(&msg.short_channel_id) {
896 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
898 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
899 if htlc_maximum_msat > MAX_VALUE_MSAT {
900 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
903 if let Some(capacity_sats) = channel.capacity_sats {
904 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
905 // Don't query UTXO set here to reduce DoS risks.
906 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
907 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
911 macro_rules! maybe_update_channel_info {
912 ( $target: expr, $src_node: expr) => {
913 if let Some(existing_chan_info) = $target.as_ref() {
914 if existing_chan_info.last_update >= msg.timestamp {
915 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
917 chan_was_enabled = existing_chan_info.enabled;
919 chan_was_enabled = false;
922 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
923 { full_msg.cloned() } else { None };
925 let updated_channel_dir_info = DirectionalChannelInfo {
926 enabled: chan_enabled,
927 last_update: msg.timestamp,
928 cltv_expiry_delta: msg.cltv_expiry_delta,
929 htlc_minimum_msat: msg.htlc_minimum_msat,
930 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
932 base_msat: msg.fee_base_msat,
933 proportional_millionths: msg.fee_proportional_millionths,
937 $target = Some(updated_channel_dir_info);
941 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
942 if msg.flags & 1 == 1 {
943 dest_node_id = channel.node_one.clone();
944 if let Some((sig, ctx)) = sig_info {
945 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
947 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
949 dest_node_id = channel.node_two.clone();
950 if let Some((sig, ctx)) = sig_info {
951 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
953 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
959 let node = self.nodes.get_mut(&dest_node_id).unwrap();
960 let mut base_msat = msg.fee_base_msat;
961 let mut proportional_millionths = msg.fee_proportional_millionths;
962 if let Some(fees) = node.lowest_inbound_channel_fees {
963 base_msat = cmp::min(base_msat, fees.base_msat);
964 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
966 node.lowest_inbound_channel_fees = Some(RoutingFees {
968 proportional_millionths
970 } else if chan_was_enabled {
971 let node = self.nodes.get_mut(&dest_node_id).unwrap();
972 let mut lowest_inbound_channel_fees = None;
974 for chan_id in node.channels.iter() {
975 let chan = self.channels.get(chan_id).unwrap();
977 if chan.node_one == dest_node_id {
978 chan_info_opt = chan.two_to_one.as_ref();
980 chan_info_opt = chan.one_to_two.as_ref();
982 if let Some(chan_info) = chan_info_opt {
983 if chan_info.enabled {
984 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
985 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
986 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
987 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
992 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
998 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
999 macro_rules! remove_from_node {
1000 ($node_id: expr) => {
1001 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1002 entry.get_mut().channels.retain(|chan_id| {
1003 short_channel_id != *chan_id
1005 if entry.get().channels.is_empty() {
1006 entry.remove_entry();
1009 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1014 remove_from_node!(chan.node_one);
1015 remove_from_node!(chan.node_two);
1022 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1023 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
1024 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1025 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1026 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1027 use util::test_utils;
1028 use util::logger::Logger;
1029 use util::ser::{Readable, Writeable};
1030 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1032 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1033 use bitcoin::hashes::Hash;
1034 use bitcoin::network::constants::Network;
1035 use bitcoin::blockdata::constants::genesis_block;
1036 use bitcoin::blockdata::script::Builder;
1037 use bitcoin::blockdata::transaction::TxOut;
1038 use bitcoin::blockdata::opcodes;
1042 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1043 use bitcoin::secp256k1::{All, Secp256k1};
1047 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1048 let secp_ctx = Secp256k1::new();
1049 let logger = Arc::new(test_utils::TestLogger::new());
1050 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1051 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1052 (secp_ctx, net_graph_msg_handler)
1056 fn request_full_sync_finite_times() {
1057 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1058 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1060 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1061 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1062 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1063 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1064 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1065 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1069 fn handling_node_announcements() {
1070 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1072 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1073 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1074 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1075 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1076 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1077 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1078 let zero_hash = Sha256dHash::hash(&[0; 32]);
1079 let first_announcement_time = 500;
1081 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1082 features: NodeFeatures::known(),
1083 timestamp: first_announcement_time,
1087 addresses: Vec::new(),
1088 excess_address_data: Vec::new(),
1089 excess_data: Vec::new(),
1091 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1092 let valid_announcement = NodeAnnouncement {
1093 signature: secp_ctx.sign(&msghash, node_1_privkey),
1094 contents: unsigned_announcement.clone()
1097 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1099 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1103 // Announce a channel to add a corresponding node.
1104 let unsigned_announcement = UnsignedChannelAnnouncement {
1105 features: ChannelFeatures::known(),
1106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1107 short_channel_id: 0,
1110 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1111 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1112 excess_data: Vec::new(),
1115 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1116 let valid_announcement = ChannelAnnouncement {
1117 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1118 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1119 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1120 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1121 contents: unsigned_announcement.clone(),
1123 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1124 Ok(res) => assert!(res),
1129 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1130 Ok(res) => assert!(res),
1134 let fake_msghash = hash_to_message!(&zero_hash);
1135 match net_graph_msg_handler.handle_node_announcement(
1137 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1138 contents: unsigned_announcement.clone()
1141 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1144 unsigned_announcement.timestamp += 1000;
1145 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1146 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1147 let announcement_with_data = NodeAnnouncement {
1148 signature: secp_ctx.sign(&msghash, node_1_privkey),
1149 contents: unsigned_announcement.clone()
1151 // Return false because contains excess data.
1152 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1153 Ok(res) => assert!(!res),
1156 unsigned_announcement.excess_data = Vec::new();
1158 // Even though previous announcement was not relayed further, we still accepted it,
1159 // so we now won't accept announcements before the previous one.
1160 unsigned_announcement.timestamp -= 10;
1161 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1162 let outdated_announcement = NodeAnnouncement {
1163 signature: secp_ctx.sign(&msghash, node_1_privkey),
1164 contents: unsigned_announcement.clone()
1166 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1168 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1173 fn handling_channel_announcements() {
1174 let secp_ctx = Secp256k1::new();
1175 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1177 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1178 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1179 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1180 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1181 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1182 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1184 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1185 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1186 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1187 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1188 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1191 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1192 features: ChannelFeatures::known(),
1193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1194 short_channel_id: 0,
1197 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1198 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1199 excess_data: Vec::new(),
1202 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1203 let valid_announcement = ChannelAnnouncement {
1204 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1205 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1206 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1207 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1208 contents: unsigned_announcement.clone(),
1211 // Test if the UTXO lookups were not supported
1212 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1213 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1214 Ok(res) => assert!(res),
1219 let network = net_graph_msg_handler.network_graph.read().unwrap();
1220 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1226 // If we receive announcement for the same channel (with UTXO lookups disabled),
1227 // drop new one on the floor, since we can't see any changes.
1228 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1230 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1233 // Test if an associated transaction were not on-chain (or not confirmed).
1234 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1235 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1236 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1237 unsigned_announcement.short_channel_id += 1;
1239 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1240 let valid_announcement = ChannelAnnouncement {
1241 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1242 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1243 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1244 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1245 contents: unsigned_announcement.clone(),
1248 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1250 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1253 // Now test if the transaction is found in the UTXO set and the script is correct.
1254 unsigned_announcement.short_channel_id += 1;
1255 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1257 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1258 let valid_announcement = ChannelAnnouncement {
1259 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1260 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1261 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1262 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1263 contents: unsigned_announcement.clone(),
1265 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1266 Ok(res) => assert!(res),
1271 let network = net_graph_msg_handler.network_graph.read().unwrap();
1272 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1278 // If we receive announcement for the same channel (but TX is not confirmed),
1279 // drop new one on the floor, since we can't see any changes.
1280 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1281 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1283 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1286 // But if it is confirmed, replace the channel
1287 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1288 unsigned_announcement.features = ChannelFeatures::empty();
1289 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1290 let valid_announcement = ChannelAnnouncement {
1291 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1292 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1293 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1294 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1295 contents: unsigned_announcement.clone(),
1297 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1298 Ok(res) => assert!(res),
1302 let network = net_graph_msg_handler.network_graph.read().unwrap();
1303 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1304 Some(channel_entry) => {
1305 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1311 // Don't relay valid channels with excess data
1312 unsigned_announcement.short_channel_id += 1;
1313 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1314 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1315 let valid_announcement = ChannelAnnouncement {
1316 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1317 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1318 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1319 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1320 contents: unsigned_announcement.clone(),
1322 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1323 Ok(res) => assert!(!res),
1327 unsigned_announcement.excess_data = Vec::new();
1328 let invalid_sig_announcement = ChannelAnnouncement {
1329 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1330 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1331 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1332 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1333 contents: unsigned_announcement.clone(),
1335 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1337 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1340 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1341 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1342 let channel_to_itself_announcement = ChannelAnnouncement {
1343 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1344 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1345 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1346 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1347 contents: unsigned_announcement.clone(),
1349 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1351 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1356 fn handling_channel_update() {
1357 let secp_ctx = Secp256k1::new();
1358 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1359 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1360 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1362 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1363 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1364 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1365 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1366 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1367 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1369 let zero_hash = Sha256dHash::hash(&[0; 32]);
1370 let short_channel_id = 0;
1371 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1372 let amount_sats = 1000_000;
1375 // Announce a channel we will update
1376 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1377 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1378 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1379 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1380 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1381 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1382 let unsigned_announcement = UnsignedChannelAnnouncement {
1383 features: ChannelFeatures::empty(),
1388 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1389 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1390 excess_data: Vec::new(),
1393 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1394 let valid_channel_announcement = ChannelAnnouncement {
1395 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1396 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1397 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1398 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1399 contents: unsigned_announcement.clone(),
1401 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1408 let mut unsigned_channel_update = UnsignedChannelUpdate {
1413 cltv_expiry_delta: 144,
1414 htlc_minimum_msat: 1000000,
1415 htlc_maximum_msat: OptionalField::Absent,
1416 fee_base_msat: 10000,
1417 fee_proportional_millionths: 20,
1418 excess_data: Vec::new()
1420 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1421 let valid_channel_update = ChannelUpdate {
1422 signature: secp_ctx.sign(&msghash, node_1_privkey),
1423 contents: unsigned_channel_update.clone()
1426 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1427 Ok(res) => assert!(res),
1432 let network = net_graph_msg_handler.network_graph.read().unwrap();
1433 match network.get_channels().get(&short_channel_id) {
1435 Some(channel_info) => {
1436 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1437 assert!(channel_info.two_to_one.is_none());
1442 unsigned_channel_update.timestamp += 100;
1443 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1444 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1445 let valid_channel_update = ChannelUpdate {
1446 signature: secp_ctx.sign(&msghash, node_1_privkey),
1447 contents: unsigned_channel_update.clone()
1449 // Return false because contains excess data
1450 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1451 Ok(res) => assert!(!res),
1454 unsigned_channel_update.timestamp += 10;
1456 unsigned_channel_update.short_channel_id += 1;
1457 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1458 let valid_channel_update = ChannelUpdate {
1459 signature: secp_ctx.sign(&msghash, node_1_privkey),
1460 contents: unsigned_channel_update.clone()
1463 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1465 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1467 unsigned_channel_update.short_channel_id = short_channel_id;
1469 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1470 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1471 let valid_channel_update = ChannelUpdate {
1472 signature: secp_ctx.sign(&msghash, node_1_privkey),
1473 contents: unsigned_channel_update.clone()
1476 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1478 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1480 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1482 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1483 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1484 let valid_channel_update = ChannelUpdate {
1485 signature: secp_ctx.sign(&msghash, node_1_privkey),
1486 contents: unsigned_channel_update.clone()
1489 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1491 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1493 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1495 // Even though previous update was not relayed further, we still accepted it,
1496 // so we now won't accept update before the previous one.
1497 unsigned_channel_update.timestamp -= 10;
1498 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1499 let valid_channel_update = ChannelUpdate {
1500 signature: secp_ctx.sign(&msghash, node_1_privkey),
1501 contents: unsigned_channel_update.clone()
1504 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1506 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1508 unsigned_channel_update.timestamp += 500;
1510 let fake_msghash = hash_to_message!(&zero_hash);
1511 let invalid_sig_channel_update = ChannelUpdate {
1512 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1513 contents: unsigned_channel_update.clone()
1516 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1518 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1524 fn handling_htlc_fail_channel_update() {
1525 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1526 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1527 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1528 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1529 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1530 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1531 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1533 let short_channel_id = 0;
1534 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1537 // There is no nodes in the table at the beginning.
1538 let network = net_graph_msg_handler.network_graph.read().unwrap();
1539 assert_eq!(network.get_nodes().len(), 0);
1543 // Announce a channel we will update
1544 let unsigned_announcement = UnsignedChannelAnnouncement {
1545 features: ChannelFeatures::empty(),
1550 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1551 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1552 excess_data: Vec::new(),
1555 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1556 let valid_channel_announcement = ChannelAnnouncement {
1557 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1558 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1559 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1560 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1561 contents: unsigned_announcement.clone(),
1563 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1568 let unsigned_channel_update = UnsignedChannelUpdate {
1573 cltv_expiry_delta: 144,
1574 htlc_minimum_msat: 1000000,
1575 htlc_maximum_msat: OptionalField::Absent,
1576 fee_base_msat: 10000,
1577 fee_proportional_millionths: 20,
1578 excess_data: Vec::new()
1580 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1581 let valid_channel_update = ChannelUpdate {
1582 signature: secp_ctx.sign(&msghash, node_1_privkey),
1583 contents: unsigned_channel_update.clone()
1586 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1587 Ok(res) => assert!(res),
1592 // Non-permanent closing just disables a channel
1594 let network = net_graph_msg_handler.network_graph.read().unwrap();
1595 match network.get_channels().get(&short_channel_id) {
1597 Some(channel_info) => {
1598 assert!(channel_info.one_to_two.is_some());
1603 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1608 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1610 // Non-permanent closing just disables a channel
1612 let network = net_graph_msg_handler.network_graph.read().unwrap();
1613 match network.get_channels().get(&short_channel_id) {
1615 Some(channel_info) => {
1616 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1621 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1626 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1628 // Permanent closing deletes a channel
1630 let network = net_graph_msg_handler.network_graph.read().unwrap();
1631 assert_eq!(network.get_channels().len(), 0);
1632 // Nodes are also deleted because there are no associated channels anymore
1633 assert_eq!(network.get_nodes().len(), 0);
1635 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1639 fn getting_next_channel_announcements() {
1640 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1641 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1642 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1643 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1644 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1645 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1646 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1648 let short_channel_id = 1;
1649 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1651 // Channels were not announced yet.
1652 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1653 assert_eq!(channels_with_announcements.len(), 0);
1656 // Announce a channel we will update
1657 let unsigned_announcement = UnsignedChannelAnnouncement {
1658 features: ChannelFeatures::empty(),
1663 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1664 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1665 excess_data: Vec::new(),
1668 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1669 let valid_channel_announcement = ChannelAnnouncement {
1670 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1671 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1672 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1673 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1674 contents: unsigned_announcement.clone(),
1676 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1682 // Contains initial channel announcement now.
1683 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1684 assert_eq!(channels_with_announcements.len(), 1);
1685 if let Some(channel_announcements) = channels_with_announcements.first() {
1686 let &(_, ref update_1, ref update_2) = channel_announcements;
1687 assert_eq!(update_1, &None);
1688 assert_eq!(update_2, &None);
1695 // Valid channel update
1696 let unsigned_channel_update = UnsignedChannelUpdate {
1701 cltv_expiry_delta: 144,
1702 htlc_minimum_msat: 1000000,
1703 htlc_maximum_msat: OptionalField::Absent,
1704 fee_base_msat: 10000,
1705 fee_proportional_millionths: 20,
1706 excess_data: Vec::new()
1708 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1709 let valid_channel_update = ChannelUpdate {
1710 signature: secp_ctx.sign(&msghash, node_1_privkey),
1711 contents: unsigned_channel_update.clone()
1713 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1719 // Now contains an initial announcement and an update.
1720 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1721 assert_eq!(channels_with_announcements.len(), 1);
1722 if let Some(channel_announcements) = channels_with_announcements.first() {
1723 let &(_, ref update_1, ref update_2) = channel_announcements;
1724 assert_ne!(update_1, &None);
1725 assert_eq!(update_2, &None);
1732 // Channel update with excess data.
1733 let unsigned_channel_update = UnsignedChannelUpdate {
1738 cltv_expiry_delta: 144,
1739 htlc_minimum_msat: 1000000,
1740 htlc_maximum_msat: OptionalField::Absent,
1741 fee_base_msat: 10000,
1742 fee_proportional_millionths: 20,
1743 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1745 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1746 let valid_channel_update = ChannelUpdate {
1747 signature: secp_ctx.sign(&msghash, node_1_privkey),
1748 contents: unsigned_channel_update.clone()
1750 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1756 // Test that announcements with excess data won't be returned
1757 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1758 assert_eq!(channels_with_announcements.len(), 1);
1759 if let Some(channel_announcements) = channels_with_announcements.first() {
1760 let &(_, ref update_1, ref update_2) = channel_announcements;
1761 assert_eq!(update_1, &None);
1762 assert_eq!(update_2, &None);
1767 // Further starting point have no channels after it
1768 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1769 assert_eq!(channels_with_announcements.len(), 0);
1773 fn getting_next_node_announcements() {
1774 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1775 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1776 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1777 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1778 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1779 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1780 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1782 let short_channel_id = 1;
1783 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1786 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1787 assert_eq!(next_announcements.len(), 0);
1790 // Announce a channel to add 2 nodes
1791 let unsigned_announcement = UnsignedChannelAnnouncement {
1792 features: ChannelFeatures::empty(),
1797 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1798 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1799 excess_data: Vec::new(),
1802 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1803 let valid_channel_announcement = ChannelAnnouncement {
1804 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1805 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1806 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1807 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1808 contents: unsigned_announcement.clone(),
1810 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1817 // Nodes were never announced
1818 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1819 assert_eq!(next_announcements.len(), 0);
1822 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1823 features: NodeFeatures::known(),
1828 addresses: Vec::new(),
1829 excess_address_data: Vec::new(),
1830 excess_data: Vec::new(),
1832 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1833 let valid_announcement = NodeAnnouncement {
1834 signature: secp_ctx.sign(&msghash, node_1_privkey),
1835 contents: unsigned_announcement.clone()
1837 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1842 unsigned_announcement.node_id = node_id_2;
1843 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1844 let valid_announcement = NodeAnnouncement {
1845 signature: secp_ctx.sign(&msghash, node_2_privkey),
1846 contents: unsigned_announcement.clone()
1849 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1855 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1856 assert_eq!(next_announcements.len(), 2);
1858 // Skip the first node.
1859 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1860 assert_eq!(next_announcements.len(), 1);
1863 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1864 let unsigned_announcement = UnsignedNodeAnnouncement {
1865 features: NodeFeatures::known(),
1870 addresses: Vec::new(),
1871 excess_address_data: Vec::new(),
1872 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
1874 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1875 let valid_announcement = NodeAnnouncement {
1876 signature: secp_ctx.sign(&msghash, node_2_privkey),
1877 contents: unsigned_announcement.clone()
1879 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1880 Ok(res) => assert!(!res),
1885 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1886 assert_eq!(next_announcements.len(), 0);
1890 fn network_graph_serialization() {
1891 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1893 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1894 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1895 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1896 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1898 // Announce a channel to add a corresponding node.
1899 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1900 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1901 let unsigned_announcement = UnsignedChannelAnnouncement {
1902 features: ChannelFeatures::known(),
1903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1904 short_channel_id: 0,
1907 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1908 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1909 excess_data: Vec::new(),
1912 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1913 let valid_announcement = ChannelAnnouncement {
1914 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1915 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1916 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1917 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1918 contents: unsigned_announcement.clone(),
1920 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1921 Ok(res) => assert!(res),
1926 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1927 let unsigned_announcement = UnsignedNodeAnnouncement {
1928 features: NodeFeatures::known(),
1933 addresses: Vec::new(),
1934 excess_address_data: Vec::new(),
1935 excess_data: Vec::new(),
1937 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1938 let valid_announcement = NodeAnnouncement {
1939 signature: secp_ctx.sign(&msghash, node_1_privkey),
1940 contents: unsigned_announcement.clone()
1943 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1948 let network = net_graph_msg_handler.network_graph.write().unwrap();
1949 let mut w = test_utils::TestVecWriter(Vec::new());
1950 assert!(!network.get_nodes().is_empty());
1951 assert!(!network.get_channels().is_empty());
1952 network.write(&mut w).unwrap();
1953 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1957 fn calling_sync_routing_table() {
1958 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1959 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1960 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
1962 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1963 let first_blocknum = 0;
1964 let number_of_blocks = 0xffff_ffff;
1966 // It should ignore if gossip_queries feature is not enabled
1968 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
1969 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1970 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1971 assert_eq!(events.len(), 0);
1974 // It should send a query_channel_message with the correct information
1976 let init_msg = Init { features: InitFeatures::known() };
1977 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
1978 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1979 assert_eq!(events.len(), 1);
1981 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
1982 assert_eq!(node_id, &node_id_1);
1983 assert_eq!(msg.chain_hash, chain_hash);
1984 assert_eq!(msg.first_blocknum, first_blocknum);
1985 assert_eq!(msg.number_of_blocks, number_of_blocks);
1987 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
1991 // It should not enqueue a query when should_request_full_sync return false.
1992 // The initial implementation allows syncing with the first 5 peers after
1993 // which should_request_full_sync will return false
1995 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1996 let init_msg = Init { features: InitFeatures::known() };
1998 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
1999 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2000 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2001 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2003 assert_eq!(events.len(), 1);
2005 assert_eq!(events.len(), 0);
2013 fn handling_reply_channel_range() {
2014 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2015 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2016 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2018 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2020 // Test receipt of a single reply that should enqueue an SCID query
2021 // matching the SCIDs in the reply
2023 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2025 sync_complete: true,
2027 number_of_blocks: 2000,
2028 short_channel_ids: vec![
2029 0x0003e0_000000_0000, // 992x0x0
2030 0x0003e8_000000_0000, // 1000x0x0
2031 0x0003e9_000000_0000, // 1001x0x0
2032 0x0003f0_000000_0000, // 1008x0x0
2033 0x00044c_000000_0000, // 1100x0x0
2034 0x0006e0_000000_0000, // 1760x0x0
2037 assert!(result.is_ok());
2039 // We expect to emit a query_short_channel_ids message with the received scids
2040 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2041 assert_eq!(events.len(), 1);
2043 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2044 assert_eq!(node_id, &node_id_1);
2045 assert_eq!(msg.chain_hash, chain_hash);
2046 assert_eq!(msg.short_channel_ids, vec![
2047 0x0003e0_000000_0000, // 992x0x0
2048 0x0003e8_000000_0000, // 1000x0x0
2049 0x0003e9_000000_0000, // 1001x0x0
2050 0x0003f0_000000_0000, // 1008x0x0
2051 0x00044c_000000_0000, // 1100x0x0
2052 0x0006e0_000000_0000, // 1760x0x0
2055 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2061 fn handling_reply_short_channel_ids() {
2062 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2063 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2064 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2066 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2068 // Test receipt of a successful reply
2070 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2072 full_information: true,
2074 assert!(result.is_ok());
2077 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2078 // for the chain_hash requested in the query.
2080 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2082 full_information: false,
2084 assert!(result.is_err());
2085 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2090 fn handling_query_channel_range() {
2091 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2092 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2093 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2095 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2097 let result = net_graph_msg_handler.handle_query_channel_range(&node_id, QueryChannelRange {
2100 number_of_blocks: 0xffff_ffff,
2102 assert!(result.is_err());
2106 fn handling_query_short_channel_ids() {
2107 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2108 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2109 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2111 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2113 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2115 short_channel_ids: vec![0x0003e8_000000_0000],
2117 assert!(result.is_err());