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 std::sync::{RwLock, RwLockReadGuard};
37 use std::sync::atomic::{AtomicUsize, Ordering};
39 use std::collections::BTreeMap;
40 use std::collections::btree_map::Entry as BtreeEntry;
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 + Sync + Send, L: Deref + Sync + Send> 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 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.
324 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
325 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);
327 let network_graph = self.network_graph.read().unwrap();
329 let start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
331 // We receive valid queries with end_blocknum that would overflow SCID conversion.
332 // Manually cap the ending block to avoid this overflow.
333 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
335 // Per spec, we must reply to a query. Send an empty message when things are invalid.
336 if msg.chain_hash != network_graph.genesis_hash || start_scid.is_err() || exclusive_end_scid.is_err() {
337 let mut pending_events = self.pending_events.lock().unwrap();
338 pending_events.push(MessageSendEvent::SendReplyChannelRange {
339 node_id: their_node_id.clone(),
340 msg: ReplyChannelRange {
341 chain_hash: msg.chain_hash.clone(),
342 first_blocknum: msg.first_blocknum,
343 number_of_blocks: msg.number_of_blocks,
345 short_channel_ids: vec![],
351 // Creates channel batches. We are not checking if the channel is routable
352 // (has at least one update). A peer may still want to know the channel
353 // exists even if its not yet routable.
354 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
355 for (_, ref chan) in network_graph.get_channels().range(start_scid.unwrap()..exclusive_end_scid.unwrap()) {
356 if let Some(chan_announcement) = &chan.announcement_message {
357 // Construct a new batch if last one is full
358 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
359 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
362 let batch = batches.last_mut().unwrap();
363 batch.push(chan_announcement.contents.short_channel_id);
368 let mut pending_events = self.pending_events.lock().unwrap();
369 let batch_count = batches.len();
370 for (batch_index, batch) in batches.into_iter().enumerate() {
371 // Per spec, the initial first_blocknum needs to be <= the query's first_blocknum.
372 // Use the query's values since we don't use pre-processed reply ranges.
373 let first_blocknum = if batch_index == 0 {
376 // Subsequent replies must be >= the last sent first_blocknum. Use the first block
379 block_from_scid(batch.first().unwrap())
382 // Per spec, the last end_block needs to be >= the query's end_block. Last
383 // reply calculates difference between the query's end_blocknum and the start of the reply.
384 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and first_blocknum
385 // will be either msg.first_blocknum or a higher block height.
386 let number_of_blocks = if batch_index == batch_count-1 {
387 msg.end_blocknum() - first_blocknum
389 // Prior replies should use the number of blocks that fit into the reply. Overflow
390 // safe since first_blocknum is always <= last SCID's block.
392 block_from_scid(batch.last().unwrap()) - first_blocknum + 1
395 // Only true for the last message in a sequence
396 let sync_complete = batch_index == batch_count - 1;
398 pending_events.push(MessageSendEvent::SendReplyChannelRange {
399 node_id: their_node_id.clone(),
400 msg: ReplyChannelRange {
401 chain_hash: msg.chain_hash.clone(),
405 short_channel_ids: batch,
413 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
416 err: String::from("Not implemented"),
417 action: ErrorAction::IgnoreError,
422 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
424 C::Target: chain::Access,
427 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
428 let mut ret = Vec::new();
429 let mut pending_events = self.pending_events.lock().unwrap();
430 std::mem::swap(&mut ret, &mut pending_events);
435 #[derive(Clone, Debug, PartialEq)]
436 /// Details about one direction of a channel. Received
437 /// within a channel update.
438 pub struct DirectionalChannelInfo {
439 /// When the last update to the channel direction was issued.
440 /// Value is opaque, as set in the announcement.
441 pub last_update: u32,
442 /// Whether the channel can be currently used for payments (in this one direction).
444 /// The difference in CLTV values that you must have when routing through this channel.
445 pub cltv_expiry_delta: u16,
446 /// The minimum value, which must be relayed to the next hop via the channel
447 pub htlc_minimum_msat: u64,
448 /// The maximum value which may be relayed to the next hop via the channel.
449 pub htlc_maximum_msat: Option<u64>,
450 /// Fees charged when the channel is used for routing
451 pub fees: RoutingFees,
452 /// Most recent update for the channel received from the network
453 /// Mostly redundant with the data we store in fields explicitly.
454 /// Everything else is useful only for sending out for initial routing sync.
455 /// Not stored if contains excess data to prevent DoS.
456 pub last_update_message: Option<ChannelUpdate>,
459 impl fmt::Display for DirectionalChannelInfo {
460 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
461 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)?;
466 impl_writeable!(DirectionalChannelInfo, 0, {
476 #[derive(Clone, Debug, PartialEq)]
477 /// Details about a channel (both directions).
478 /// Received within a channel announcement.
479 pub struct ChannelInfo {
480 /// Protocol features of a channel communicated during its announcement
481 pub features: ChannelFeatures,
482 /// Source node of the first direction of a channel
483 pub node_one: PublicKey,
484 /// Details about the first direction of a channel
485 pub one_to_two: Option<DirectionalChannelInfo>,
486 /// Source node of the second direction of a channel
487 pub node_two: PublicKey,
488 /// Details about the second direction of a channel
489 pub two_to_one: Option<DirectionalChannelInfo>,
490 /// The channel capacity as seen on-chain, if chain lookup is available.
491 pub capacity_sats: Option<u64>,
492 /// An initial announcement of the channel
493 /// Mostly redundant with the data we store in fields explicitly.
494 /// Everything else is useful only for sending out for initial routing sync.
495 /// Not stored if contains excess data to prevent DoS.
496 pub announcement_message: Option<ChannelAnnouncement>,
499 impl fmt::Display for ChannelInfo {
500 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
501 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
502 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
507 impl_writeable!(ChannelInfo, 0, {
518 /// Fees for routing via a given channel or a node
519 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
520 pub struct RoutingFees {
521 /// Flat routing fee in satoshis
523 /// Liquidity-based routing fee in millionths of a routed amount.
524 /// In other words, 10000 is 1%.
525 pub proportional_millionths: u32,
528 impl Readable for RoutingFees{
529 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
530 let base_msat: u32 = Readable::read(reader)?;
531 let proportional_millionths: u32 = Readable::read(reader)?;
534 proportional_millionths,
539 impl Writeable for RoutingFees {
540 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
541 self.base_msat.write(writer)?;
542 self.proportional_millionths.write(writer)?;
547 #[derive(Clone, Debug, PartialEq)]
548 /// Information received in the latest node_announcement from this node.
549 pub struct NodeAnnouncementInfo {
550 /// Protocol features the node announced support for
551 pub features: NodeFeatures,
552 /// When the last known update to the node state was issued.
553 /// Value is opaque, as set in the announcement.
554 pub last_update: u32,
555 /// Color assigned to the node
557 /// Moniker assigned to the node.
558 /// May be invalid or malicious (eg control chars),
559 /// should not be exposed to the user.
561 /// Internet-level addresses via which one can connect to the node
562 pub addresses: Vec<NetAddress>,
563 /// An initial announcement of the node
564 /// Mostly redundant with the data we store in fields explicitly.
565 /// Everything else is useful only for sending out for initial routing sync.
566 /// Not stored if contains excess data to prevent DoS.
567 pub announcement_message: Option<NodeAnnouncement>
570 impl Writeable for NodeAnnouncementInfo {
571 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
572 self.features.write(writer)?;
573 self.last_update.write(writer)?;
574 self.rgb.write(writer)?;
575 self.alias.write(writer)?;
576 (self.addresses.len() as u64).write(writer)?;
577 for ref addr in &self.addresses {
580 self.announcement_message.write(writer)?;
585 impl Readable for NodeAnnouncementInfo {
586 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
587 let features = Readable::read(reader)?;
588 let last_update = Readable::read(reader)?;
589 let rgb = Readable::read(reader)?;
590 let alias = Readable::read(reader)?;
591 let addresses_count: u64 = Readable::read(reader)?;
592 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
593 for _ in 0..addresses_count {
594 match Readable::read(reader) {
595 Ok(Ok(addr)) => { addresses.push(addr); },
596 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
597 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
601 let announcement_message = Readable::read(reader)?;
602 Ok(NodeAnnouncementInfo {
613 #[derive(Clone, Debug, PartialEq)]
614 /// Details about a node in the network, known from the network announcement.
615 pub struct NodeInfo {
616 /// All valid channels a node has announced
617 pub channels: Vec<u64>,
618 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
619 /// The two fields (flat and proportional fee) are independent,
620 /// meaning they don't have to refer to the same channel.
621 pub lowest_inbound_channel_fees: Option<RoutingFees>,
622 /// More information about a node from node_announcement.
623 /// Optional because we store a Node entry after learning about it from
624 /// a channel announcement, but before receiving a node announcement.
625 pub announcement_info: Option<NodeAnnouncementInfo>
628 impl fmt::Display for NodeInfo {
629 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
630 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
631 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
636 impl Writeable for NodeInfo {
637 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
638 (self.channels.len() as u64).write(writer)?;
639 for ref chan in self.channels.iter() {
642 self.lowest_inbound_channel_fees.write(writer)?;
643 self.announcement_info.write(writer)?;
648 const MAX_ALLOC_SIZE: u64 = 64*1024;
650 impl Readable for NodeInfo {
651 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
652 let channels_count: u64 = Readable::read(reader)?;
653 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
654 for _ in 0..channels_count {
655 channels.push(Readable::read(reader)?);
657 let lowest_inbound_channel_fees = Readable::read(reader)?;
658 let announcement_info = Readable::read(reader)?;
661 lowest_inbound_channel_fees,
667 impl Writeable for NetworkGraph {
668 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
669 self.genesis_hash.write(writer)?;
670 (self.channels.len() as u64).write(writer)?;
671 for (ref chan_id, ref chan_info) in self.channels.iter() {
672 (*chan_id).write(writer)?;
673 chan_info.write(writer)?;
675 (self.nodes.len() as u64).write(writer)?;
676 for (ref node_id, ref node_info) in self.nodes.iter() {
677 node_id.write(writer)?;
678 node_info.write(writer)?;
684 impl Readable for NetworkGraph {
685 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
686 let genesis_hash: BlockHash = Readable::read(reader)?;
687 let channels_count: u64 = Readable::read(reader)?;
688 let mut channels = BTreeMap::new();
689 for _ in 0..channels_count {
690 let chan_id: u64 = Readable::read(reader)?;
691 let chan_info = Readable::read(reader)?;
692 channels.insert(chan_id, chan_info);
694 let nodes_count: u64 = Readable::read(reader)?;
695 let mut nodes = BTreeMap::new();
696 for _ in 0..nodes_count {
697 let node_id = Readable::read(reader)?;
698 let node_info = Readable::read(reader)?;
699 nodes.insert(node_id, node_info);
709 impl fmt::Display for NetworkGraph {
710 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
711 writeln!(f, "Network map\n[Channels]")?;
712 for (key, val) in self.channels.iter() {
713 writeln!(f, " {}: {}", key, val)?;
715 writeln!(f, "[Nodes]")?;
716 for (key, val) in self.nodes.iter() {
717 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
724 /// Returns all known valid channels' short ids along with announced channel info.
726 /// (C-not exported) because we have no mapping for `BTreeMap`s
727 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
728 /// Returns all known nodes' public keys along with announced node info.
730 /// (C-not exported) because we have no mapping for `BTreeMap`s
731 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
733 /// Get network addresses by node id.
734 /// Returns None if the requested node is completely unknown,
735 /// or if node announcement for the node was never received.
737 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
738 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
739 if let Some(node) = self.nodes.get(pubkey) {
740 if let Some(node_info) = node.announcement_info.as_ref() {
741 return Some(&node_info.addresses)
747 /// Creates a new, empty, network graph.
748 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
751 channels: BTreeMap::new(),
752 nodes: BTreeMap::new(),
756 /// For an already known node (from channel announcements), update its stored properties from a
757 /// given node announcement.
759 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
760 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
761 /// routing messages from a source using a protocol other than the lightning P2P protocol.
762 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
763 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
764 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
765 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
768 /// For an already known node (from channel announcements), update its stored properties from a
769 /// given node announcement without verifying the associated signatures. Because we aren't
770 /// given the associated signatures here we cannot relay the node announcement to any of our
772 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
773 self.update_node_from_announcement_intern(msg, None)
776 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
777 match self.nodes.get_mut(&msg.node_id) {
778 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
780 if let Some(node_info) = node.announcement_info.as_ref() {
781 if node_info.last_update >= msg.timestamp {
782 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
787 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
788 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
789 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
790 node.announcement_info = Some(NodeAnnouncementInfo {
791 features: msg.features.clone(),
792 last_update: msg.timestamp,
795 addresses: msg.addresses.clone(),
796 announcement_message: if should_relay { full_msg.cloned() } else { None },
804 /// Store or update channel info from a channel announcement.
806 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
807 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
808 /// routing messages from a source using a protocol other than the lightning P2P protocol.
810 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
811 /// the corresponding UTXO exists on chain and is correctly-formatted.
812 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
813 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
814 -> Result<(), LightningError>
815 where C::Target: chain::Access {
816 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
817 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
818 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
819 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
820 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
821 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
824 /// Store or update channel info from a channel announcement without verifying the associated
825 /// signatures. Because we aren't given the associated signatures here we cannot relay the
826 /// channel announcement to any of our peers.
828 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
829 /// the corresponding UTXO exists on chain and is correctly-formatted.
830 pub fn update_channel_from_unsigned_announcement<C: Deref>
831 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
832 -> Result<(), LightningError>
833 where C::Target: chain::Access {
834 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
837 fn update_channel_from_unsigned_announcement_intern<C: Deref>
838 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
839 -> Result<(), LightningError>
840 where C::Target: chain::Access {
841 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
842 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
845 let utxo_value = match &chain_access {
847 // Tentatively accept, potentially exposing us to DoS attacks
850 &Some(ref chain_access) => {
851 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
852 Ok(TxOut { value, script_pubkey }) => {
853 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
854 .push_slice(&msg.bitcoin_key_1.serialize())
855 .push_slice(&msg.bitcoin_key_2.serialize())
856 .push_opcode(opcodes::all::OP_PUSHNUM_2)
857 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
858 if script_pubkey != expected_script {
859 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});
861 //TODO: Check if value is worth storing, use it to inform routing, and compare it
862 //to the new HTLC max field in channel_update
865 Err(chain::AccessError::UnknownChain) => {
866 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
868 Err(chain::AccessError::UnknownTx) => {
869 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
875 let chan_info = ChannelInfo {
876 features: msg.features.clone(),
877 node_one: msg.node_id_1.clone(),
879 node_two: msg.node_id_2.clone(),
881 capacity_sats: utxo_value,
882 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
883 { full_msg.cloned() } else { None },
886 match self.channels.entry(msg.short_channel_id) {
887 BtreeEntry::Occupied(mut entry) => {
888 //TODO: because asking the blockchain if short_channel_id is valid is only optional
889 //in the blockchain API, we need to handle it smartly here, though it's unclear
891 if utxo_value.is_some() {
892 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
893 // only sometimes returns results. In any case remove the previous entry. Note
894 // that the spec expects us to "blacklist" the node_ids involved, but we can't
896 // a) we don't *require* a UTXO provider that always returns results.
897 // b) we don't track UTXOs of channels we know about and remove them if they
899 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
900 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
901 *entry.get_mut() = chan_info;
903 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
906 BtreeEntry::Vacant(entry) => {
907 entry.insert(chan_info);
911 macro_rules! add_channel_to_node {
912 ( $node_id: expr ) => {
913 match self.nodes.entry($node_id) {
914 BtreeEntry::Occupied(node_entry) => {
915 node_entry.into_mut().channels.push(msg.short_channel_id);
917 BtreeEntry::Vacant(node_entry) => {
918 node_entry.insert(NodeInfo {
919 channels: vec!(msg.short_channel_id),
920 lowest_inbound_channel_fees: None,
921 announcement_info: None,
928 add_channel_to_node!(msg.node_id_1);
929 add_channel_to_node!(msg.node_id_2);
934 /// Close a channel if a corresponding HTLC fail was sent.
935 /// If permanent, removes a channel from the local storage.
936 /// May cause the removal of nodes too, if this was their last channel.
937 /// If not permanent, makes channels unavailable for routing.
938 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
940 if let Some(chan) = self.channels.remove(&short_channel_id) {
941 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
944 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
945 if let Some(one_to_two) = chan.one_to_two.as_mut() {
946 one_to_two.enabled = false;
948 if let Some(two_to_one) = chan.two_to_one.as_mut() {
949 two_to_one.enabled = false;
955 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
957 // TODO: Wholly remove the node
959 // TODO: downgrade the node
963 /// For an already known (from announcement) channel, update info about one of the directions
966 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
967 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
968 /// routing messages from a source using a protocol other than the lightning P2P protocol.
969 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
970 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
973 /// For an already known (from announcement) channel, update info about one of the directions
974 /// of the channel without verifying the associated signatures. Because we aren't given the
975 /// associated signatures here we cannot relay the channel update to any of our peers.
976 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
977 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
980 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> {
982 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
983 let chan_was_enabled;
985 match self.channels.get_mut(&msg.short_channel_id) {
986 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
988 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
989 if htlc_maximum_msat > MAX_VALUE_MSAT {
990 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
993 if let Some(capacity_sats) = channel.capacity_sats {
994 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
995 // Don't query UTXO set here to reduce DoS risks.
996 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
997 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1001 macro_rules! maybe_update_channel_info {
1002 ( $target: expr, $src_node: expr) => {
1003 if let Some(existing_chan_info) = $target.as_ref() {
1004 if existing_chan_info.last_update >= msg.timestamp {
1005 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
1007 chan_was_enabled = existing_chan_info.enabled;
1009 chan_was_enabled = false;
1012 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1013 { full_msg.cloned() } else { None };
1015 let updated_channel_dir_info = DirectionalChannelInfo {
1016 enabled: chan_enabled,
1017 last_update: msg.timestamp,
1018 cltv_expiry_delta: msg.cltv_expiry_delta,
1019 htlc_minimum_msat: msg.htlc_minimum_msat,
1020 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1022 base_msat: msg.fee_base_msat,
1023 proportional_millionths: msg.fee_proportional_millionths,
1027 $target = Some(updated_channel_dir_info);
1031 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1032 if msg.flags & 1 == 1 {
1033 dest_node_id = channel.node_one.clone();
1034 if let Some((sig, ctx)) = sig_info {
1035 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1037 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1039 dest_node_id = channel.node_two.clone();
1040 if let Some((sig, ctx)) = sig_info {
1041 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1043 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1049 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1050 let mut base_msat = msg.fee_base_msat;
1051 let mut proportional_millionths = msg.fee_proportional_millionths;
1052 if let Some(fees) = node.lowest_inbound_channel_fees {
1053 base_msat = cmp::min(base_msat, fees.base_msat);
1054 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1056 node.lowest_inbound_channel_fees = Some(RoutingFees {
1058 proportional_millionths
1060 } else if chan_was_enabled {
1061 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1062 let mut lowest_inbound_channel_fees = None;
1064 for chan_id in node.channels.iter() {
1065 let chan = self.channels.get(chan_id).unwrap();
1067 if chan.node_one == dest_node_id {
1068 chan_info_opt = chan.two_to_one.as_ref();
1070 chan_info_opt = chan.one_to_two.as_ref();
1072 if let Some(chan_info) = chan_info_opt {
1073 if chan_info.enabled {
1074 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1075 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1076 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1077 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1082 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1088 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1089 macro_rules! remove_from_node {
1090 ($node_id: expr) => {
1091 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1092 entry.get_mut().channels.retain(|chan_id| {
1093 short_channel_id != *chan_id
1095 if entry.get().channels.is_empty() {
1096 entry.remove_entry();
1099 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1104 remove_from_node!(chan.node_one);
1105 remove_from_node!(chan.node_two);
1112 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1113 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
1114 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1115 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1116 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1117 use util::test_utils;
1118 use util::logger::Logger;
1119 use util::ser::{Readable, Writeable};
1120 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1121 use util::scid_utils::scid_from_parts;
1123 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1124 use bitcoin::hashes::Hash;
1125 use bitcoin::network::constants::Network;
1126 use bitcoin::blockdata::constants::genesis_block;
1127 use bitcoin::blockdata::script::Builder;
1128 use bitcoin::blockdata::transaction::TxOut;
1129 use bitcoin::blockdata::opcodes;
1133 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1134 use bitcoin::secp256k1::{All, Secp256k1};
1138 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1139 let secp_ctx = Secp256k1::new();
1140 let logger = Arc::new(test_utils::TestLogger::new());
1141 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1142 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1143 (secp_ctx, net_graph_msg_handler)
1147 fn request_full_sync_finite_times() {
1148 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1149 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1151 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1152 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1153 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1154 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1155 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1156 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1160 fn handling_node_announcements() {
1161 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1163 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1164 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1165 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1166 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1167 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1168 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1169 let zero_hash = Sha256dHash::hash(&[0; 32]);
1170 let first_announcement_time = 500;
1172 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1173 features: NodeFeatures::known(),
1174 timestamp: first_announcement_time,
1178 addresses: Vec::new(),
1179 excess_address_data: Vec::new(),
1180 excess_data: Vec::new(),
1182 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1183 let valid_announcement = NodeAnnouncement {
1184 signature: secp_ctx.sign(&msghash, node_1_privkey),
1185 contents: unsigned_announcement.clone()
1188 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1190 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1194 // Announce a channel to add a corresponding node.
1195 let unsigned_announcement = UnsignedChannelAnnouncement {
1196 features: ChannelFeatures::known(),
1197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1198 short_channel_id: 0,
1201 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1202 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1203 excess_data: Vec::new(),
1206 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1207 let valid_announcement = ChannelAnnouncement {
1208 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1209 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1210 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1211 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1212 contents: unsigned_announcement.clone(),
1214 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1215 Ok(res) => assert!(res),
1220 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1221 Ok(res) => assert!(res),
1225 let fake_msghash = hash_to_message!(&zero_hash);
1226 match net_graph_msg_handler.handle_node_announcement(
1228 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1229 contents: unsigned_announcement.clone()
1232 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1235 unsigned_announcement.timestamp += 1000;
1236 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1237 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1238 let announcement_with_data = NodeAnnouncement {
1239 signature: secp_ctx.sign(&msghash, node_1_privkey),
1240 contents: unsigned_announcement.clone()
1242 // Return false because contains excess data.
1243 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1244 Ok(res) => assert!(!res),
1247 unsigned_announcement.excess_data = Vec::new();
1249 // Even though previous announcement was not relayed further, we still accepted it,
1250 // so we now won't accept announcements before the previous one.
1251 unsigned_announcement.timestamp -= 10;
1252 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1253 let outdated_announcement = NodeAnnouncement {
1254 signature: secp_ctx.sign(&msghash, node_1_privkey),
1255 contents: unsigned_announcement.clone()
1257 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1259 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1264 fn handling_channel_announcements() {
1265 let secp_ctx = Secp256k1::new();
1266 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1268 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1269 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1270 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1271 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1272 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1273 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1275 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1276 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1277 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1278 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1279 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1282 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1283 features: ChannelFeatures::known(),
1284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1285 short_channel_id: 0,
1288 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1289 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1290 excess_data: Vec::new(),
1293 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1294 let valid_announcement = ChannelAnnouncement {
1295 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1296 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1297 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1298 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1299 contents: unsigned_announcement.clone(),
1302 // Test if the UTXO lookups were not supported
1303 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1304 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1305 Ok(res) => assert!(res),
1310 let network = net_graph_msg_handler.network_graph.read().unwrap();
1311 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1317 // If we receive announcement for the same channel (with UTXO lookups disabled),
1318 // drop new one on the floor, since we can't see any changes.
1319 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1321 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1324 // Test if an associated transaction were not on-chain (or not confirmed).
1325 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1326 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1327 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1328 unsigned_announcement.short_channel_id += 1;
1330 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1331 let valid_announcement = ChannelAnnouncement {
1332 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1333 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1334 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1335 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1336 contents: unsigned_announcement.clone(),
1339 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1341 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1344 // Now test if the transaction is found in the UTXO set and the script is correct.
1345 unsigned_announcement.short_channel_id += 1;
1346 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1348 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1349 let valid_announcement = ChannelAnnouncement {
1350 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1351 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1352 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1353 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1354 contents: unsigned_announcement.clone(),
1356 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1357 Ok(res) => assert!(res),
1362 let network = net_graph_msg_handler.network_graph.read().unwrap();
1363 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1369 // If we receive announcement for the same channel (but TX is not confirmed),
1370 // drop new one on the floor, since we can't see any changes.
1371 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1372 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1374 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1377 // But if it is confirmed, replace the channel
1378 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1379 unsigned_announcement.features = ChannelFeatures::empty();
1380 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1381 let valid_announcement = ChannelAnnouncement {
1382 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1383 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1384 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1385 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1386 contents: unsigned_announcement.clone(),
1388 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1389 Ok(res) => assert!(res),
1393 let network = net_graph_msg_handler.network_graph.read().unwrap();
1394 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1395 Some(channel_entry) => {
1396 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1402 // Don't relay valid channels with excess data
1403 unsigned_announcement.short_channel_id += 1;
1404 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1405 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1406 let valid_announcement = ChannelAnnouncement {
1407 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1408 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1409 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1410 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1411 contents: unsigned_announcement.clone(),
1413 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1414 Ok(res) => assert!(!res),
1418 unsigned_announcement.excess_data = Vec::new();
1419 let invalid_sig_announcement = ChannelAnnouncement {
1420 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1421 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1422 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1423 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1424 contents: unsigned_announcement.clone(),
1426 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1428 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1431 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1432 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1433 let channel_to_itself_announcement = ChannelAnnouncement {
1434 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1435 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1436 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1437 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1438 contents: unsigned_announcement.clone(),
1440 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1442 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1447 fn handling_channel_update() {
1448 let secp_ctx = Secp256k1::new();
1449 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1450 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1451 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1453 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1454 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1455 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1456 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1457 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1458 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1460 let zero_hash = Sha256dHash::hash(&[0; 32]);
1461 let short_channel_id = 0;
1462 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1463 let amount_sats = 1000_000;
1466 // Announce a channel we will update
1467 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1468 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1469 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1470 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1471 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1472 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1473 let unsigned_announcement = UnsignedChannelAnnouncement {
1474 features: ChannelFeatures::empty(),
1479 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1480 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1481 excess_data: Vec::new(),
1484 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1485 let valid_channel_announcement = ChannelAnnouncement {
1486 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1487 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1488 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1489 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1490 contents: unsigned_announcement.clone(),
1492 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1499 let mut unsigned_channel_update = UnsignedChannelUpdate {
1504 cltv_expiry_delta: 144,
1505 htlc_minimum_msat: 1000000,
1506 htlc_maximum_msat: OptionalField::Absent,
1507 fee_base_msat: 10000,
1508 fee_proportional_millionths: 20,
1509 excess_data: Vec::new()
1511 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1512 let valid_channel_update = ChannelUpdate {
1513 signature: secp_ctx.sign(&msghash, node_1_privkey),
1514 contents: unsigned_channel_update.clone()
1517 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1518 Ok(res) => assert!(res),
1523 let network = net_graph_msg_handler.network_graph.read().unwrap();
1524 match network.get_channels().get(&short_channel_id) {
1526 Some(channel_info) => {
1527 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1528 assert!(channel_info.two_to_one.is_none());
1533 unsigned_channel_update.timestamp += 100;
1534 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1535 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1536 let valid_channel_update = ChannelUpdate {
1537 signature: secp_ctx.sign(&msghash, node_1_privkey),
1538 contents: unsigned_channel_update.clone()
1540 // Return false because contains excess data
1541 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1542 Ok(res) => assert!(!res),
1545 unsigned_channel_update.timestamp += 10;
1547 unsigned_channel_update.short_channel_id += 1;
1548 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1549 let valid_channel_update = ChannelUpdate {
1550 signature: secp_ctx.sign(&msghash, node_1_privkey),
1551 contents: unsigned_channel_update.clone()
1554 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1556 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1558 unsigned_channel_update.short_channel_id = short_channel_id;
1560 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1561 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1562 let valid_channel_update = ChannelUpdate {
1563 signature: secp_ctx.sign(&msghash, node_1_privkey),
1564 contents: unsigned_channel_update.clone()
1567 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1569 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1571 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1573 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1574 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1575 let valid_channel_update = ChannelUpdate {
1576 signature: secp_ctx.sign(&msghash, node_1_privkey),
1577 contents: unsigned_channel_update.clone()
1580 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1582 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1584 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1586 // Even though previous update was not relayed further, we still accepted it,
1587 // so we now won't accept update before the previous one.
1588 unsigned_channel_update.timestamp -= 10;
1589 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1590 let valid_channel_update = ChannelUpdate {
1591 signature: secp_ctx.sign(&msghash, node_1_privkey),
1592 contents: unsigned_channel_update.clone()
1595 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1597 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1599 unsigned_channel_update.timestamp += 500;
1601 let fake_msghash = hash_to_message!(&zero_hash);
1602 let invalid_sig_channel_update = ChannelUpdate {
1603 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1604 contents: unsigned_channel_update.clone()
1607 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1609 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1615 fn handling_htlc_fail_channel_update() {
1616 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1617 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1618 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1619 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1620 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1621 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1622 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1624 let short_channel_id = 0;
1625 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1628 // There is no nodes in the table at the beginning.
1629 let network = net_graph_msg_handler.network_graph.read().unwrap();
1630 assert_eq!(network.get_nodes().len(), 0);
1634 // Announce a channel we will update
1635 let unsigned_announcement = UnsignedChannelAnnouncement {
1636 features: ChannelFeatures::empty(),
1641 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1642 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1643 excess_data: Vec::new(),
1646 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1647 let valid_channel_announcement = ChannelAnnouncement {
1648 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1649 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1650 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1651 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1652 contents: unsigned_announcement.clone(),
1654 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1659 let unsigned_channel_update = UnsignedChannelUpdate {
1664 cltv_expiry_delta: 144,
1665 htlc_minimum_msat: 1000000,
1666 htlc_maximum_msat: OptionalField::Absent,
1667 fee_base_msat: 10000,
1668 fee_proportional_millionths: 20,
1669 excess_data: Vec::new()
1671 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1672 let valid_channel_update = ChannelUpdate {
1673 signature: secp_ctx.sign(&msghash, node_1_privkey),
1674 contents: unsigned_channel_update.clone()
1677 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1678 Ok(res) => assert!(res),
1683 // Non-permanent closing just disables a channel
1685 let network = net_graph_msg_handler.network_graph.read().unwrap();
1686 match network.get_channels().get(&short_channel_id) {
1688 Some(channel_info) => {
1689 assert!(channel_info.one_to_two.is_some());
1694 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1699 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1701 // Non-permanent closing just disables a channel
1703 let network = net_graph_msg_handler.network_graph.read().unwrap();
1704 match network.get_channels().get(&short_channel_id) {
1706 Some(channel_info) => {
1707 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1712 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1717 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1719 // Permanent closing deletes a channel
1721 let network = net_graph_msg_handler.network_graph.read().unwrap();
1722 assert_eq!(network.get_channels().len(), 0);
1723 // Nodes are also deleted because there are no associated channels anymore
1724 assert_eq!(network.get_nodes().len(), 0);
1726 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1730 fn getting_next_channel_announcements() {
1731 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1732 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1733 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1734 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1735 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1736 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1737 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1739 let short_channel_id = 1;
1740 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1742 // Channels were not announced yet.
1743 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1744 assert_eq!(channels_with_announcements.len(), 0);
1747 // Announce a channel we will update
1748 let unsigned_announcement = UnsignedChannelAnnouncement {
1749 features: ChannelFeatures::empty(),
1754 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1755 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1756 excess_data: Vec::new(),
1759 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1760 let valid_channel_announcement = ChannelAnnouncement {
1761 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1762 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1763 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1764 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1765 contents: unsigned_announcement.clone(),
1767 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1773 // Contains initial channel announcement now.
1774 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1775 assert_eq!(channels_with_announcements.len(), 1);
1776 if let Some(channel_announcements) = channels_with_announcements.first() {
1777 let &(_, ref update_1, ref update_2) = channel_announcements;
1778 assert_eq!(update_1, &None);
1779 assert_eq!(update_2, &None);
1786 // Valid channel update
1787 let unsigned_channel_update = UnsignedChannelUpdate {
1792 cltv_expiry_delta: 144,
1793 htlc_minimum_msat: 1000000,
1794 htlc_maximum_msat: OptionalField::Absent,
1795 fee_base_msat: 10000,
1796 fee_proportional_millionths: 20,
1797 excess_data: Vec::new()
1799 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1800 let valid_channel_update = ChannelUpdate {
1801 signature: secp_ctx.sign(&msghash, node_1_privkey),
1802 contents: unsigned_channel_update.clone()
1804 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1810 // Now contains an initial announcement and an update.
1811 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1812 assert_eq!(channels_with_announcements.len(), 1);
1813 if let Some(channel_announcements) = channels_with_announcements.first() {
1814 let &(_, ref update_1, ref update_2) = channel_announcements;
1815 assert_ne!(update_1, &None);
1816 assert_eq!(update_2, &None);
1823 // Channel update with excess data.
1824 let unsigned_channel_update = UnsignedChannelUpdate {
1829 cltv_expiry_delta: 144,
1830 htlc_minimum_msat: 1000000,
1831 htlc_maximum_msat: OptionalField::Absent,
1832 fee_base_msat: 10000,
1833 fee_proportional_millionths: 20,
1834 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1836 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1837 let valid_channel_update = ChannelUpdate {
1838 signature: secp_ctx.sign(&msghash, node_1_privkey),
1839 contents: unsigned_channel_update.clone()
1841 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1847 // Test that announcements with excess data won't be returned
1848 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1849 assert_eq!(channels_with_announcements.len(), 1);
1850 if let Some(channel_announcements) = channels_with_announcements.first() {
1851 let &(_, ref update_1, ref update_2) = channel_announcements;
1852 assert_eq!(update_1, &None);
1853 assert_eq!(update_2, &None);
1858 // Further starting point have no channels after it
1859 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1860 assert_eq!(channels_with_announcements.len(), 0);
1864 fn getting_next_node_announcements() {
1865 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1866 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1867 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1868 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1869 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1870 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1871 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1873 let short_channel_id = 1;
1874 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1877 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1878 assert_eq!(next_announcements.len(), 0);
1881 // Announce a channel to add 2 nodes
1882 let unsigned_announcement = UnsignedChannelAnnouncement {
1883 features: ChannelFeatures::empty(),
1888 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1889 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1890 excess_data: Vec::new(),
1893 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1894 let valid_channel_announcement = ChannelAnnouncement {
1895 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1896 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1897 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1898 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1899 contents: unsigned_announcement.clone(),
1901 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1908 // Nodes were never announced
1909 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1910 assert_eq!(next_announcements.len(), 0);
1913 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1914 features: NodeFeatures::known(),
1919 addresses: Vec::new(),
1920 excess_address_data: Vec::new(),
1921 excess_data: Vec::new(),
1923 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1924 let valid_announcement = NodeAnnouncement {
1925 signature: secp_ctx.sign(&msghash, node_1_privkey),
1926 contents: unsigned_announcement.clone()
1928 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1933 unsigned_announcement.node_id = node_id_2;
1934 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1935 let valid_announcement = NodeAnnouncement {
1936 signature: secp_ctx.sign(&msghash, node_2_privkey),
1937 contents: unsigned_announcement.clone()
1940 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1946 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1947 assert_eq!(next_announcements.len(), 2);
1949 // Skip the first node.
1950 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1951 assert_eq!(next_announcements.len(), 1);
1954 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1955 let unsigned_announcement = UnsignedNodeAnnouncement {
1956 features: NodeFeatures::known(),
1961 addresses: Vec::new(),
1962 excess_address_data: Vec::new(),
1963 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
1965 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1966 let valid_announcement = NodeAnnouncement {
1967 signature: secp_ctx.sign(&msghash, node_2_privkey),
1968 contents: unsigned_announcement.clone()
1970 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1971 Ok(res) => assert!(!res),
1976 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1977 assert_eq!(next_announcements.len(), 0);
1981 fn network_graph_serialization() {
1982 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1984 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1985 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1986 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1987 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1989 // Announce a channel to add a corresponding node.
1990 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1991 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1992 let unsigned_announcement = UnsignedChannelAnnouncement {
1993 features: ChannelFeatures::known(),
1994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1995 short_channel_id: 0,
1998 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1999 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2000 excess_data: Vec::new(),
2003 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2004 let valid_announcement = ChannelAnnouncement {
2005 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2006 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2007 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2008 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2009 contents: unsigned_announcement.clone(),
2011 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2012 Ok(res) => assert!(res),
2017 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2018 let unsigned_announcement = UnsignedNodeAnnouncement {
2019 features: NodeFeatures::known(),
2024 addresses: Vec::new(),
2025 excess_address_data: Vec::new(),
2026 excess_data: Vec::new(),
2028 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2029 let valid_announcement = NodeAnnouncement {
2030 signature: secp_ctx.sign(&msghash, node_1_privkey),
2031 contents: unsigned_announcement.clone()
2034 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2039 let network = net_graph_msg_handler.network_graph.write().unwrap();
2040 let mut w = test_utils::TestVecWriter(Vec::new());
2041 assert!(!network.get_nodes().is_empty());
2042 assert!(!network.get_channels().is_empty());
2043 network.write(&mut w).unwrap();
2044 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
2048 fn calling_sync_routing_table() {
2049 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2050 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2051 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2053 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2054 let first_blocknum = 0;
2055 let number_of_blocks = 0xffff_ffff;
2057 // It should ignore if gossip_queries feature is not enabled
2059 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2060 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2061 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2062 assert_eq!(events.len(), 0);
2065 // It should send a query_channel_message with the correct information
2067 let init_msg = Init { features: InitFeatures::known() };
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(), 1);
2072 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2073 assert_eq!(node_id, &node_id_1);
2074 assert_eq!(msg.chain_hash, chain_hash);
2075 assert_eq!(msg.first_blocknum, first_blocknum);
2076 assert_eq!(msg.number_of_blocks, number_of_blocks);
2078 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2082 // It should not enqueue a query when should_request_full_sync return false.
2083 // The initial implementation allows syncing with the first 5 peers after
2084 // which should_request_full_sync will return false
2086 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2087 let init_msg = Init { features: InitFeatures::known() };
2089 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2090 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2091 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2092 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2094 assert_eq!(events.len(), 1);
2096 assert_eq!(events.len(), 0);
2104 fn handling_reply_channel_range() {
2105 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2106 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2107 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2109 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2111 // Test receipt of a single reply that should enqueue an SCID query
2112 // matching the SCIDs in the reply
2114 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2116 sync_complete: true,
2118 number_of_blocks: 2000,
2119 short_channel_ids: vec![
2120 0x0003e0_000000_0000, // 992x0x0
2121 0x0003e8_000000_0000, // 1000x0x0
2122 0x0003e9_000000_0000, // 1001x0x0
2123 0x0003f0_000000_0000, // 1008x0x0
2124 0x00044c_000000_0000, // 1100x0x0
2125 0x0006e0_000000_0000, // 1760x0x0
2128 assert!(result.is_ok());
2130 // We expect to emit a query_short_channel_ids message with the received scids
2131 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2132 assert_eq!(events.len(), 1);
2134 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2135 assert_eq!(node_id, &node_id_1);
2136 assert_eq!(msg.chain_hash, chain_hash);
2137 assert_eq!(msg.short_channel_ids, vec![
2138 0x0003e0_000000_0000, // 992x0x0
2139 0x0003e8_000000_0000, // 1000x0x0
2140 0x0003e9_000000_0000, // 1001x0x0
2141 0x0003f0_000000_0000, // 1008x0x0
2142 0x00044c_000000_0000, // 1100x0x0
2143 0x0006e0_000000_0000, // 1760x0x0
2146 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2152 fn handling_reply_short_channel_ids() {
2153 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2154 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2155 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2157 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2159 // Test receipt of a successful reply
2161 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2163 full_information: true,
2165 assert!(result.is_ok());
2168 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2169 // for the chain_hash requested in the query.
2171 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2173 full_information: false,
2175 assert!(result.is_err());
2176 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2181 fn handling_query_channel_range() {
2182 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2184 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2185 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2186 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2187 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2188 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2189 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2190 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2191 let bitcoin_key_1 = PublicKey::from_secret_key(&secp_ctx, node_1_btckey);
2192 let bitcoin_key_2 = PublicKey::from_secret_key(&secp_ctx, node_2_btckey);
2194 let mut scids: Vec<u64> = vec![
2195 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2196 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2199 // used for testing multipart reply across blocks
2200 for block in 100000..=108001 {
2201 scids.push(scid_from_parts(block, 0, 0).unwrap());
2204 // used for testing resumption on same block
2205 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2206 scids.push(scid_from_parts(108001, 2, 0).unwrap());
2209 let unsigned_announcement = UnsignedChannelAnnouncement {
2210 features: ChannelFeatures::known(),
2211 chain_hash: chain_hash.clone(),
2212 short_channel_id: scid,
2217 excess_data: Vec::new(),
2220 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2221 let valid_announcement = ChannelAnnouncement {
2222 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2223 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2224 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2225 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2226 contents: unsigned_announcement.clone(),
2228 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2234 // Empty reply when number_of_blocks=0
2235 do_handling_query_channel_range(
2236 &net_graph_msg_handler,
2239 chain_hash: chain_hash.clone(),
2241 number_of_blocks: 0,
2243 vec![ReplyChannelRange {
2244 chain_hash: chain_hash.clone(),
2246 number_of_blocks: 0,
2247 sync_complete: true,
2248 short_channel_ids: vec![]
2252 // Empty when wrong chain
2253 do_handling_query_channel_range(
2254 &net_graph_msg_handler,
2257 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2259 number_of_blocks: 0xffff_ffff,
2261 vec![ReplyChannelRange {
2262 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2264 number_of_blocks: 0xffff_ffff,
2265 sync_complete: true,
2266 short_channel_ids: vec![],
2270 // Empty reply when first_blocknum > 0xffffff
2271 do_handling_query_channel_range(
2272 &net_graph_msg_handler,
2275 chain_hash: chain_hash.clone(),
2276 first_blocknum: 0x01000000,
2277 number_of_blocks: 0xffff_ffff,
2279 vec![ReplyChannelRange {
2280 chain_hash: chain_hash.clone(),
2281 first_blocknum: 0x01000000,
2282 number_of_blocks: 0xffff_ffff,
2283 sync_complete: true,
2284 short_channel_ids: vec![]
2288 // Empty reply when max valid SCID block num.
2289 // Unlike prior test this is a valid query but no results are found
2290 do_handling_query_channel_range(
2291 &net_graph_msg_handler,
2294 chain_hash: chain_hash.clone(),
2295 first_blocknum: 0xffffff,
2296 number_of_blocks: 1,
2300 chain_hash: chain_hash.clone(),
2301 first_blocknum: 0xffffff,
2302 number_of_blocks: 1,
2303 sync_complete: true,
2304 short_channel_ids: vec![]
2309 // No results in valid query range
2310 do_handling_query_channel_range(
2311 &net_graph_msg_handler,
2314 chain_hash: chain_hash.clone(),
2315 first_blocknum: 0x00800000,
2316 number_of_blocks: 1000,
2320 chain_hash: chain_hash.clone(),
2321 first_blocknum: 0x00800000,
2322 number_of_blocks: 1000,
2323 sync_complete: true,
2324 short_channel_ids: vec![],
2329 // Overflow first_blocknum + number_of_blocks
2330 do_handling_query_channel_range(
2331 &net_graph_msg_handler,
2334 chain_hash: chain_hash.clone(),
2335 first_blocknum: 0xfe0000,
2336 number_of_blocks: 0xffffffff,
2340 chain_hash: chain_hash.clone(),
2341 first_blocknum: 0xfe0000,
2342 number_of_blocks: 0xffffffff - 0xfe0000,
2343 sync_complete: true,
2344 short_channel_ids: vec![
2345 0xfffffe_ffffff_ffff, // max
2351 // Multiple split on new block
2352 do_handling_query_channel_range(
2353 &net_graph_msg_handler,
2356 chain_hash: chain_hash.clone(),
2357 first_blocknum: 100000,
2358 number_of_blocks: 8001,
2362 chain_hash: chain_hash.clone(),
2363 first_blocknum: 100000,
2364 number_of_blocks: 8000,
2365 sync_complete: false,
2366 short_channel_ids: (100000..=107999)
2367 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2371 chain_hash: chain_hash.clone(),
2372 first_blocknum: 108000,
2373 number_of_blocks: 1,
2374 sync_complete: true,
2375 short_channel_ids: vec![
2376 scid_from_parts(108000, 0, 0).unwrap(),
2382 // Multiple split on same block
2383 do_handling_query_channel_range(
2384 &net_graph_msg_handler,
2387 chain_hash: chain_hash.clone(),
2388 first_blocknum: 100002,
2389 number_of_blocks: 8000,
2393 chain_hash: chain_hash.clone(),
2394 first_blocknum: 100002,
2395 number_of_blocks: 8000,
2396 sync_complete: false,
2397 short_channel_ids: (100002..=108001)
2398 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2402 chain_hash: chain_hash.clone(),
2403 first_blocknum: 108001,
2404 number_of_blocks: 1,
2405 sync_complete: true,
2406 short_channel_ids: vec![
2407 scid_from_parts(108001, 1, 0).unwrap(),
2408 scid_from_parts(108001, 2, 0).unwrap(),
2415 fn do_handling_query_channel_range(
2416 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2417 test_node_id: &PublicKey,
2418 msg: QueryChannelRange,
2419 expected_replies: Vec<ReplyChannelRange>
2421 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2422 assert!(result.is_ok());
2424 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2425 assert_eq!(events.len(), expected_replies.len());
2427 for i in 0..events.len() {
2428 let expected_reply = &expected_replies[i];
2430 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2431 assert_eq!(node_id, test_node_id);
2432 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2433 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2434 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2435 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2436 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2438 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2444 fn handling_query_short_channel_ids() {
2445 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2446 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2447 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2449 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2451 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2453 short_channel_ids: vec![0x0003e8_000000_0000],
2455 assert!(result.is_err());