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};
33 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
36 use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
38 use std::sync::{RwLock, RwLockReadGuard};
39 use core::sync::atomic::{AtomicUsize, Ordering};
42 use bitcoin::hashes::hex::ToHex;
44 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
45 /// refuse to relay the message.
46 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
48 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
49 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
50 const MAX_SCIDS_PER_REPLY: usize = 8000;
52 /// Represents the network as nodes and channels between them
53 #[derive(Clone, PartialEq)]
54 pub struct NetworkGraph {
55 genesis_hash: BlockHash,
56 channels: BTreeMap<u64, ChannelInfo>,
57 nodes: BTreeMap<PublicKey, NodeInfo>,
60 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
61 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
62 /// the C bindings, as it can be done directly in Rust code.
63 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
65 /// Receives and validates network updates from peers,
66 /// stores authentic and relevant data as a network graph.
67 /// This network graph is then used for routing payments.
68 /// Provides interface to help with initial routing sync by
69 /// serving historical announcements.
70 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
71 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
72 /// Representation of the payment channel network
73 pub network_graph: RwLock<NetworkGraph>,
74 chain_access: Option<C>,
75 full_syncs_requested: AtomicUsize,
76 pending_events: Mutex<Vec<MessageSendEvent>>,
80 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
81 /// Creates a new tracker of the actual state of the network of channels and nodes,
82 /// assuming a fresh network graph.
83 /// Chain monitor is used to make sure announced channels exist on-chain,
84 /// channel data is correct, and that the announcement is signed with
85 /// channel owners' keys.
86 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
88 secp_ctx: Secp256k1::verification_only(),
89 network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
90 full_syncs_requested: AtomicUsize::new(0),
92 pending_events: Mutex::new(vec![]),
97 /// Creates a new tracker of the actual state of the network of channels and nodes,
98 /// assuming an existing Network Graph.
99 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
101 secp_ctx: Secp256k1::verification_only(),
102 network_graph: RwLock::new(network_graph),
103 full_syncs_requested: AtomicUsize::new(0),
105 pending_events: Mutex::new(vec![]),
110 /// Adds a provider used to check new announcements. Does not affect
111 /// existing announcements unless they are updated.
112 /// Add, update or remove the provider would replace the current one.
113 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
114 self.chain_access = chain_access;
117 /// Take a read lock on the network_graph and return it in the C-bindings
118 /// newtype helper. This is likely only useful when called via the C
119 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
121 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
122 LockedNetworkGraph(self.network_graph.read().unwrap())
125 /// Returns true when a full routing table sync should be performed with a peer.
126 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
127 //TODO: Determine whether to request a full sync based on the network map.
128 const FULL_SYNCS_TO_REQUEST: usize = 5;
129 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
130 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
138 impl<'a> LockedNetworkGraph<'a> {
139 /// Get a reference to the NetworkGraph which this read-lock contains.
140 pub fn graph(&self) -> &NetworkGraph {
146 macro_rules! secp_verify_sig {
147 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
148 match $secp_ctx.verify($msg, $sig, $pubkey) {
150 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
155 impl<C: Deref , L: Deref > RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
156 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
157 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
158 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
159 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
160 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
163 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
164 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
165 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 { "" });
166 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
169 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
171 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
172 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
174 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
175 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
177 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
178 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
183 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
184 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
185 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
188 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
189 let network_graph = self.network_graph.read().unwrap();
190 let mut result = Vec::with_capacity(batch_amount as usize);
191 let mut iter = network_graph.get_channels().range(starting_point..);
192 while result.len() < batch_amount as usize {
193 if let Some((_, ref chan)) = iter.next() {
194 if chan.announcement_message.is_some() {
195 let chan_announcement = chan.announcement_message.clone().unwrap();
196 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
197 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
198 if let Some(one_to_two) = chan.one_to_two.as_ref() {
199 one_to_two_announcement = one_to_two.last_update_message.clone();
201 if let Some(two_to_one) = chan.two_to_one.as_ref() {
202 two_to_one_announcement = two_to_one.last_update_message.clone();
204 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
206 // TODO: We may end up sending un-announced channel_updates if we are sending
207 // initial sync data while receiving announce/updates for this channel.
216 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
217 let network_graph = self.network_graph.read().unwrap();
218 let mut result = Vec::with_capacity(batch_amount as usize);
219 let mut iter = if let Some(pubkey) = starting_point {
220 let mut iter = network_graph.get_nodes().range((*pubkey)..);
224 network_graph.get_nodes().range(..)
226 while result.len() < batch_amount as usize {
227 if let Some((_, ref node)) = iter.next() {
228 if let Some(node_info) = node.announcement_info.as_ref() {
229 if node_info.announcement_message.is_some() {
230 result.push(node_info.announcement_message.clone().unwrap());
240 /// Initiates a stateless sync of routing gossip information with a peer
241 /// using gossip_queries. The default strategy used by this implementation
242 /// is to sync the full block range with several peers.
244 /// We should expect one or more reply_channel_range messages in response
245 /// to our query_channel_range. Each reply will enqueue a query_scid message
246 /// to request gossip messages for each channel. The sync is considered complete
247 /// when the final reply_scids_end message is received, though we are not
248 /// tracking this directly.
249 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
251 // We will only perform a sync with peers that support gossip_queries.
252 if !init_msg.features.supports_gossip_queries() {
256 // Check if we need to perform a full synchronization with this peer
257 if !self.should_request_full_sync(their_node_id) {
261 let first_blocknum = 0;
262 let number_of_blocks = 0xffffffff;
263 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
264 let mut pending_events = self.pending_events.lock().unwrap();
265 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
266 node_id: their_node_id.clone(),
267 msg: QueryChannelRange {
268 chain_hash: self.network_graph.read().unwrap().genesis_hash,
275 /// Statelessly processes a reply to a channel range query by immediately
276 /// sending an SCID query with SCIDs in the reply. To keep this handler
277 /// stateless, it does not validate the sequencing of replies for multi-
278 /// reply ranges. It does not validate whether the reply(ies) cover the
279 /// queried range. It also does not filter SCIDs to only those in the
280 /// original query range. We also do not validate that the chain_hash
281 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
282 /// does not match our chain_hash will be rejected when the announcement is
284 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
285 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(),);
287 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
288 let mut pending_events = self.pending_events.lock().unwrap();
289 pending_events.push(MessageSendEvent::SendShortIdsQuery {
290 node_id: their_node_id.clone(),
291 msg: QueryShortChannelIds {
292 chain_hash: msg.chain_hash,
293 short_channel_ids: msg.short_channel_ids,
300 /// When an SCID query is initiated the remote peer will begin streaming
301 /// gossip messages. In the event of a failure, we may have received
302 /// some channel information. Before trying with another peer, the
303 /// caller should update its set of SCIDs that need to be queried.
304 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
305 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
307 // If the remote node does not have up-to-date information for the
308 // chain_hash they will set full_information=false. We can fail
309 // the result and try again with a different peer.
310 if !msg.full_information {
311 return Err(LightningError {
312 err: String::from("Received reply_short_channel_ids_end with no information"),
313 action: ErrorAction::IgnoreError
320 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
321 /// are in the specified block range. Due to message size limits, large range
322 /// queries may result in several reply messages. This implementation enqueues
323 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
324 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
325 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
326 /// memory constrained systems.
327 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
328 log_debug!(self.logger, "Handling query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks);
330 let network_graph = self.network_graph.read().unwrap();
332 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
334 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
335 // If so, we manually cap the ending block to avoid this overflow.
336 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
338 // Per spec, we must reply to a query. Send an empty message when things are invalid.
339 if msg.chain_hash != network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
340 let mut pending_events = self.pending_events.lock().unwrap();
341 pending_events.push(MessageSendEvent::SendReplyChannelRange {
342 node_id: their_node_id.clone(),
343 msg: ReplyChannelRange {
344 chain_hash: msg.chain_hash.clone(),
345 first_blocknum: msg.first_blocknum,
346 number_of_blocks: msg.number_of_blocks,
348 short_channel_ids: vec![],
351 return Err(LightningError {
352 err: String::from("query_channel_range could not be processed"),
353 action: ErrorAction::IgnoreError,
357 // Creates channel batches. We are not checking if the channel is routable
358 // (has at least one update). A peer may still want to know the channel
359 // exists even if its not yet routable.
360 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
361 for (_, ref chan) in network_graph.get_channels().range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
362 if let Some(chan_announcement) = &chan.announcement_message {
363 // Construct a new batch if last one is full
364 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
365 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
368 let batch = batches.last_mut().unwrap();
369 batch.push(chan_announcement.contents.short_channel_id);
374 let mut pending_events = self.pending_events.lock().unwrap();
375 let batch_count = batches.len();
376 for (batch_index, batch) in batches.into_iter().enumerate() {
377 // Per spec, the initial first_blocknum needs to be <= the query's first_blocknum and subsequent
378 // must be >= the prior reply. We'll simplify this by using zero since its still spec compliant and
379 // sequence completion is now explicitly.
380 let first_blocknum = 0;
382 // Per spec, the final end_blocknum needs to be >= the query's end_blocknum, so we'll use the
383 // query's value. Prior batches must use the number of blocks that fit into the message. We'll
384 // base this off the last SCID in the batch since we've somewhat abusing first_blocknum.
385 let number_of_blocks = if batch_index == batch_count-1 {
388 block_from_scid(batch.last().unwrap()) + 1
391 // Only true for the last message in a sequence
392 let sync_complete = batch_index == batch_count - 1;
394 pending_events.push(MessageSendEvent::SendReplyChannelRange {
395 node_id: their_node_id.clone(),
396 msg: ReplyChannelRange {
397 chain_hash: msg.chain_hash.clone(),
401 short_channel_ids: batch,
409 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
412 err: String::from("Not implemented"),
413 action: ErrorAction::IgnoreError,
418 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
420 C::Target: chain::Access,
423 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
424 let mut ret = Vec::new();
425 let mut pending_events = self.pending_events.lock().unwrap();
426 core::mem::swap(&mut ret, &mut pending_events);
431 #[derive(Clone, Debug, PartialEq)]
432 /// Details about one direction of a channel. Received
433 /// within a channel update.
434 pub struct DirectionalChannelInfo {
435 /// When the last update to the channel direction was issued.
436 /// Value is opaque, as set in the announcement.
437 pub last_update: u32,
438 /// Whether the channel can be currently used for payments (in this one direction).
440 /// The difference in CLTV values that you must have when routing through this channel.
441 pub cltv_expiry_delta: u16,
442 /// The minimum value, which must be relayed to the next hop via the channel
443 pub htlc_minimum_msat: u64,
444 /// The maximum value which may be relayed to the next hop via the channel.
445 pub htlc_maximum_msat: Option<u64>,
446 /// Fees charged when the channel is used for routing
447 pub fees: RoutingFees,
448 /// Most recent update for the channel received from the network
449 /// Mostly redundant with the data we store in fields explicitly.
450 /// Everything else is useful only for sending out for initial routing sync.
451 /// Not stored if contains excess data to prevent DoS.
452 pub last_update_message: Option<ChannelUpdate>,
455 impl fmt::Display for DirectionalChannelInfo {
456 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
457 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)?;
462 impl_writeable!(DirectionalChannelInfo, 0, {
472 #[derive(Clone, Debug, PartialEq)]
473 /// Details about a channel (both directions).
474 /// Received within a channel announcement.
475 pub struct ChannelInfo {
476 /// Protocol features of a channel communicated during its announcement
477 pub features: ChannelFeatures,
478 /// Source node of the first direction of a channel
479 pub node_one: PublicKey,
480 /// Details about the first direction of a channel
481 pub one_to_two: Option<DirectionalChannelInfo>,
482 /// Source node of the second direction of a channel
483 pub node_two: PublicKey,
484 /// Details about the second direction of a channel
485 pub two_to_one: Option<DirectionalChannelInfo>,
486 /// The channel capacity as seen on-chain, if chain lookup is available.
487 pub capacity_sats: Option<u64>,
488 /// An initial announcement of the channel
489 /// Mostly redundant with the data we store in fields explicitly.
490 /// Everything else is useful only for sending out for initial routing sync.
491 /// Not stored if contains excess data to prevent DoS.
492 pub announcement_message: Option<ChannelAnnouncement>,
495 impl fmt::Display for ChannelInfo {
496 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
497 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
498 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
503 impl_writeable!(ChannelInfo, 0, {
514 /// Fees for routing via a given channel or a node
515 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
516 pub struct RoutingFees {
517 /// Flat routing fee in satoshis
519 /// Liquidity-based routing fee in millionths of a routed amount.
520 /// In other words, 10000 is 1%.
521 pub proportional_millionths: u32,
524 impl Readable for RoutingFees{
525 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
526 let base_msat: u32 = Readable::read(reader)?;
527 let proportional_millionths: u32 = Readable::read(reader)?;
530 proportional_millionths,
535 impl Writeable for RoutingFees {
536 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
537 self.base_msat.write(writer)?;
538 self.proportional_millionths.write(writer)?;
543 #[derive(Clone, Debug, PartialEq)]
544 /// Information received in the latest node_announcement from this node.
545 pub struct NodeAnnouncementInfo {
546 /// Protocol features the node announced support for
547 pub features: NodeFeatures,
548 /// When the last known update to the node state was issued.
549 /// Value is opaque, as set in the announcement.
550 pub last_update: u32,
551 /// Color assigned to the node
553 /// Moniker assigned to the node.
554 /// May be invalid or malicious (eg control chars),
555 /// should not be exposed to the user.
557 /// Internet-level addresses via which one can connect to the node
558 pub addresses: Vec<NetAddress>,
559 /// An initial announcement of the node
560 /// Mostly redundant with the data we store in fields explicitly.
561 /// Everything else is useful only for sending out for initial routing sync.
562 /// Not stored if contains excess data to prevent DoS.
563 pub announcement_message: Option<NodeAnnouncement>
566 impl Writeable for NodeAnnouncementInfo {
567 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
568 self.features.write(writer)?;
569 self.last_update.write(writer)?;
570 self.rgb.write(writer)?;
571 self.alias.write(writer)?;
572 (self.addresses.len() as u64).write(writer)?;
573 for ref addr in &self.addresses {
576 self.announcement_message.write(writer)?;
581 impl Readable for NodeAnnouncementInfo {
582 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
583 let features = Readable::read(reader)?;
584 let last_update = Readable::read(reader)?;
585 let rgb = Readable::read(reader)?;
586 let alias = Readable::read(reader)?;
587 let addresses_count: u64 = Readable::read(reader)?;
588 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
589 for _ in 0..addresses_count {
590 match Readable::read(reader) {
591 Ok(Ok(addr)) => { addresses.push(addr); },
592 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
593 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
597 let announcement_message = Readable::read(reader)?;
598 Ok(NodeAnnouncementInfo {
609 #[derive(Clone, Debug, PartialEq)]
610 /// Details about a node in the network, known from the network announcement.
611 pub struct NodeInfo {
612 /// All valid channels a node has announced
613 pub channels: Vec<u64>,
614 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
615 /// The two fields (flat and proportional fee) are independent,
616 /// meaning they don't have to refer to the same channel.
617 pub lowest_inbound_channel_fees: Option<RoutingFees>,
618 /// More information about a node from node_announcement.
619 /// Optional because we store a Node entry after learning about it from
620 /// a channel announcement, but before receiving a node announcement.
621 pub announcement_info: Option<NodeAnnouncementInfo>
624 impl fmt::Display for NodeInfo {
625 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
626 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
627 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
632 impl Writeable for NodeInfo {
633 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
634 (self.channels.len() as u64).write(writer)?;
635 for ref chan in self.channels.iter() {
638 self.lowest_inbound_channel_fees.write(writer)?;
639 self.announcement_info.write(writer)?;
644 const MAX_ALLOC_SIZE: u64 = 64*1024;
646 impl Readable for NodeInfo {
647 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
648 let channels_count: u64 = Readable::read(reader)?;
649 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
650 for _ in 0..channels_count {
651 channels.push(Readable::read(reader)?);
653 let lowest_inbound_channel_fees = Readable::read(reader)?;
654 let announcement_info = Readable::read(reader)?;
657 lowest_inbound_channel_fees,
663 const SERIALIZATION_VERSION: u8 = 1;
664 const MIN_SERIALIZATION_VERSION: u8 = 1;
666 impl Writeable for NetworkGraph {
667 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
668 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
670 self.genesis_hash.write(writer)?;
671 (self.channels.len() as u64).write(writer)?;
672 for (ref chan_id, ref chan_info) in self.channels.iter() {
673 (*chan_id).write(writer)?;
674 chan_info.write(writer)?;
676 (self.nodes.len() as u64).write(writer)?;
677 for (ref node_id, ref node_info) in self.nodes.iter() {
678 node_id.write(writer)?;
679 node_info.write(writer)?;
682 write_tlv_fields!(writer, {}, {});
687 impl Readable for NetworkGraph {
688 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
689 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
691 let genesis_hash: BlockHash = Readable::read(reader)?;
692 let channels_count: u64 = Readable::read(reader)?;
693 let mut channels = BTreeMap::new();
694 for _ in 0..channels_count {
695 let chan_id: u64 = Readable::read(reader)?;
696 let chan_info = Readable::read(reader)?;
697 channels.insert(chan_id, chan_info);
699 let nodes_count: u64 = Readable::read(reader)?;
700 let mut nodes = BTreeMap::new();
701 for _ in 0..nodes_count {
702 let node_id = Readable::read(reader)?;
703 let node_info = Readable::read(reader)?;
704 nodes.insert(node_id, node_info);
706 read_tlv_fields!(reader, {}, {});
716 impl fmt::Display for NetworkGraph {
717 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
718 writeln!(f, "Network map\n[Channels]")?;
719 for (key, val) in self.channels.iter() {
720 writeln!(f, " {}: {}", key, val)?;
722 writeln!(f, "[Nodes]")?;
723 for (key, val) in self.nodes.iter() {
724 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
731 /// Returns all known valid channels' short ids along with announced channel info.
733 /// (C-not exported) because we have no mapping for `BTreeMap`s
734 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
735 /// Returns all known nodes' public keys along with announced node info.
737 /// (C-not exported) because we have no mapping for `BTreeMap`s
738 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
740 /// Get network addresses by node id.
741 /// Returns None if the requested node is completely unknown,
742 /// or if node announcement for the node was never received.
744 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
745 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
746 if let Some(node) = self.nodes.get(pubkey) {
747 if let Some(node_info) = node.announcement_info.as_ref() {
748 return Some(&node_info.addresses)
754 /// Creates a new, empty, network graph.
755 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
758 channels: BTreeMap::new(),
759 nodes: BTreeMap::new(),
763 /// For an already known node (from channel announcements), update its stored properties from a
764 /// given node announcement.
766 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
767 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
768 /// routing messages from a source using a protocol other than the lightning P2P protocol.
769 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
770 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
771 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
772 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
775 /// For an already known node (from channel announcements), update its stored properties from a
776 /// given node announcement without verifying the associated signatures. Because we aren't
777 /// given the associated signatures here we cannot relay the node announcement to any of our
779 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
780 self.update_node_from_announcement_intern(msg, None)
783 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
784 match self.nodes.get_mut(&msg.node_id) {
785 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
787 if let Some(node_info) = node.announcement_info.as_ref() {
788 if node_info.last_update >= msg.timestamp {
789 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
794 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
795 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
796 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
797 node.announcement_info = Some(NodeAnnouncementInfo {
798 features: msg.features.clone(),
799 last_update: msg.timestamp,
802 addresses: msg.addresses.clone(),
803 announcement_message: if should_relay { full_msg.cloned() } else { None },
811 /// Store or update channel info from a channel announcement.
813 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
814 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
815 /// routing messages from a source using a protocol other than the lightning P2P protocol.
817 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
818 /// the corresponding UTXO exists on chain and is correctly-formatted.
819 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
820 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
821 -> Result<(), LightningError>
822 where C::Target: chain::Access {
823 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
824 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
825 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
826 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
827 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
828 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
831 /// Store or update channel info from a channel announcement without verifying the associated
832 /// signatures. Because we aren't given the associated signatures here we cannot relay the
833 /// channel announcement to any of our peers.
835 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
836 /// the corresponding UTXO exists on chain and is correctly-formatted.
837 pub fn update_channel_from_unsigned_announcement<C: Deref>
838 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
839 -> Result<(), LightningError>
840 where C::Target: chain::Access {
841 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
844 fn update_channel_from_unsigned_announcement_intern<C: Deref>
845 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
846 -> Result<(), LightningError>
847 where C::Target: chain::Access {
848 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
849 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
852 let utxo_value = match &chain_access {
854 // Tentatively accept, potentially exposing us to DoS attacks
857 &Some(ref chain_access) => {
858 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
859 Ok(TxOut { value, script_pubkey }) => {
860 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
861 .push_slice(&msg.bitcoin_key_1.serialize())
862 .push_slice(&msg.bitcoin_key_2.serialize())
863 .push_opcode(opcodes::all::OP_PUSHNUM_2)
864 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
865 if script_pubkey != expected_script {
866 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});
868 //TODO: Check if value is worth storing, use it to inform routing, and compare it
869 //to the new HTLC max field in channel_update
872 Err(chain::AccessError::UnknownChain) => {
873 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
875 Err(chain::AccessError::UnknownTx) => {
876 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
882 let chan_info = ChannelInfo {
883 features: msg.features.clone(),
884 node_one: msg.node_id_1.clone(),
886 node_two: msg.node_id_2.clone(),
888 capacity_sats: utxo_value,
889 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
890 { full_msg.cloned() } else { None },
893 match self.channels.entry(msg.short_channel_id) {
894 BtreeEntry::Occupied(mut entry) => {
895 //TODO: because asking the blockchain if short_channel_id is valid is only optional
896 //in the blockchain API, we need to handle it smartly here, though it's unclear
898 if utxo_value.is_some() {
899 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
900 // only sometimes returns results. In any case remove the previous entry. Note
901 // that the spec expects us to "blacklist" the node_ids involved, but we can't
903 // a) we don't *require* a UTXO provider that always returns results.
904 // b) we don't track UTXOs of channels we know about and remove them if they
906 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
907 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
908 *entry.get_mut() = chan_info;
910 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
913 BtreeEntry::Vacant(entry) => {
914 entry.insert(chan_info);
918 macro_rules! add_channel_to_node {
919 ( $node_id: expr ) => {
920 match self.nodes.entry($node_id) {
921 BtreeEntry::Occupied(node_entry) => {
922 node_entry.into_mut().channels.push(msg.short_channel_id);
924 BtreeEntry::Vacant(node_entry) => {
925 node_entry.insert(NodeInfo {
926 channels: vec!(msg.short_channel_id),
927 lowest_inbound_channel_fees: None,
928 announcement_info: None,
935 add_channel_to_node!(msg.node_id_1);
936 add_channel_to_node!(msg.node_id_2);
941 /// Close a channel if a corresponding HTLC fail was sent.
942 /// If permanent, removes a channel from the local storage.
943 /// May cause the removal of nodes too, if this was their last channel.
944 /// If not permanent, makes channels unavailable for routing.
945 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
947 if let Some(chan) = self.channels.remove(&short_channel_id) {
948 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
951 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
952 if let Some(one_to_two) = chan.one_to_two.as_mut() {
953 one_to_two.enabled = false;
955 if let Some(two_to_one) = chan.two_to_one.as_mut() {
956 two_to_one.enabled = false;
962 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
964 // TODO: Wholly remove the node
966 // TODO: downgrade the node
970 /// For an already known (from announcement) channel, update info about one of the directions
973 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
974 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
975 /// routing messages from a source using a protocol other than the lightning P2P protocol.
976 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
977 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
980 /// For an already known (from announcement) channel, update info about one of the directions
981 /// of the channel without verifying the associated signatures. Because we aren't given the
982 /// associated signatures here we cannot relay the channel update to any of our peers.
983 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
984 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
987 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> {
989 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
990 let chan_was_enabled;
992 match self.channels.get_mut(&msg.short_channel_id) {
993 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
995 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
996 if htlc_maximum_msat > MAX_VALUE_MSAT {
997 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
1000 if let Some(capacity_sats) = channel.capacity_sats {
1001 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1002 // Don't query UTXO set here to reduce DoS risks.
1003 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1004 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1008 macro_rules! maybe_update_channel_info {
1009 ( $target: expr, $src_node: expr) => {
1010 if let Some(existing_chan_info) = $target.as_ref() {
1011 if existing_chan_info.last_update >= msg.timestamp {
1012 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
1014 chan_was_enabled = existing_chan_info.enabled;
1016 chan_was_enabled = false;
1019 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1020 { full_msg.cloned() } else { None };
1022 let updated_channel_dir_info = DirectionalChannelInfo {
1023 enabled: chan_enabled,
1024 last_update: msg.timestamp,
1025 cltv_expiry_delta: msg.cltv_expiry_delta,
1026 htlc_minimum_msat: msg.htlc_minimum_msat,
1027 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1029 base_msat: msg.fee_base_msat,
1030 proportional_millionths: msg.fee_proportional_millionths,
1034 $target = Some(updated_channel_dir_info);
1038 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1039 if msg.flags & 1 == 1 {
1040 dest_node_id = channel.node_one.clone();
1041 if let Some((sig, ctx)) = sig_info {
1042 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1044 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1046 dest_node_id = channel.node_two.clone();
1047 if let Some((sig, ctx)) = sig_info {
1048 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1050 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1056 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1057 let mut base_msat = msg.fee_base_msat;
1058 let mut proportional_millionths = msg.fee_proportional_millionths;
1059 if let Some(fees) = node.lowest_inbound_channel_fees {
1060 base_msat = cmp::min(base_msat, fees.base_msat);
1061 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1063 node.lowest_inbound_channel_fees = Some(RoutingFees {
1065 proportional_millionths
1067 } else if chan_was_enabled {
1068 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1069 let mut lowest_inbound_channel_fees = None;
1071 for chan_id in node.channels.iter() {
1072 let chan = self.channels.get(chan_id).unwrap();
1074 if chan.node_one == dest_node_id {
1075 chan_info_opt = chan.two_to_one.as_ref();
1077 chan_info_opt = chan.one_to_two.as_ref();
1079 if let Some(chan_info) = chan_info_opt {
1080 if chan_info.enabled {
1081 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1082 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1083 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1084 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1089 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1095 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1096 macro_rules! remove_from_node {
1097 ($node_id: expr) => {
1098 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1099 entry.get_mut().channels.retain(|chan_id| {
1100 short_channel_id != *chan_id
1102 if entry.get().channels.is_empty() {
1103 entry.remove_entry();
1106 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1111 remove_from_node!(chan.node_one);
1112 remove_from_node!(chan.node_two);
1119 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1120 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
1121 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1122 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1123 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1124 use util::test_utils;
1125 use util::logger::Logger;
1126 use util::ser::{Readable, Writeable};
1127 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1128 use util::scid_utils::scid_from_parts;
1130 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1131 use bitcoin::hashes::Hash;
1132 use bitcoin::network::constants::Network;
1133 use bitcoin::blockdata::constants::genesis_block;
1134 use bitcoin::blockdata::script::Builder;
1135 use bitcoin::blockdata::transaction::TxOut;
1136 use bitcoin::blockdata::opcodes;
1140 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1141 use bitcoin::secp256k1::{All, Secp256k1};
1146 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1147 let secp_ctx = Secp256k1::new();
1148 let logger = Arc::new(test_utils::TestLogger::new());
1149 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1150 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1151 (secp_ctx, net_graph_msg_handler)
1155 fn request_full_sync_finite_times() {
1156 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1157 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1159 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1160 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1161 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1162 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1163 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1164 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1168 fn handling_node_announcements() {
1169 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1171 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1172 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1173 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1174 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1175 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1176 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1177 let zero_hash = Sha256dHash::hash(&[0; 32]);
1178 let first_announcement_time = 500;
1180 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1181 features: NodeFeatures::known(),
1182 timestamp: first_announcement_time,
1186 addresses: Vec::new(),
1187 excess_address_data: Vec::new(),
1188 excess_data: Vec::new(),
1190 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1191 let valid_announcement = NodeAnnouncement {
1192 signature: secp_ctx.sign(&msghash, node_1_privkey),
1193 contents: unsigned_announcement.clone()
1196 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1198 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1202 // Announce a channel to add a corresponding node.
1203 let unsigned_announcement = UnsignedChannelAnnouncement {
1204 features: ChannelFeatures::known(),
1205 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1206 short_channel_id: 0,
1209 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1210 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1211 excess_data: Vec::new(),
1214 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1215 let valid_announcement = ChannelAnnouncement {
1216 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1217 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1218 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1219 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1220 contents: unsigned_announcement.clone(),
1222 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1223 Ok(res) => assert!(res),
1228 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1229 Ok(res) => assert!(res),
1233 let fake_msghash = hash_to_message!(&zero_hash);
1234 match net_graph_msg_handler.handle_node_announcement(
1236 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1237 contents: unsigned_announcement.clone()
1240 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1243 unsigned_announcement.timestamp += 1000;
1244 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1245 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1246 let announcement_with_data = NodeAnnouncement {
1247 signature: secp_ctx.sign(&msghash, node_1_privkey),
1248 contents: unsigned_announcement.clone()
1250 // Return false because contains excess data.
1251 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1252 Ok(res) => assert!(!res),
1255 unsigned_announcement.excess_data = Vec::new();
1257 // Even though previous announcement was not relayed further, we still accepted it,
1258 // so we now won't accept announcements before the previous one.
1259 unsigned_announcement.timestamp -= 10;
1260 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1261 let outdated_announcement = NodeAnnouncement {
1262 signature: secp_ctx.sign(&msghash, node_1_privkey),
1263 contents: unsigned_announcement.clone()
1265 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1267 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1272 fn handling_channel_announcements() {
1273 let secp_ctx = Secp256k1::new();
1274 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1276 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1277 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1278 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1279 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1280 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1281 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1283 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1284 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1285 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1286 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1287 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1290 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1291 features: ChannelFeatures::known(),
1292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1293 short_channel_id: 0,
1296 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1297 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1298 excess_data: Vec::new(),
1301 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1302 let valid_announcement = ChannelAnnouncement {
1303 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1304 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1305 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1306 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1307 contents: unsigned_announcement.clone(),
1310 // Test if the UTXO lookups were not supported
1311 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1312 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1313 Ok(res) => assert!(res),
1318 let network = net_graph_msg_handler.network_graph.read().unwrap();
1319 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1325 // If we receive announcement for the same channel (with UTXO lookups disabled),
1326 // drop new one on the floor, since we can't see any changes.
1327 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1329 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1332 // Test if an associated transaction were not on-chain (or not confirmed).
1333 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1334 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1335 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1336 unsigned_announcement.short_channel_id += 1;
1338 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1339 let valid_announcement = ChannelAnnouncement {
1340 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1341 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1342 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1343 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1344 contents: unsigned_announcement.clone(),
1347 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1349 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1352 // Now test if the transaction is found in the UTXO set and the script is correct.
1353 unsigned_announcement.short_channel_id += 1;
1354 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1356 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1357 let valid_announcement = ChannelAnnouncement {
1358 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1359 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1360 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1361 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1362 contents: unsigned_announcement.clone(),
1364 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1365 Ok(res) => assert!(res),
1370 let network = net_graph_msg_handler.network_graph.read().unwrap();
1371 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1377 // If we receive announcement for the same channel (but TX is not confirmed),
1378 // drop new one on the floor, since we can't see any changes.
1379 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1380 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1382 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1385 // But if it is confirmed, replace the channel
1386 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1387 unsigned_announcement.features = ChannelFeatures::empty();
1388 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1389 let valid_announcement = ChannelAnnouncement {
1390 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1391 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1392 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1393 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1394 contents: unsigned_announcement.clone(),
1396 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1397 Ok(res) => assert!(res),
1401 let network = net_graph_msg_handler.network_graph.read().unwrap();
1402 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1403 Some(channel_entry) => {
1404 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1410 // Don't relay valid channels with excess data
1411 unsigned_announcement.short_channel_id += 1;
1412 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1413 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1414 let valid_announcement = ChannelAnnouncement {
1415 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1416 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1417 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1418 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1419 contents: unsigned_announcement.clone(),
1421 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1422 Ok(res) => assert!(!res),
1426 unsigned_announcement.excess_data = Vec::new();
1427 let invalid_sig_announcement = ChannelAnnouncement {
1428 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1429 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1430 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1431 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1432 contents: unsigned_announcement.clone(),
1434 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1436 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1439 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1440 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1441 let channel_to_itself_announcement = ChannelAnnouncement {
1442 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1443 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1444 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1445 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1446 contents: unsigned_announcement.clone(),
1448 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1450 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1455 fn handling_channel_update() {
1456 let secp_ctx = Secp256k1::new();
1457 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1458 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1459 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1461 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1462 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1463 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1464 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1465 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1466 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1468 let zero_hash = Sha256dHash::hash(&[0; 32]);
1469 let short_channel_id = 0;
1470 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1471 let amount_sats = 1000_000;
1474 // Announce a channel we will update
1475 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1476 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1477 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1478 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1479 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1480 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1481 let unsigned_announcement = UnsignedChannelAnnouncement {
1482 features: ChannelFeatures::empty(),
1487 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1488 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1489 excess_data: Vec::new(),
1492 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1493 let valid_channel_announcement = ChannelAnnouncement {
1494 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1495 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1496 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1497 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1498 contents: unsigned_announcement.clone(),
1500 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1507 let mut unsigned_channel_update = UnsignedChannelUpdate {
1512 cltv_expiry_delta: 144,
1513 htlc_minimum_msat: 1000000,
1514 htlc_maximum_msat: OptionalField::Absent,
1515 fee_base_msat: 10000,
1516 fee_proportional_millionths: 20,
1517 excess_data: Vec::new()
1519 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1520 let valid_channel_update = ChannelUpdate {
1521 signature: secp_ctx.sign(&msghash, node_1_privkey),
1522 contents: unsigned_channel_update.clone()
1525 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1526 Ok(res) => assert!(res),
1531 let network = net_graph_msg_handler.network_graph.read().unwrap();
1532 match network.get_channels().get(&short_channel_id) {
1534 Some(channel_info) => {
1535 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1536 assert!(channel_info.two_to_one.is_none());
1541 unsigned_channel_update.timestamp += 100;
1542 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1543 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1544 let valid_channel_update = ChannelUpdate {
1545 signature: secp_ctx.sign(&msghash, node_1_privkey),
1546 contents: unsigned_channel_update.clone()
1548 // Return false because contains excess data
1549 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1550 Ok(res) => assert!(!res),
1553 unsigned_channel_update.timestamp += 10;
1555 unsigned_channel_update.short_channel_id += 1;
1556 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1557 let valid_channel_update = ChannelUpdate {
1558 signature: secp_ctx.sign(&msghash, node_1_privkey),
1559 contents: unsigned_channel_update.clone()
1562 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1564 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1566 unsigned_channel_update.short_channel_id = short_channel_id;
1568 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1569 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1570 let valid_channel_update = ChannelUpdate {
1571 signature: secp_ctx.sign(&msghash, node_1_privkey),
1572 contents: unsigned_channel_update.clone()
1575 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1577 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1579 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1581 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1582 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1583 let valid_channel_update = ChannelUpdate {
1584 signature: secp_ctx.sign(&msghash, node_1_privkey),
1585 contents: unsigned_channel_update.clone()
1588 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1590 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1592 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1594 // Even though previous update was not relayed further, we still accepted it,
1595 // so we now won't accept update before the previous one.
1596 unsigned_channel_update.timestamp -= 10;
1597 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1598 let valid_channel_update = ChannelUpdate {
1599 signature: secp_ctx.sign(&msghash, node_1_privkey),
1600 contents: unsigned_channel_update.clone()
1603 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1605 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1607 unsigned_channel_update.timestamp += 500;
1609 let fake_msghash = hash_to_message!(&zero_hash);
1610 let invalid_sig_channel_update = ChannelUpdate {
1611 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1612 contents: unsigned_channel_update.clone()
1615 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1617 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1623 fn handling_htlc_fail_channel_update() {
1624 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1625 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1626 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1627 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1628 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1629 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1630 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1632 let short_channel_id = 0;
1633 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1636 // There is no nodes in the table at the beginning.
1637 let network = net_graph_msg_handler.network_graph.read().unwrap();
1638 assert_eq!(network.get_nodes().len(), 0);
1642 // Announce a channel we will update
1643 let unsigned_announcement = UnsignedChannelAnnouncement {
1644 features: ChannelFeatures::empty(),
1649 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1650 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1651 excess_data: Vec::new(),
1654 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1655 let valid_channel_announcement = ChannelAnnouncement {
1656 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1657 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1658 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1659 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1660 contents: unsigned_announcement.clone(),
1662 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1667 let unsigned_channel_update = UnsignedChannelUpdate {
1672 cltv_expiry_delta: 144,
1673 htlc_minimum_msat: 1000000,
1674 htlc_maximum_msat: OptionalField::Absent,
1675 fee_base_msat: 10000,
1676 fee_proportional_millionths: 20,
1677 excess_data: Vec::new()
1679 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1680 let valid_channel_update = ChannelUpdate {
1681 signature: secp_ctx.sign(&msghash, node_1_privkey),
1682 contents: unsigned_channel_update.clone()
1685 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1686 Ok(res) => assert!(res),
1691 // Non-permanent closing just disables a channel
1693 let network = net_graph_msg_handler.network_graph.read().unwrap();
1694 match network.get_channels().get(&short_channel_id) {
1696 Some(channel_info) => {
1697 assert!(channel_info.one_to_two.is_some());
1702 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1707 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1709 // Non-permanent closing just disables a channel
1711 let network = net_graph_msg_handler.network_graph.read().unwrap();
1712 match network.get_channels().get(&short_channel_id) {
1714 Some(channel_info) => {
1715 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1720 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1725 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1727 // Permanent closing deletes a channel
1729 let network = net_graph_msg_handler.network_graph.read().unwrap();
1730 assert_eq!(network.get_channels().len(), 0);
1731 // Nodes are also deleted because there are no associated channels anymore
1732 assert_eq!(network.get_nodes().len(), 0);
1734 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1738 fn getting_next_channel_announcements() {
1739 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1740 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1741 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1742 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1743 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1744 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1745 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1747 let short_channel_id = 1;
1748 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1750 // Channels were not announced yet.
1751 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1752 assert_eq!(channels_with_announcements.len(), 0);
1755 // Announce a channel we will update
1756 let unsigned_announcement = UnsignedChannelAnnouncement {
1757 features: ChannelFeatures::empty(),
1762 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1763 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1764 excess_data: Vec::new(),
1767 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1768 let valid_channel_announcement = ChannelAnnouncement {
1769 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1770 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1771 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1772 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1773 contents: unsigned_announcement.clone(),
1775 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1781 // Contains initial channel announcement now.
1782 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1783 assert_eq!(channels_with_announcements.len(), 1);
1784 if let Some(channel_announcements) = channels_with_announcements.first() {
1785 let &(_, ref update_1, ref update_2) = channel_announcements;
1786 assert_eq!(update_1, &None);
1787 assert_eq!(update_2, &None);
1794 // Valid channel update
1795 let unsigned_channel_update = UnsignedChannelUpdate {
1800 cltv_expiry_delta: 144,
1801 htlc_minimum_msat: 1000000,
1802 htlc_maximum_msat: OptionalField::Absent,
1803 fee_base_msat: 10000,
1804 fee_proportional_millionths: 20,
1805 excess_data: Vec::new()
1807 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1808 let valid_channel_update = ChannelUpdate {
1809 signature: secp_ctx.sign(&msghash, node_1_privkey),
1810 contents: unsigned_channel_update.clone()
1812 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1818 // Now contains an initial announcement and an update.
1819 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1820 assert_eq!(channels_with_announcements.len(), 1);
1821 if let Some(channel_announcements) = channels_with_announcements.first() {
1822 let &(_, ref update_1, ref update_2) = channel_announcements;
1823 assert_ne!(update_1, &None);
1824 assert_eq!(update_2, &None);
1831 // Channel update with excess data.
1832 let unsigned_channel_update = UnsignedChannelUpdate {
1837 cltv_expiry_delta: 144,
1838 htlc_minimum_msat: 1000000,
1839 htlc_maximum_msat: OptionalField::Absent,
1840 fee_base_msat: 10000,
1841 fee_proportional_millionths: 20,
1842 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1844 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1845 let valid_channel_update = ChannelUpdate {
1846 signature: secp_ctx.sign(&msghash, node_1_privkey),
1847 contents: unsigned_channel_update.clone()
1849 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1855 // Test that announcements with excess data won't be returned
1856 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1857 assert_eq!(channels_with_announcements.len(), 1);
1858 if let Some(channel_announcements) = channels_with_announcements.first() {
1859 let &(_, ref update_1, ref update_2) = channel_announcements;
1860 assert_eq!(update_1, &None);
1861 assert_eq!(update_2, &None);
1866 // Further starting point have no channels after it
1867 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1868 assert_eq!(channels_with_announcements.len(), 0);
1872 fn getting_next_node_announcements() {
1873 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1874 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1875 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
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 node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1879 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1881 let short_channel_id = 1;
1882 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1885 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1886 assert_eq!(next_announcements.len(), 0);
1889 // Announce a channel to add 2 nodes
1890 let unsigned_announcement = UnsignedChannelAnnouncement {
1891 features: ChannelFeatures::empty(),
1896 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1897 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1898 excess_data: Vec::new(),
1901 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1902 let valid_channel_announcement = ChannelAnnouncement {
1903 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1904 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1905 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1906 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1907 contents: unsigned_announcement.clone(),
1909 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1916 // Nodes were never announced
1917 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1918 assert_eq!(next_announcements.len(), 0);
1921 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1922 features: NodeFeatures::known(),
1927 addresses: Vec::new(),
1928 excess_address_data: Vec::new(),
1929 excess_data: Vec::new(),
1931 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1932 let valid_announcement = NodeAnnouncement {
1933 signature: secp_ctx.sign(&msghash, node_1_privkey),
1934 contents: unsigned_announcement.clone()
1936 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1941 unsigned_announcement.node_id = node_id_2;
1942 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1943 let valid_announcement = NodeAnnouncement {
1944 signature: secp_ctx.sign(&msghash, node_2_privkey),
1945 contents: unsigned_announcement.clone()
1948 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1954 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1955 assert_eq!(next_announcements.len(), 2);
1957 // Skip the first node.
1958 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1959 assert_eq!(next_announcements.len(), 1);
1962 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1963 let unsigned_announcement = UnsignedNodeAnnouncement {
1964 features: NodeFeatures::known(),
1969 addresses: Vec::new(),
1970 excess_address_data: Vec::new(),
1971 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
1973 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1974 let valid_announcement = NodeAnnouncement {
1975 signature: secp_ctx.sign(&msghash, node_2_privkey),
1976 contents: unsigned_announcement.clone()
1978 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1979 Ok(res) => assert!(!res),
1984 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1985 assert_eq!(next_announcements.len(), 0);
1989 fn network_graph_serialization() {
1990 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1992 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1993 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1994 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1995 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1997 // Announce a channel to add a corresponding node.
1998 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1999 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2000 let unsigned_announcement = UnsignedChannelAnnouncement {
2001 features: ChannelFeatures::known(),
2002 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2003 short_channel_id: 0,
2006 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2007 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2008 excess_data: Vec::new(),
2011 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2012 let valid_announcement = ChannelAnnouncement {
2013 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2014 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2015 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2016 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2017 contents: unsigned_announcement.clone(),
2019 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2020 Ok(res) => assert!(res),
2025 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2026 let unsigned_announcement = UnsignedNodeAnnouncement {
2027 features: NodeFeatures::known(),
2032 addresses: Vec::new(),
2033 excess_address_data: Vec::new(),
2034 excess_data: Vec::new(),
2036 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2037 let valid_announcement = NodeAnnouncement {
2038 signature: secp_ctx.sign(&msghash, node_1_privkey),
2039 contents: unsigned_announcement.clone()
2042 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2047 let network = net_graph_msg_handler.network_graph.write().unwrap();
2048 let mut w = test_utils::TestVecWriter(Vec::new());
2049 assert!(!network.get_nodes().is_empty());
2050 assert!(!network.get_channels().is_empty());
2051 network.write(&mut w).unwrap();
2052 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
2056 fn calling_sync_routing_table() {
2057 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2058 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2059 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2061 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2062 let first_blocknum = 0;
2063 let number_of_blocks = 0xffff_ffff;
2065 // It should ignore if gossip_queries feature is not enabled
2067 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2068 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2069 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2070 assert_eq!(events.len(), 0);
2073 // It should send a query_channel_message with the correct information
2075 let init_msg = Init { features: InitFeatures::known() };
2076 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2077 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2078 assert_eq!(events.len(), 1);
2080 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2081 assert_eq!(node_id, &node_id_1);
2082 assert_eq!(msg.chain_hash, chain_hash);
2083 assert_eq!(msg.first_blocknum, first_blocknum);
2084 assert_eq!(msg.number_of_blocks, number_of_blocks);
2086 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2090 // It should not enqueue a query when should_request_full_sync return false.
2091 // The initial implementation allows syncing with the first 5 peers after
2092 // which should_request_full_sync will return false
2094 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2095 let init_msg = Init { features: InitFeatures::known() };
2097 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2098 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2099 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2100 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2102 assert_eq!(events.len(), 1);
2104 assert_eq!(events.len(), 0);
2112 fn handling_reply_channel_range() {
2113 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2114 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2115 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2117 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2119 // Test receipt of a single reply that should enqueue an SCID query
2120 // matching the SCIDs in the reply
2122 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2124 sync_complete: true,
2126 number_of_blocks: 2000,
2127 short_channel_ids: vec![
2128 0x0003e0_000000_0000, // 992x0x0
2129 0x0003e8_000000_0000, // 1000x0x0
2130 0x0003e9_000000_0000, // 1001x0x0
2131 0x0003f0_000000_0000, // 1008x0x0
2132 0x00044c_000000_0000, // 1100x0x0
2133 0x0006e0_000000_0000, // 1760x0x0
2136 assert!(result.is_ok());
2138 // We expect to emit a query_short_channel_ids message with the received scids
2139 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2140 assert_eq!(events.len(), 1);
2142 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2143 assert_eq!(node_id, &node_id_1);
2144 assert_eq!(msg.chain_hash, chain_hash);
2145 assert_eq!(msg.short_channel_ids, vec![
2146 0x0003e0_000000_0000, // 992x0x0
2147 0x0003e8_000000_0000, // 1000x0x0
2148 0x0003e9_000000_0000, // 1001x0x0
2149 0x0003f0_000000_0000, // 1008x0x0
2150 0x00044c_000000_0000, // 1100x0x0
2151 0x0006e0_000000_0000, // 1760x0x0
2154 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2160 fn handling_reply_short_channel_ids() {
2161 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2162 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2163 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2165 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2167 // Test receipt of a successful reply
2169 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2171 full_information: true,
2173 assert!(result.is_ok());
2176 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2177 // for the chain_hash requested in the query.
2179 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2181 full_information: false,
2183 assert!(result.is_err());
2184 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2189 fn handling_query_channel_range() {
2190 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2192 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2193 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2194 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2195 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2196 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2197 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2198 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2199 let bitcoin_key_1 = PublicKey::from_secret_key(&secp_ctx, node_1_btckey);
2200 let bitcoin_key_2 = PublicKey::from_secret_key(&secp_ctx, node_2_btckey);
2202 let mut scids: Vec<u64> = vec![
2203 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2204 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2207 // used for testing multipart reply across blocks
2208 for block in 100000..=108001 {
2209 scids.push(scid_from_parts(block, 0, 0).unwrap());
2212 // used for testing resumption on same block
2213 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2216 let unsigned_announcement = UnsignedChannelAnnouncement {
2217 features: ChannelFeatures::known(),
2218 chain_hash: chain_hash.clone(),
2219 short_channel_id: scid,
2224 excess_data: Vec::new(),
2227 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2228 let valid_announcement = ChannelAnnouncement {
2229 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2230 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2231 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2232 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2233 contents: unsigned_announcement.clone(),
2235 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2241 // Error when number_of_blocks=0
2242 do_handling_query_channel_range(
2243 &net_graph_msg_handler,
2246 chain_hash: chain_hash.clone(),
2248 number_of_blocks: 0,
2251 vec![ReplyChannelRange {
2252 chain_hash: chain_hash.clone(),
2254 number_of_blocks: 0,
2255 sync_complete: true,
2256 short_channel_ids: vec![]
2260 // Error when wrong chain
2261 do_handling_query_channel_range(
2262 &net_graph_msg_handler,
2265 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2267 number_of_blocks: 0xffff_ffff,
2270 vec![ReplyChannelRange {
2271 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2273 number_of_blocks: 0xffff_ffff,
2274 sync_complete: true,
2275 short_channel_ids: vec![],
2279 // Error when first_blocknum > 0xffffff
2280 do_handling_query_channel_range(
2281 &net_graph_msg_handler,
2284 chain_hash: chain_hash.clone(),
2285 first_blocknum: 0x01000000,
2286 number_of_blocks: 0xffff_ffff,
2289 vec![ReplyChannelRange {
2290 chain_hash: chain_hash.clone(),
2291 first_blocknum: 0x01000000,
2292 number_of_blocks: 0xffff_ffff,
2293 sync_complete: true,
2294 short_channel_ids: vec![]
2298 // Empty reply when max valid SCID block num
2299 do_handling_query_channel_range(
2300 &net_graph_msg_handler,
2303 chain_hash: chain_hash.clone(),
2304 first_blocknum: 0xffffff,
2305 number_of_blocks: 1,
2310 chain_hash: chain_hash.clone(),
2312 number_of_blocks: 0x01000000,
2313 sync_complete: true,
2314 short_channel_ids: vec![]
2319 // No results in valid query range
2320 do_handling_query_channel_range(
2321 &net_graph_msg_handler,
2324 chain_hash: chain_hash.clone(),
2325 first_blocknum: 1000,
2326 number_of_blocks: 1000,
2331 chain_hash: chain_hash.clone(),
2333 number_of_blocks: 2000,
2334 sync_complete: true,
2335 short_channel_ids: vec![],
2340 // Overflow first_blocknum + number_of_blocks
2341 do_handling_query_channel_range(
2342 &net_graph_msg_handler,
2345 chain_hash: chain_hash.clone(),
2346 first_blocknum: 0xfe0000,
2347 number_of_blocks: 0xffffffff,
2352 chain_hash: chain_hash.clone(),
2354 number_of_blocks: 0xffffffff,
2355 sync_complete: true,
2356 short_channel_ids: vec![
2357 0xfffffe_ffffff_ffff, // max
2363 // Single block exactly full
2364 do_handling_query_channel_range(
2365 &net_graph_msg_handler,
2368 chain_hash: chain_hash.clone(),
2369 first_blocknum: 100000,
2370 number_of_blocks: 8000,
2375 chain_hash: chain_hash.clone(),
2377 number_of_blocks: 108000,
2378 sync_complete: true,
2379 short_channel_ids: (100000..=107999)
2380 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2386 // Multiple split on new block
2387 do_handling_query_channel_range(
2388 &net_graph_msg_handler,
2391 chain_hash: chain_hash.clone(),
2392 first_blocknum: 100000,
2393 number_of_blocks: 8001,
2398 chain_hash: chain_hash.clone(),
2400 number_of_blocks: 108000,
2401 sync_complete: false,
2402 short_channel_ids: (100000..=107999)
2403 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2407 chain_hash: chain_hash.clone(),
2409 number_of_blocks: 108001,
2410 sync_complete: true,
2411 short_channel_ids: vec![
2412 scid_from_parts(108000, 0, 0).unwrap(),
2418 // Multiple split on same block
2419 do_handling_query_channel_range(
2420 &net_graph_msg_handler,
2423 chain_hash: chain_hash.clone(),
2424 first_blocknum: 100002,
2425 number_of_blocks: 8000,
2430 chain_hash: chain_hash.clone(),
2432 number_of_blocks: 108002,
2433 sync_complete: false,
2434 short_channel_ids: (100002..=108001)
2435 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2439 chain_hash: chain_hash.clone(),
2441 number_of_blocks: 108002,
2442 sync_complete: true,
2443 short_channel_ids: vec![
2444 scid_from_parts(108001, 1, 0).unwrap(),
2451 fn do_handling_query_channel_range(
2452 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2453 test_node_id: &PublicKey,
2454 msg: QueryChannelRange,
2456 expected_replies: Vec<ReplyChannelRange>
2458 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2461 assert!(result.is_ok());
2463 assert!(result.is_err());
2466 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2467 assert_eq!(events.len(), expected_replies.len());
2469 for i in 0..events.len() {
2470 let expected_reply = &expected_replies[i];
2472 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2473 assert_eq!(node_id, test_node_id);
2474 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2475 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2476 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2477 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2478 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2480 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2486 fn handling_query_short_channel_ids() {
2487 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2488 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2489 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2491 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2493 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2495 short_channel_ids: vec![0x0003e8_000000_0000],
2497 assert!(result.is_err());