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, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
27 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
28 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use util::ser::{Writeable, Readable, Writer};
31 use util::logger::Logger;
35 use std::sync::{RwLock, RwLockReadGuard};
36 use std::sync::atomic::{AtomicUsize, Ordering};
38 use std::collections::BTreeMap;
39 use std::collections::btree_map::Entry as BtreeEntry;
41 use bitcoin::hashes::hex::ToHex;
43 /// Represents the network as nodes and channels between them
45 pub struct NetworkGraph {
46 genesis_hash: BlockHash,
47 channels: BTreeMap<u64, ChannelInfo>,
48 nodes: BTreeMap<PublicKey, NodeInfo>,
51 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
52 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
53 /// the C bindings, as it can be done directly in Rust code.
54 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
56 /// Receives and validates network updates from peers,
57 /// stores authentic and relevant data as a network graph.
58 /// This network graph is then used for routing payments.
59 /// Provides interface to help with initial routing sync by
60 /// serving historical announcements.
61 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
62 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
63 /// Representation of the payment channel network
64 pub network_graph: RwLock<NetworkGraph>,
65 chain_access: Option<C>,
66 full_syncs_requested: AtomicUsize,
67 pending_events: Mutex<Vec<events::MessageSendEvent>>,
71 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
72 /// Creates a new tracker of the actual state of the network of channels and nodes,
73 /// assuming a fresh network graph.
74 /// Chain monitor is used to make sure announced channels exist on-chain,
75 /// channel data is correct, and that the announcement is signed with
76 /// channel owners' keys.
77 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
79 secp_ctx: Secp256k1::verification_only(),
80 network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
81 full_syncs_requested: AtomicUsize::new(0),
83 pending_events: Mutex::new(vec![]),
88 /// Creates a new tracker of the actual state of the network of channels and nodes,
89 /// assuming an existing Network Graph.
90 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
92 secp_ctx: Secp256k1::verification_only(),
93 network_graph: RwLock::new(network_graph),
94 full_syncs_requested: AtomicUsize::new(0),
96 pending_events: Mutex::new(vec![]),
101 /// Take a read lock on the network_graph and return it in the C-bindings
102 /// newtype helper. This is likely only useful when called via the C
103 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
105 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
106 LockedNetworkGraph(self.network_graph.read().unwrap())
110 impl<'a> LockedNetworkGraph<'a> {
111 /// Get a reference to the NetworkGraph which this read-lock contains.
112 pub fn graph(&self) -> &NetworkGraph {
118 macro_rules! secp_verify_sig {
119 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
120 match $secp_ctx.verify($msg, $sig, $pubkey) {
122 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
127 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
128 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
129 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
130 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty())
133 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
134 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
135 log_trace!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
136 Ok(msg.contents.excess_data.is_empty())
139 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
141 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
142 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
144 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
145 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
147 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
148 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
153 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
154 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
155 Ok(msg.contents.excess_data.is_empty())
158 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
159 let network_graph = self.network_graph.read().unwrap();
160 let mut result = Vec::with_capacity(batch_amount as usize);
161 let mut iter = network_graph.get_channels().range(starting_point..);
162 while result.len() < batch_amount as usize {
163 if let Some((_, ref chan)) = iter.next() {
164 if chan.announcement_message.is_some() {
165 let chan_announcement = chan.announcement_message.clone().unwrap();
166 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
167 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
168 if let Some(one_to_two) = chan.one_to_two.as_ref() {
169 one_to_two_announcement = one_to_two.last_update_message.clone();
171 if let Some(two_to_one) = chan.two_to_one.as_ref() {
172 two_to_one_announcement = two_to_one.last_update_message.clone();
174 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
176 // TODO: We may end up sending un-announced channel_updates if we are sending
177 // initial sync data while receiving announce/updates for this channel.
186 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
187 let network_graph = self.network_graph.read().unwrap();
188 let mut result = Vec::with_capacity(batch_amount as usize);
189 let mut iter = if let Some(pubkey) = starting_point {
190 let mut iter = network_graph.get_nodes().range((*pubkey)..);
194 network_graph.get_nodes().range(..)
196 while result.len() < batch_amount as usize {
197 if let Some((_, ref node)) = iter.next() {
198 if let Some(node_info) = node.announcement_info.as_ref() {
199 if node_info.announcement_message.is_some() {
200 result.push(node_info.announcement_message.clone().unwrap());
210 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
211 //TODO: Determine whether to request a full sync based on the network map.
212 const FULL_SYNCS_TO_REQUEST: usize = 5;
213 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
214 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
221 /// Initiates a stateless sync of routing gossip information with a peer
222 /// by calling query_channel_range. The default strategy used by this
223 /// implementation is to sync for the full block range with several peers.
224 /// We should expect one or more reply_channel_range messages in response
225 /// to our query. Each reply will enqueue a query_scid message to request
226 /// gossip messages for each channel. The sync is considered complete when
227 /// the final reply_scids_end message is received, though we are not
228 /// tracking this directly.
229 fn sync_routing_table(&self, their_node_id: &PublicKey) {
230 let first_blocknum = 0;
231 let number_of_blocks = 0xffffffff;
232 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
233 let mut pending_events = self.pending_events.lock().unwrap();
234 pending_events.push(events::MessageSendEvent::SendChannelRangeQuery {
235 node_id: their_node_id.clone(),
236 msg: QueryChannelRange {
237 chain_hash: self.network_graph.read().unwrap().genesis_hash,
244 /// Statelessly processes a reply to a channel range query by immediately
245 /// sending an SCID query with SCIDs in the reply. To keep this handler
246 /// stateless, it does not validate the sequencing of replies for multi-
247 /// reply ranges. It does not validate whether the reply(ies) cover the
248 /// queried range. It also does not filter SCIDs to only those in the
249 /// original query range.
250 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
251 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(),);
253 // Validate that the remote node maintains up-to-date channel
254 // information for chain_hash. Some nodes use the full_information
255 // flag to indicate multi-part messages so we must check whether
256 // we received SCIDs as well.
257 if !msg.full_information && msg.short_channel_ids.len() == 0 {
258 return Err(LightningError {
259 err: String::from("Received reply_channel_range with no information available"),
260 action: ErrorAction::IgnoreError,
264 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
265 let mut pending_events = self.pending_events.lock().unwrap();
266 pending_events.push(events::MessageSendEvent::SendShortIdsQuery {
267 node_id: their_node_id.clone(),
268 msg: QueryShortChannelIds {
269 chain_hash: msg.chain_hash,
270 short_channel_ids: msg.short_channel_ids,
277 /// When an SCID query is initiated the remote peer will begin streaming
278 /// gossip messages. In the event of a failure, we may have received
279 /// some channel information. Before trying with another peer, the
280 /// caller should update its set of SCIDs that need to be queried.
281 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
282 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
284 // If the remote node does not have up-to-date information for the
285 // chain_hash they will set full_information=false. We can fail
286 // the result and try again with a different peer.
287 if !msg.full_information {
288 return Err(LightningError {
289 err: String::from("Received reply_short_channel_ids_end with no information"),
290 action: ErrorAction::IgnoreError
297 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: QueryChannelRange) -> Result<(), LightningError> {
300 err: String::from("Not implemented"),
301 action: ErrorAction::IgnoreError,
305 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
308 err: String::from("Not implemented"),
309 action: ErrorAction::IgnoreError,
314 impl<C: Deref, L: Deref> events::MessageSendEventsProvider for NetGraphMsgHandler<C, L>
316 C::Target: chain::Access,
319 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
320 let mut ret = Vec::new();
321 let mut pending_events = self.pending_events.lock().unwrap();
322 std::mem::swap(&mut ret, &mut pending_events);
327 #[derive(PartialEq, Debug)]
328 /// Details about one direction of a channel. Received
329 /// within a channel update.
330 pub struct DirectionalChannelInfo {
331 /// When the last update to the channel direction was issued.
332 /// Value is opaque, as set in the announcement.
333 pub last_update: u32,
334 /// Whether the channel can be currently used for payments (in this one direction).
336 /// The difference in CLTV values that you must have when routing through this channel.
337 pub cltv_expiry_delta: u16,
338 /// The minimum value, which must be relayed to the next hop via the channel
339 pub htlc_minimum_msat: u64,
340 /// The maximum value which may be relayed to the next hop via the channel.
341 pub htlc_maximum_msat: Option<u64>,
342 /// Fees charged when the channel is used for routing
343 pub fees: RoutingFees,
344 /// Most recent update for the channel received from the network
345 /// Mostly redundant with the data we store in fields explicitly.
346 /// Everything else is useful only for sending out for initial routing sync.
347 /// Not stored if contains excess data to prevent DoS.
348 pub last_update_message: Option<ChannelUpdate>,
351 impl fmt::Display for DirectionalChannelInfo {
352 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
353 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)?;
358 impl_writeable!(DirectionalChannelInfo, 0, {
369 /// Details about a channel (both directions).
370 /// Received within a channel announcement.
371 pub struct ChannelInfo {
372 /// Protocol features of a channel communicated during its announcement
373 pub features: ChannelFeatures,
374 /// Source node of the first direction of a channel
375 pub node_one: PublicKey,
376 /// Details about the first direction of a channel
377 pub one_to_two: Option<DirectionalChannelInfo>,
378 /// Source node of the second direction of a channel
379 pub node_two: PublicKey,
380 /// Details about the second direction of a channel
381 pub two_to_one: Option<DirectionalChannelInfo>,
382 /// The channel capacity as seen on-chain, if chain lookup is available.
383 pub capacity_sats: Option<u64>,
384 /// An initial announcement of the channel
385 /// Mostly redundant with the data we store in fields explicitly.
386 /// Everything else is useful only for sending out for initial routing sync.
387 /// Not stored if contains excess data to prevent DoS.
388 pub announcement_message: Option<ChannelAnnouncement>,
391 impl fmt::Display for ChannelInfo {
392 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
393 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
394 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
399 impl_writeable!(ChannelInfo, 0, {
410 /// Fees for routing via a given channel or a node
411 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
412 pub struct RoutingFees {
413 /// Flat routing fee in satoshis
415 /// Liquidity-based routing fee in millionths of a routed amount.
416 /// In other words, 10000 is 1%.
417 pub proportional_millionths: u32,
420 impl Readable for RoutingFees{
421 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
422 let base_msat: u32 = Readable::read(reader)?;
423 let proportional_millionths: u32 = Readable::read(reader)?;
426 proportional_millionths,
431 impl Writeable for RoutingFees {
432 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
433 self.base_msat.write(writer)?;
434 self.proportional_millionths.write(writer)?;
439 #[derive(PartialEq, Debug)]
440 /// Information received in the latest node_announcement from this node.
441 pub struct NodeAnnouncementInfo {
442 /// Protocol features the node announced support for
443 pub features: NodeFeatures,
444 /// When the last known update to the node state was issued.
445 /// Value is opaque, as set in the announcement.
446 pub last_update: u32,
447 /// Color assigned to the node
449 /// Moniker assigned to the node.
450 /// May be invalid or malicious (eg control chars),
451 /// should not be exposed to the user.
453 /// Internet-level addresses via which one can connect to the node
454 pub addresses: Vec<NetAddress>,
455 /// An initial announcement of the node
456 /// Mostly redundant with the data we store in fields explicitly.
457 /// Everything else is useful only for sending out for initial routing sync.
458 /// Not stored if contains excess data to prevent DoS.
459 pub announcement_message: Option<NodeAnnouncement>
462 impl Writeable for NodeAnnouncementInfo {
463 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
464 self.features.write(writer)?;
465 self.last_update.write(writer)?;
466 self.rgb.write(writer)?;
467 self.alias.write(writer)?;
468 (self.addresses.len() as u64).write(writer)?;
469 for ref addr in &self.addresses {
472 self.announcement_message.write(writer)?;
477 impl Readable for NodeAnnouncementInfo {
478 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
479 let features = Readable::read(reader)?;
480 let last_update = Readable::read(reader)?;
481 let rgb = Readable::read(reader)?;
482 let alias = Readable::read(reader)?;
483 let addresses_count: u64 = Readable::read(reader)?;
484 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
485 for _ in 0..addresses_count {
486 match Readable::read(reader) {
487 Ok(Ok(addr)) => { addresses.push(addr); },
488 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
489 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
493 let announcement_message = Readable::read(reader)?;
494 Ok(NodeAnnouncementInfo {
506 /// Details about a node in the network, known from the network announcement.
507 pub struct NodeInfo {
508 /// All valid channels a node has announced
509 pub channels: Vec<u64>,
510 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
511 /// The two fields (flat and proportional fee) are independent,
512 /// meaning they don't have to refer to the same channel.
513 pub lowest_inbound_channel_fees: Option<RoutingFees>,
514 /// More information about a node from node_announcement.
515 /// Optional because we store a Node entry after learning about it from
516 /// a channel announcement, but before receiving a node announcement.
517 pub announcement_info: Option<NodeAnnouncementInfo>
520 impl fmt::Display for NodeInfo {
521 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
522 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
523 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
528 impl Writeable for NodeInfo {
529 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
530 (self.channels.len() as u64).write(writer)?;
531 for ref chan in self.channels.iter() {
534 self.lowest_inbound_channel_fees.write(writer)?;
535 self.announcement_info.write(writer)?;
540 const MAX_ALLOC_SIZE: u64 = 64*1024;
542 impl Readable for NodeInfo {
543 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
544 let channels_count: u64 = Readable::read(reader)?;
545 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
546 for _ in 0..channels_count {
547 channels.push(Readable::read(reader)?);
549 let lowest_inbound_channel_fees = Readable::read(reader)?;
550 let announcement_info = Readable::read(reader)?;
553 lowest_inbound_channel_fees,
559 impl Writeable for NetworkGraph {
560 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
561 self.genesis_hash.write(writer)?;
562 (self.channels.len() as u64).write(writer)?;
563 for (ref chan_id, ref chan_info) in self.channels.iter() {
564 (*chan_id).write(writer)?;
565 chan_info.write(writer)?;
567 (self.nodes.len() as u64).write(writer)?;
568 for (ref node_id, ref node_info) in self.nodes.iter() {
569 node_id.write(writer)?;
570 node_info.write(writer)?;
576 impl Readable for NetworkGraph {
577 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
578 let genesis_hash: BlockHash = Readable::read(reader)?;
579 let channels_count: u64 = Readable::read(reader)?;
580 let mut channels = BTreeMap::new();
581 for _ in 0..channels_count {
582 let chan_id: u64 = Readable::read(reader)?;
583 let chan_info = Readable::read(reader)?;
584 channels.insert(chan_id, chan_info);
586 let nodes_count: u64 = Readable::read(reader)?;
587 let mut nodes = BTreeMap::new();
588 for _ in 0..nodes_count {
589 let node_id = Readable::read(reader)?;
590 let node_info = Readable::read(reader)?;
591 nodes.insert(node_id, node_info);
601 impl fmt::Display for NetworkGraph {
602 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
603 writeln!(f, "Network map\n[Channels]")?;
604 for (key, val) in self.channels.iter() {
605 writeln!(f, " {}: {}", key, val)?;
607 writeln!(f, "[Nodes]")?;
608 for (key, val) in self.nodes.iter() {
609 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
616 /// Returns all known valid channels' short ids along with announced channel info.
618 /// (C-not exported) because we have no mapping for `BTreeMap`s
619 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
620 /// Returns all known nodes' public keys along with announced node info.
622 /// (C-not exported) because we have no mapping for `BTreeMap`s
623 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
625 /// Get network addresses by node id.
626 /// Returns None if the requested node is completely unknown,
627 /// or if node announcement for the node was never received.
629 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
630 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
631 if let Some(node) = self.nodes.get(pubkey) {
632 if let Some(node_info) = node.announcement_info.as_ref() {
633 return Some(&node_info.addresses)
639 /// Creates a new, empty, network graph.
640 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
643 channels: BTreeMap::new(),
644 nodes: BTreeMap::new(),
648 /// For an already known node (from channel announcements), update its stored properties from a
649 /// given node announcement.
651 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
652 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
653 /// routing messages from a source using a protocol other than the lightning P2P protocol.
654 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
655 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
656 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
657 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
660 /// For an already known node (from channel announcements), update its stored properties from a
661 /// given node announcement without verifying the associated signatures. Because we aren't
662 /// given the associated signatures here we cannot relay the node announcement to any of our
664 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
665 self.update_node_from_announcement_intern(msg, None)
668 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
669 match self.nodes.get_mut(&msg.node_id) {
670 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
672 if let Some(node_info) = node.announcement_info.as_ref() {
673 if node_info.last_update >= msg.timestamp {
674 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
678 let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
679 node.announcement_info = Some(NodeAnnouncementInfo {
680 features: msg.features.clone(),
681 last_update: msg.timestamp,
684 addresses: msg.addresses.clone(),
685 announcement_message: if should_relay { full_msg.cloned() } else { None },
693 /// Store or update channel info from a channel announcement.
695 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
696 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
697 /// routing messages from a source using a protocol other than the lightning P2P protocol.
699 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
700 /// the corresponding UTXO exists on chain and is correctly-formatted.
701 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
702 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
703 -> Result<(), LightningError>
704 where C::Target: chain::Access {
705 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
706 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
707 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
708 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
709 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
710 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
713 /// Store or update channel info from a channel announcement without verifying the associated
714 /// signatures. Because we aren't given the associated signatures here we cannot relay the
715 /// channel announcement to any of our peers.
717 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
718 /// the corresponding UTXO exists on chain and is correctly-formatted.
719 pub fn update_channel_from_unsigned_announcement<C: Deref>
720 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
721 -> Result<(), LightningError>
722 where C::Target: chain::Access {
723 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
726 fn update_channel_from_unsigned_announcement_intern<C: Deref>
727 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
728 -> Result<(), LightningError>
729 where C::Target: chain::Access {
730 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
731 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
734 let utxo_value = match &chain_access {
736 // Tentatively accept, potentially exposing us to DoS attacks
739 &Some(ref chain_access) => {
740 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
741 Ok(TxOut { value, script_pubkey }) => {
742 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
743 .push_slice(&msg.bitcoin_key_1.serialize())
744 .push_slice(&msg.bitcoin_key_2.serialize())
745 .push_opcode(opcodes::all::OP_PUSHNUM_2)
746 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
747 if script_pubkey != expected_script {
748 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});
750 //TODO: Check if value is worth storing, use it to inform routing, and compare it
751 //to the new HTLC max field in channel_update
754 Err(chain::AccessError::UnknownChain) => {
755 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
757 Err(chain::AccessError::UnknownTx) => {
758 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
764 let chan_info = ChannelInfo {
765 features: msg.features.clone(),
766 node_one: msg.node_id_1.clone(),
768 node_two: msg.node_id_2.clone(),
770 capacity_sats: utxo_value,
771 announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
774 match self.channels.entry(msg.short_channel_id) {
775 BtreeEntry::Occupied(mut entry) => {
776 //TODO: because asking the blockchain if short_channel_id is valid is only optional
777 //in the blockchain API, we need to handle it smartly here, though it's unclear
779 if utxo_value.is_some() {
780 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
781 // only sometimes returns results. In any case remove the previous entry. Note
782 // that the spec expects us to "blacklist" the node_ids involved, but we can't
784 // a) we don't *require* a UTXO provider that always returns results.
785 // b) we don't track UTXOs of channels we know about and remove them if they
787 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
788 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
789 *entry.get_mut() = chan_info;
791 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
794 BtreeEntry::Vacant(entry) => {
795 entry.insert(chan_info);
799 macro_rules! add_channel_to_node {
800 ( $node_id: expr ) => {
801 match self.nodes.entry($node_id) {
802 BtreeEntry::Occupied(node_entry) => {
803 node_entry.into_mut().channels.push(msg.short_channel_id);
805 BtreeEntry::Vacant(node_entry) => {
806 node_entry.insert(NodeInfo {
807 channels: vec!(msg.short_channel_id),
808 lowest_inbound_channel_fees: None,
809 announcement_info: None,
816 add_channel_to_node!(msg.node_id_1);
817 add_channel_to_node!(msg.node_id_2);
822 /// Close a channel if a corresponding HTLC fail was sent.
823 /// If permanent, removes a channel from the local storage.
824 /// May cause the removal of nodes too, if this was their last channel.
825 /// If not permanent, makes channels unavailable for routing.
826 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
828 if let Some(chan) = self.channels.remove(&short_channel_id) {
829 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
832 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
833 if let Some(one_to_two) = chan.one_to_two.as_mut() {
834 one_to_two.enabled = false;
836 if let Some(two_to_one) = chan.two_to_one.as_mut() {
837 two_to_one.enabled = false;
843 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
845 // TODO: Wholly remove the node
847 // TODO: downgrade the node
851 /// For an already known (from announcement) channel, update info about one of the directions
854 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
855 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
856 /// routing messages from a source using a protocol other than the lightning P2P protocol.
857 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
858 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
861 /// For an already known (from announcement) channel, update info about one of the directions
862 /// of the channel without verifying the associated signatures. Because we aren't given the
863 /// associated signatures here we cannot relay the channel update to any of our peers.
864 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
865 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
868 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> {
870 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
871 let chan_was_enabled;
873 match self.channels.get_mut(&msg.short_channel_id) {
874 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
876 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
877 if htlc_maximum_msat > MAX_VALUE_MSAT {
878 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
881 if let Some(capacity_sats) = channel.capacity_sats {
882 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
883 // Don't query UTXO set here to reduce DoS risks.
884 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
885 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
889 macro_rules! maybe_update_channel_info {
890 ( $target: expr, $src_node: expr) => {
891 if let Some(existing_chan_info) = $target.as_ref() {
892 if existing_chan_info.last_update >= msg.timestamp {
893 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
895 chan_was_enabled = existing_chan_info.enabled;
897 chan_was_enabled = false;
900 let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
902 let updated_channel_dir_info = DirectionalChannelInfo {
903 enabled: chan_enabled,
904 last_update: msg.timestamp,
905 cltv_expiry_delta: msg.cltv_expiry_delta,
906 htlc_minimum_msat: msg.htlc_minimum_msat,
907 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
909 base_msat: msg.fee_base_msat,
910 proportional_millionths: msg.fee_proportional_millionths,
914 $target = Some(updated_channel_dir_info);
918 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
919 if msg.flags & 1 == 1 {
920 dest_node_id = channel.node_one.clone();
921 if let Some((sig, ctx)) = sig_info {
922 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
924 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
926 dest_node_id = channel.node_two.clone();
927 if let Some((sig, ctx)) = sig_info {
928 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
930 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
936 let node = self.nodes.get_mut(&dest_node_id).unwrap();
937 let mut base_msat = msg.fee_base_msat;
938 let mut proportional_millionths = msg.fee_proportional_millionths;
939 if let Some(fees) = node.lowest_inbound_channel_fees {
940 base_msat = cmp::min(base_msat, fees.base_msat);
941 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
943 node.lowest_inbound_channel_fees = Some(RoutingFees {
945 proportional_millionths
947 } else if chan_was_enabled {
948 let node = self.nodes.get_mut(&dest_node_id).unwrap();
949 let mut lowest_inbound_channel_fees = None;
951 for chan_id in node.channels.iter() {
952 let chan = self.channels.get(chan_id).unwrap();
954 if chan.node_one == dest_node_id {
955 chan_info_opt = chan.two_to_one.as_ref();
957 chan_info_opt = chan.one_to_two.as_ref();
959 if let Some(chan_info) = chan_info_opt {
960 if chan_info.enabled {
961 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
962 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
963 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
964 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
969 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
975 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
976 macro_rules! remove_from_node {
977 ($node_id: expr) => {
978 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
979 entry.get_mut().channels.retain(|chan_id| {
980 short_channel_id != *chan_id
982 if entry.get().channels.is_empty() {
983 entry.remove_entry();
986 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
991 remove_from_node!(chan.node_one);
992 remove_from_node!(chan.node_two);
999 use ln::features::{ChannelFeatures, NodeFeatures};
1000 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
1001 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1002 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1003 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1004 use util::test_utils;
1005 use util::logger::Logger;
1006 use util::ser::{Readable, Writeable};
1007 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1009 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1010 use bitcoin::hashes::Hash;
1011 use bitcoin::network::constants::Network;
1012 use bitcoin::blockdata::constants::genesis_block;
1013 use bitcoin::blockdata::script::Builder;
1014 use bitcoin::blockdata::transaction::TxOut;
1015 use bitcoin::blockdata::opcodes;
1019 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1020 use bitcoin::secp256k1::{All, Secp256k1};
1024 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1025 let secp_ctx = Secp256k1::new();
1026 let logger = Arc::new(test_utils::TestLogger::new());
1027 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1028 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1029 (secp_ctx, net_graph_msg_handler)
1033 fn request_full_sync_finite_times() {
1034 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1035 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1037 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1038 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1039 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1040 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1041 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1042 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1046 fn handling_node_announcements() {
1047 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1049 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1050 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1051 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1052 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1053 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1054 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1055 let zero_hash = Sha256dHash::hash(&[0; 32]);
1056 let first_announcement_time = 500;
1058 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1059 features: NodeFeatures::known(),
1060 timestamp: first_announcement_time,
1064 addresses: Vec::new(),
1065 excess_address_data: Vec::new(),
1066 excess_data: Vec::new(),
1068 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1069 let valid_announcement = NodeAnnouncement {
1070 signature: secp_ctx.sign(&msghash, node_1_privkey),
1071 contents: unsigned_announcement.clone()
1074 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1076 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1080 // Announce a channel to add a corresponding node.
1081 let unsigned_announcement = UnsignedChannelAnnouncement {
1082 features: ChannelFeatures::known(),
1083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1084 short_channel_id: 0,
1087 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1088 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1089 excess_data: Vec::new(),
1092 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1093 let valid_announcement = ChannelAnnouncement {
1094 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1095 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1096 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1097 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1098 contents: unsigned_announcement.clone(),
1100 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1101 Ok(res) => assert!(res),
1106 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1107 Ok(res) => assert!(res),
1111 let fake_msghash = hash_to_message!(&zero_hash);
1112 match net_graph_msg_handler.handle_node_announcement(
1114 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1115 contents: unsigned_announcement.clone()
1118 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1121 unsigned_announcement.timestamp += 1000;
1122 unsigned_announcement.excess_data.push(1);
1123 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1124 let announcement_with_data = NodeAnnouncement {
1125 signature: secp_ctx.sign(&msghash, node_1_privkey),
1126 contents: unsigned_announcement.clone()
1128 // Return false because contains excess data.
1129 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1130 Ok(res) => assert!(!res),
1133 unsigned_announcement.excess_data = Vec::new();
1135 // Even though previous announcement was not relayed further, we still accepted it,
1136 // so we now won't accept announcements before the previous one.
1137 unsigned_announcement.timestamp -= 10;
1138 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1139 let outdated_announcement = NodeAnnouncement {
1140 signature: secp_ctx.sign(&msghash, node_1_privkey),
1141 contents: unsigned_announcement.clone()
1143 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1145 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1150 fn handling_channel_announcements() {
1151 let secp_ctx = Secp256k1::new();
1152 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1154 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1155 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1156 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1157 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1158 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1159 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1161 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1162 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1163 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1164 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1165 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1168 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1169 features: ChannelFeatures::known(),
1170 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1171 short_channel_id: 0,
1174 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1175 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1176 excess_data: Vec::new(),
1179 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1180 let valid_announcement = ChannelAnnouncement {
1181 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1182 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1183 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1184 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1185 contents: unsigned_announcement.clone(),
1188 // Test if the UTXO lookups were not supported
1189 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1190 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1191 Ok(res) => assert!(res),
1196 let network = net_graph_msg_handler.network_graph.read().unwrap();
1197 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1203 // If we receive announcement for the same channel (with UTXO lookups disabled),
1204 // drop new one on the floor, since we can't see any changes.
1205 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1207 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1210 // Test if an associated transaction were not on-chain (or not confirmed).
1211 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1212 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1213 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1214 unsigned_announcement.short_channel_id += 1;
1216 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1217 let valid_announcement = ChannelAnnouncement {
1218 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1219 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1220 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1221 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1222 contents: unsigned_announcement.clone(),
1225 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1227 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1230 // Now test if the transaction is found in the UTXO set and the script is correct.
1231 unsigned_announcement.short_channel_id += 1;
1232 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1234 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1235 let valid_announcement = ChannelAnnouncement {
1236 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1237 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1238 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1239 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1240 contents: unsigned_announcement.clone(),
1242 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1243 Ok(res) => assert!(res),
1248 let network = net_graph_msg_handler.network_graph.read().unwrap();
1249 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1255 // If we receive announcement for the same channel (but TX is not confirmed),
1256 // drop new one on the floor, since we can't see any changes.
1257 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1258 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1260 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1263 // But if it is confirmed, replace the channel
1264 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1265 unsigned_announcement.features = ChannelFeatures::empty();
1266 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1267 let valid_announcement = ChannelAnnouncement {
1268 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1269 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1270 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1271 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1272 contents: unsigned_announcement.clone(),
1274 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1275 Ok(res) => assert!(res),
1279 let network = net_graph_msg_handler.network_graph.read().unwrap();
1280 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1281 Some(channel_entry) => {
1282 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1288 // Don't relay valid channels with excess data
1289 unsigned_announcement.short_channel_id += 1;
1290 unsigned_announcement.excess_data.push(1);
1291 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1292 let valid_announcement = ChannelAnnouncement {
1293 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1294 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1295 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1296 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1297 contents: unsigned_announcement.clone(),
1299 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1300 Ok(res) => assert!(!res),
1304 unsigned_announcement.excess_data = Vec::new();
1305 let invalid_sig_announcement = ChannelAnnouncement {
1306 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1307 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1308 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1309 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1310 contents: unsigned_announcement.clone(),
1312 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1314 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1317 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1318 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1319 let channel_to_itself_announcement = ChannelAnnouncement {
1320 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1321 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1322 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1323 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1324 contents: unsigned_announcement.clone(),
1326 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1328 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1333 fn handling_channel_update() {
1334 let secp_ctx = Secp256k1::new();
1335 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1336 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1337 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1339 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1340 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1341 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1342 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1343 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1344 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1346 let zero_hash = Sha256dHash::hash(&[0; 32]);
1347 let short_channel_id = 0;
1348 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1349 let amount_sats = 1000_000;
1352 // Announce a channel we will update
1353 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1354 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1355 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1356 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1357 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1358 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1359 let unsigned_announcement = UnsignedChannelAnnouncement {
1360 features: ChannelFeatures::empty(),
1365 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1366 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1367 excess_data: Vec::new(),
1370 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1371 let valid_channel_announcement = ChannelAnnouncement {
1372 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1373 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1374 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1375 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1376 contents: unsigned_announcement.clone(),
1378 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1385 let mut unsigned_channel_update = UnsignedChannelUpdate {
1390 cltv_expiry_delta: 144,
1391 htlc_minimum_msat: 1000000,
1392 htlc_maximum_msat: OptionalField::Absent,
1393 fee_base_msat: 10000,
1394 fee_proportional_millionths: 20,
1395 excess_data: Vec::new()
1397 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1398 let valid_channel_update = ChannelUpdate {
1399 signature: secp_ctx.sign(&msghash, node_1_privkey),
1400 contents: unsigned_channel_update.clone()
1403 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1404 Ok(res) => assert!(res),
1409 let network = net_graph_msg_handler.network_graph.read().unwrap();
1410 match network.get_channels().get(&short_channel_id) {
1412 Some(channel_info) => {
1413 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1414 assert!(channel_info.two_to_one.is_none());
1419 unsigned_channel_update.timestamp += 100;
1420 unsigned_channel_update.excess_data.push(1);
1421 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1422 let valid_channel_update = ChannelUpdate {
1423 signature: secp_ctx.sign(&msghash, node_1_privkey),
1424 contents: unsigned_channel_update.clone()
1426 // Return false because contains excess data
1427 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1428 Ok(res) => assert!(!res),
1431 unsigned_channel_update.timestamp += 10;
1433 unsigned_channel_update.short_channel_id += 1;
1434 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1435 let valid_channel_update = ChannelUpdate {
1436 signature: secp_ctx.sign(&msghash, node_1_privkey),
1437 contents: unsigned_channel_update.clone()
1440 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1442 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1444 unsigned_channel_update.short_channel_id = short_channel_id;
1446 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1447 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1448 let valid_channel_update = ChannelUpdate {
1449 signature: secp_ctx.sign(&msghash, node_1_privkey),
1450 contents: unsigned_channel_update.clone()
1453 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1455 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1457 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1459 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1460 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1461 let valid_channel_update = ChannelUpdate {
1462 signature: secp_ctx.sign(&msghash, node_1_privkey),
1463 contents: unsigned_channel_update.clone()
1466 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1468 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1470 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1472 // Even though previous update was not relayed further, we still accepted it,
1473 // so we now won't accept update before the previous one.
1474 unsigned_channel_update.timestamp -= 10;
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, "Update older than last processed update")
1485 unsigned_channel_update.timestamp += 500;
1487 let fake_msghash = hash_to_message!(&zero_hash);
1488 let invalid_sig_channel_update = ChannelUpdate {
1489 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1490 contents: unsigned_channel_update.clone()
1493 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1495 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1501 fn handling_htlc_fail_channel_update() {
1502 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1503 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1504 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1505 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1506 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1507 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1508 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1510 let short_channel_id = 0;
1511 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1514 // There is no nodes in the table at the beginning.
1515 let network = net_graph_msg_handler.network_graph.read().unwrap();
1516 assert_eq!(network.get_nodes().len(), 0);
1520 // Announce a channel we will update
1521 let unsigned_announcement = UnsignedChannelAnnouncement {
1522 features: ChannelFeatures::empty(),
1527 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1528 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1529 excess_data: Vec::new(),
1532 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1533 let valid_channel_announcement = ChannelAnnouncement {
1534 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1535 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1536 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1537 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1538 contents: unsigned_announcement.clone(),
1540 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1545 let unsigned_channel_update = UnsignedChannelUpdate {
1550 cltv_expiry_delta: 144,
1551 htlc_minimum_msat: 1000000,
1552 htlc_maximum_msat: OptionalField::Absent,
1553 fee_base_msat: 10000,
1554 fee_proportional_millionths: 20,
1555 excess_data: Vec::new()
1557 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1558 let valid_channel_update = ChannelUpdate {
1559 signature: secp_ctx.sign(&msghash, node_1_privkey),
1560 contents: unsigned_channel_update.clone()
1563 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1564 Ok(res) => assert!(res),
1569 // Non-permanent closing just disables a channel
1571 let network = net_graph_msg_handler.network_graph.read().unwrap();
1572 match network.get_channels().get(&short_channel_id) {
1574 Some(channel_info) => {
1575 assert!(channel_info.one_to_two.is_some());
1580 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1585 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1587 // Non-permanent closing just disables a channel
1589 let network = net_graph_msg_handler.network_graph.read().unwrap();
1590 match network.get_channels().get(&short_channel_id) {
1592 Some(channel_info) => {
1593 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1598 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1603 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1605 // Permanent closing deletes a channel
1607 let network = net_graph_msg_handler.network_graph.read().unwrap();
1608 assert_eq!(network.get_channels().len(), 0);
1609 // Nodes are also deleted because there are no associated channels anymore
1610 assert_eq!(network.get_nodes().len(), 0);
1612 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1616 fn getting_next_channel_announcements() {
1617 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1618 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1619 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1620 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1621 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1622 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1623 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1625 let short_channel_id = 1;
1626 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1628 // Channels were not announced yet.
1629 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1630 assert_eq!(channels_with_announcements.len(), 0);
1633 // Announce a channel we will update
1634 let unsigned_announcement = UnsignedChannelAnnouncement {
1635 features: ChannelFeatures::empty(),
1640 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1641 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1642 excess_data: Vec::new(),
1645 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1646 let valid_channel_announcement = ChannelAnnouncement {
1647 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1648 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1649 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1650 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1651 contents: unsigned_announcement.clone(),
1653 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1659 // Contains initial channel announcement now.
1660 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1661 assert_eq!(channels_with_announcements.len(), 1);
1662 if let Some(channel_announcements) = channels_with_announcements.first() {
1663 let &(_, ref update_1, ref update_2) = channel_announcements;
1664 assert_eq!(update_1, &None);
1665 assert_eq!(update_2, &None);
1672 // Valid channel update
1673 let unsigned_channel_update = UnsignedChannelUpdate {
1678 cltv_expiry_delta: 144,
1679 htlc_minimum_msat: 1000000,
1680 htlc_maximum_msat: OptionalField::Absent,
1681 fee_base_msat: 10000,
1682 fee_proportional_millionths: 20,
1683 excess_data: Vec::new()
1685 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1686 let valid_channel_update = ChannelUpdate {
1687 signature: secp_ctx.sign(&msghash, node_1_privkey),
1688 contents: unsigned_channel_update.clone()
1690 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1696 // Now contains an initial announcement and an update.
1697 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1698 assert_eq!(channels_with_announcements.len(), 1);
1699 if let Some(channel_announcements) = channels_with_announcements.first() {
1700 let &(_, ref update_1, ref update_2) = channel_announcements;
1701 assert_ne!(update_1, &None);
1702 assert_eq!(update_2, &None);
1709 // Channel update with excess data.
1710 let unsigned_channel_update = UnsignedChannelUpdate {
1715 cltv_expiry_delta: 144,
1716 htlc_minimum_msat: 1000000,
1717 htlc_maximum_msat: OptionalField::Absent,
1718 fee_base_msat: 10000,
1719 fee_proportional_millionths: 20,
1720 excess_data: [1; 3].to_vec()
1722 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1723 let valid_channel_update = ChannelUpdate {
1724 signature: secp_ctx.sign(&msghash, node_1_privkey),
1725 contents: unsigned_channel_update.clone()
1727 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1733 // Test that announcements with excess data won't be returned
1734 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1735 assert_eq!(channels_with_announcements.len(), 1);
1736 if let Some(channel_announcements) = channels_with_announcements.first() {
1737 let &(_, ref update_1, ref update_2) = channel_announcements;
1738 assert_eq!(update_1, &None);
1739 assert_eq!(update_2, &None);
1744 // Further starting point have no channels after it
1745 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1746 assert_eq!(channels_with_announcements.len(), 0);
1750 fn getting_next_node_announcements() {
1751 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1752 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1753 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1754 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1755 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1756 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1757 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1759 let short_channel_id = 1;
1760 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1763 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1764 assert_eq!(next_announcements.len(), 0);
1767 // Announce a channel to add 2 nodes
1768 let unsigned_announcement = UnsignedChannelAnnouncement {
1769 features: ChannelFeatures::empty(),
1774 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1775 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1776 excess_data: Vec::new(),
1779 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1780 let valid_channel_announcement = ChannelAnnouncement {
1781 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1782 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1783 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1784 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1785 contents: unsigned_announcement.clone(),
1787 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1794 // Nodes were never announced
1795 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1796 assert_eq!(next_announcements.len(), 0);
1799 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1800 features: NodeFeatures::known(),
1805 addresses: Vec::new(),
1806 excess_address_data: Vec::new(),
1807 excess_data: Vec::new(),
1809 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1810 let valid_announcement = NodeAnnouncement {
1811 signature: secp_ctx.sign(&msghash, node_1_privkey),
1812 contents: unsigned_announcement.clone()
1814 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1819 unsigned_announcement.node_id = node_id_2;
1820 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1821 let valid_announcement = NodeAnnouncement {
1822 signature: secp_ctx.sign(&msghash, node_2_privkey),
1823 contents: unsigned_announcement.clone()
1826 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1832 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1833 assert_eq!(next_announcements.len(), 2);
1835 // Skip the first node.
1836 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1837 assert_eq!(next_announcements.len(), 1);
1840 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1841 let unsigned_announcement = UnsignedNodeAnnouncement {
1842 features: NodeFeatures::known(),
1847 addresses: Vec::new(),
1848 excess_address_data: Vec::new(),
1849 excess_data: [1; 3].to_vec(),
1851 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1852 let valid_announcement = NodeAnnouncement {
1853 signature: secp_ctx.sign(&msghash, node_2_privkey),
1854 contents: unsigned_announcement.clone()
1856 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1857 Ok(res) => assert!(!res),
1862 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1863 assert_eq!(next_announcements.len(), 0);
1867 fn network_graph_serialization() {
1868 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1870 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1871 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1872 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1873 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1875 // Announce a channel to add a corresponding node.
1876 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1877 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1878 let unsigned_announcement = UnsignedChannelAnnouncement {
1879 features: ChannelFeatures::known(),
1880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1881 short_channel_id: 0,
1884 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1885 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1886 excess_data: Vec::new(),
1889 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1890 let valid_announcement = ChannelAnnouncement {
1891 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1892 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1893 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1894 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1895 contents: unsigned_announcement.clone(),
1897 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1898 Ok(res) => assert!(res),
1903 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1904 let unsigned_announcement = UnsignedNodeAnnouncement {
1905 features: NodeFeatures::known(),
1910 addresses: Vec::new(),
1911 excess_address_data: Vec::new(),
1912 excess_data: Vec::new(),
1914 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1915 let valid_announcement = NodeAnnouncement {
1916 signature: secp_ctx.sign(&msghash, node_1_privkey),
1917 contents: unsigned_announcement.clone()
1920 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1925 let network = net_graph_msg_handler.network_graph.write().unwrap();
1926 let mut w = test_utils::TestVecWriter(Vec::new());
1927 assert!(!network.get_nodes().is_empty());
1928 assert!(!network.get_channels().is_empty());
1929 network.write(&mut w).unwrap();
1930 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1934 fn calling_sync_routing_table() {
1935 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1936 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1937 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
1939 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1940 let first_blocknum = 0;
1941 let number_of_blocks = 0xffff_ffff;
1942 net_graph_msg_handler.sync_routing_table(&node_id_1);
1944 // It should send a query_channel_message with the correct information
1945 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1946 assert_eq!(events.len(), 1);
1948 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
1949 assert_eq!(node_id, &node_id_1);
1950 assert_eq!(msg.chain_hash, chain_hash);
1951 assert_eq!(msg.first_blocknum, first_blocknum);
1952 assert_eq!(msg.number_of_blocks, number_of_blocks);
1954 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
1959 fn handling_reply_channel_range() {
1960 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1961 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
1962 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
1964 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1966 // Test receipt of a single reply that should enqueue an SCID query
1967 // matching the SCIDs in the reply
1969 // Handle a single successful reply that encompasses the queried channel range
1970 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
1972 full_information: true,
1974 number_of_blocks: 2000,
1975 short_channel_ids: vec![
1976 0x0003e0_000000_0000, // 992x0x0
1977 0x0003e8_000000_0000, // 1000x0x0
1978 0x0003e9_000000_0000, // 1001x0x0
1979 0x0003f0_000000_0000, // 1008x0x0
1980 0x00044c_000000_0000, // 1100x0x0
1981 0x0006e0_000000_0000, // 1760x0x0
1984 assert!(result.is_ok());
1986 // We expect to emit a query_short_channel_ids message with the received scids
1987 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
1988 assert_eq!(events.len(), 1);
1990 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
1991 assert_eq!(node_id, &node_id_1);
1992 assert_eq!(msg.chain_hash, chain_hash);
1993 assert_eq!(msg.short_channel_ids, vec![
1994 0x0003e0_000000_0000, // 992x0x0
1995 0x0003e8_000000_0000, // 1000x0x0
1996 0x0003e9_000000_0000, // 1001x0x0
1997 0x0003f0_000000_0000, // 1008x0x0
1998 0x00044c_000000_0000, // 1100x0x0
1999 0x0006e0_000000_0000, // 1760x0x0
2002 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2006 // Test receipt of a reply that indicates the remote node does not maintain up-to-date
2007 // information for the chain_hash. Because of discrepancies in implementation we use
2008 // full_information=false and short_channel_ids=[] as the signal.
2010 // Handle the reply indicating the peer was unable to fulfill our request.
2011 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2013 full_information: false,
2014 first_blocknum: 1000,
2015 number_of_blocks: 100,
2016 short_channel_ids: vec![],
2018 assert!(result.is_err());
2019 assert_eq!(result.err().unwrap().err, "Received reply_channel_range with no information available");
2024 fn handling_reply_short_channel_ids() {
2025 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2026 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2027 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2029 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2031 // Test receipt of a successful reply
2033 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2035 full_information: true,
2037 assert!(result.is_ok());
2040 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2041 // for the chain_hash requested in the query.
2043 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2045 full_information: false,
2047 assert!(result.is_err());
2048 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2053 fn handling_query_channel_range() {
2054 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2055 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2056 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2058 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2060 let result = net_graph_msg_handler.handle_query_channel_range(&node_id, QueryChannelRange {
2063 number_of_blocks: 0xffff_ffff,
2065 assert!(result.is_err());
2069 fn handling_query_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 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2078 short_channel_ids: vec![0x0003e8_000000_0000],
2080 assert!(result.is_err());