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, Level};
32 use util::events::{MessageSendEvent, MessageSendEventsProvider};
33 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
37 use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
39 use sync::{RwLock, RwLockReadGuard};
40 use core::sync::atomic::{AtomicUsize, Ordering};
43 use bitcoin::hashes::hex::ToHex;
45 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
46 /// refuse to relay the message.
47 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
49 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
50 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
51 const MAX_SCIDS_PER_REPLY: usize = 8000;
53 /// Represents the network as nodes and channels between them
54 pub struct NetworkGraph {
55 genesis_hash: BlockHash,
56 // Lock order: channels -> nodes
57 channels: RwLock<BTreeMap<u64, ChannelInfo>>,
58 nodes: RwLock<BTreeMap<PublicKey, NodeInfo>>,
61 /// A read-only view of [`NetworkGraph`].
62 pub struct ReadOnlyNetworkGraph<'a> {
63 channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
64 nodes: RwLockReadGuard<'a, BTreeMap<PublicKey, NodeInfo>>,
67 /// Receives and validates network updates from peers,
68 /// stores authentic and relevant data as a network graph.
69 /// This network graph is then used for routing payments.
70 /// Provides interface to help with initial routing sync by
71 /// serving historical announcements.
72 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
73 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
74 /// Representation of the payment channel network
75 pub network_graph: NetworkGraph,
76 chain_access: Option<C>,
77 full_syncs_requested: AtomicUsize,
78 pending_events: Mutex<Vec<MessageSendEvent>>,
82 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
83 /// Creates a new tracker of the actual state of the network of channels and nodes,
84 /// assuming a fresh network graph.
85 /// Chain monitor is used to make sure announced channels exist on-chain,
86 /// channel data is correct, and that the announcement is signed with
87 /// channel owners' keys.
88 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
90 secp_ctx: Secp256k1::verification_only(),
91 network_graph: NetworkGraph::new(genesis_hash),
92 full_syncs_requested: AtomicUsize::new(0),
94 pending_events: Mutex::new(vec![]),
99 /// Creates a new tracker of the actual state of the network of channels and nodes,
100 /// assuming an existing Network Graph.
101 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
103 secp_ctx: Secp256k1::verification_only(),
105 full_syncs_requested: AtomicUsize::new(0),
107 pending_events: Mutex::new(vec![]),
112 /// Adds a provider used to check new announcements. Does not affect
113 /// existing announcements unless they are updated.
114 /// Add, update or remove the provider would replace the current one.
115 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
116 self.chain_access = chain_access;
119 /// Returns true when a full routing table sync should be performed with a peer.
120 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
121 //TODO: Determine whether to request a full sync based on the network map.
122 const FULL_SYNCS_TO_REQUEST: usize = 5;
123 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
124 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
132 macro_rules! secp_verify_sig {
133 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
134 match $secp_ctx.verify($msg, $sig, $pubkey) {
136 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
141 impl<C: Deref , L: Deref > RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
142 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
143 self.network_graph.update_node_from_announcement(msg, &self.secp_ctx)?;
144 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
145 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
146 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
149 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
150 self.network_graph.update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
151 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 { "" });
152 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
155 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
157 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
158 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
159 log_debug!(self.logger, "Updating channel with channel_update from a payment failure. Channel {} is {}abled.", msg.contents.short_channel_id, if chan_enabled { "en" } else { "dis" });
160 let _ = self.network_graph.update_channel(msg, &self.secp_ctx);
162 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
163 log_debug!(self.logger, "{} channel graph entry for {} due to a payment failure.", if is_permanent { "Removing" } else { "Disabling" }, short_channel_id);
164 self.network_graph.close_channel_from_update(short_channel_id, is_permanent);
166 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
167 log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", if is_permanent { "Removing" } else { "Disabling" }, node_id);
168 self.network_graph.fail_node(node_id, is_permanent);
173 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
174 self.network_graph.update_channel(msg, &self.secp_ctx)?;
175 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
178 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
179 let mut result = Vec::with_capacity(batch_amount as usize);
180 let channels = self.network_graph.channels.read().unwrap();
181 let mut iter = channels.range(starting_point..);
182 while result.len() < batch_amount as usize {
183 if let Some((_, ref chan)) = iter.next() {
184 if chan.announcement_message.is_some() {
185 let chan_announcement = chan.announcement_message.clone().unwrap();
186 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
187 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
188 if let Some(one_to_two) = chan.one_to_two.as_ref() {
189 one_to_two_announcement = one_to_two.last_update_message.clone();
191 if let Some(two_to_one) = chan.two_to_one.as_ref() {
192 two_to_one_announcement = two_to_one.last_update_message.clone();
194 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
196 // TODO: We may end up sending un-announced channel_updates if we are sending
197 // initial sync data while receiving announce/updates for this channel.
206 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
207 let mut result = Vec::with_capacity(batch_amount as usize);
208 let nodes = self.network_graph.nodes.read().unwrap();
209 let mut iter = if let Some(pubkey) = starting_point {
210 let mut iter = nodes.range((*pubkey)..);
216 while result.len() < batch_amount as usize {
217 if let Some((_, ref node)) = iter.next() {
218 if let Some(node_info) = node.announcement_info.as_ref() {
219 if node_info.announcement_message.is_some() {
220 result.push(node_info.announcement_message.clone().unwrap());
230 /// Initiates a stateless sync of routing gossip information with a peer
231 /// using gossip_queries. The default strategy used by this implementation
232 /// is to sync the full block range with several peers.
234 /// We should expect one or more reply_channel_range messages in response
235 /// to our query_channel_range. Each reply will enqueue a query_scid message
236 /// to request gossip messages for each channel. The sync is considered complete
237 /// when the final reply_scids_end message is received, though we are not
238 /// tracking this directly.
239 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
241 // We will only perform a sync with peers that support gossip_queries.
242 if !init_msg.features.supports_gossip_queries() {
246 // Check if we need to perform a full synchronization with this peer
247 if !self.should_request_full_sync(their_node_id) {
251 let first_blocknum = 0;
252 let number_of_blocks = 0xffffffff;
253 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
254 let mut pending_events = self.pending_events.lock().unwrap();
255 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
256 node_id: their_node_id.clone(),
257 msg: QueryChannelRange {
258 chain_hash: self.network_graph.genesis_hash,
265 /// Statelessly processes a reply to a channel range query by immediately
266 /// sending an SCID query with SCIDs in the reply. To keep this handler
267 /// stateless, it does not validate the sequencing of replies for multi-
268 /// reply ranges. It does not validate whether the reply(ies) cover the
269 /// queried range. It also does not filter SCIDs to only those in the
270 /// original query range. We also do not validate that the chain_hash
271 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
272 /// does not match our chain_hash will be rejected when the announcement is
274 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
275 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(),);
277 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
278 let mut pending_events = self.pending_events.lock().unwrap();
279 pending_events.push(MessageSendEvent::SendShortIdsQuery {
280 node_id: their_node_id.clone(),
281 msg: QueryShortChannelIds {
282 chain_hash: msg.chain_hash,
283 short_channel_ids: msg.short_channel_ids,
290 /// When an SCID query is initiated the remote peer will begin streaming
291 /// gossip messages. In the event of a failure, we may have received
292 /// some channel information. Before trying with another peer, the
293 /// caller should update its set of SCIDs that need to be queried.
294 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
295 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
297 // If the remote node does not have up-to-date information for the
298 // chain_hash they will set full_information=false. We can fail
299 // the result and try again with a different peer.
300 if !msg.full_information {
301 return Err(LightningError {
302 err: String::from("Received reply_short_channel_ids_end with no information"),
303 action: ErrorAction::IgnoreError
310 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
311 /// are in the specified block range. Due to message size limits, large range
312 /// queries may result in several reply messages. This implementation enqueues
313 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
314 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
315 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
316 /// memory constrained systems.
317 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
318 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);
320 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
322 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
323 // If so, we manually cap the ending block to avoid this overflow.
324 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
326 // Per spec, we must reply to a query. Send an empty message when things are invalid.
327 if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
328 let mut pending_events = self.pending_events.lock().unwrap();
329 pending_events.push(MessageSendEvent::SendReplyChannelRange {
330 node_id: their_node_id.clone(),
331 msg: ReplyChannelRange {
332 chain_hash: msg.chain_hash.clone(),
333 first_blocknum: msg.first_blocknum,
334 number_of_blocks: msg.number_of_blocks,
336 short_channel_ids: vec![],
339 return Err(LightningError {
340 err: String::from("query_channel_range could not be processed"),
341 action: ErrorAction::IgnoreError,
345 // Creates channel batches. We are not checking if the channel is routable
346 // (has at least one update). A peer may still want to know the channel
347 // exists even if its not yet routable.
348 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
349 let channels = self.network_graph.channels.read().unwrap();
350 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
351 if let Some(chan_announcement) = &chan.announcement_message {
352 // Construct a new batch if last one is full
353 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
354 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
357 let batch = batches.last_mut().unwrap();
358 batch.push(chan_announcement.contents.short_channel_id);
363 let mut pending_events = self.pending_events.lock().unwrap();
364 let batch_count = batches.len();
365 let mut prev_batch_endblock = msg.first_blocknum;
366 for (batch_index, batch) in batches.into_iter().enumerate() {
367 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
368 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
370 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
371 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
372 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
373 // significant diversion from the requirements set by the spec, and, in case of blocks
374 // with no channel opens (e.g. empty blocks), requires that we use the previous value
375 // and *not* derive the first_blocknum from the actual first block of the reply.
376 let first_blocknum = prev_batch_endblock;
378 // Each message carries the number of blocks (from the `first_blocknum`) its contents
379 // fit in. Though there is no requirement that we use exactly the number of blocks its
380 // contents are from, except for the bogus requirements c-lightning enforces, above.
382 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
383 // >= the query's end block. Thus, for the last reply, we calculate the difference
384 // between the query's end block and the start of the reply.
386 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
387 // first_blocknum will be either msg.first_blocknum or a higher block height.
388 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
389 (true, msg.end_blocknum() - first_blocknum)
391 // Prior replies should use the number of blocks that fit into the reply. Overflow
392 // safe since first_blocknum is always <= last SCID's block.
394 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
397 prev_batch_endblock = first_blocknum + number_of_blocks;
399 pending_events.push(MessageSendEvent::SendReplyChannelRange {
400 node_id: their_node_id.clone(),
401 msg: ReplyChannelRange {
402 chain_hash: msg.chain_hash.clone(),
406 short_channel_ids: batch,
414 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
417 err: String::from("Not implemented"),
418 action: ErrorAction::IgnoreError,
423 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
425 C::Target: chain::Access,
428 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
429 let mut ret = Vec::new();
430 let mut pending_events = self.pending_events.lock().unwrap();
431 core::mem::swap(&mut ret, &mut pending_events);
436 #[derive(Clone, Debug, PartialEq)]
437 /// Details about one direction of a channel. Received
438 /// within a channel update.
439 pub struct DirectionalChannelInfo {
440 /// When the last update to the channel direction was issued.
441 /// Value is opaque, as set in the announcement.
442 pub last_update: u32,
443 /// Whether the channel can be currently used for payments (in this one direction).
445 /// The difference in CLTV values that you must have when routing through this channel.
446 pub cltv_expiry_delta: u16,
447 /// The minimum value, which must be relayed to the next hop via the channel
448 pub htlc_minimum_msat: u64,
449 /// The maximum value which may be relayed to the next hop via the channel.
450 pub htlc_maximum_msat: Option<u64>,
451 /// Fees charged when the channel is used for routing
452 pub fees: RoutingFees,
453 /// Most recent update for the channel received from the network
454 /// Mostly redundant with the data we store in fields explicitly.
455 /// Everything else is useful only for sending out for initial routing sync.
456 /// Not stored if contains excess data to prevent DoS.
457 pub last_update_message: Option<ChannelUpdate>,
460 impl fmt::Display for DirectionalChannelInfo {
461 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
462 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)?;
467 impl_writeable_tlv_based!(DirectionalChannelInfo, {
468 (0, last_update, required),
469 (2, enabled, required),
470 (4, cltv_expiry_delta, required),
471 (6, htlc_minimum_msat, required),
472 (8, htlc_maximum_msat, required),
473 (10, fees, required),
474 (12, last_update_message, required),
477 #[derive(Clone, Debug, PartialEq)]
478 /// Details about a channel (both directions).
479 /// Received within a channel announcement.
480 pub struct ChannelInfo {
481 /// Protocol features of a channel communicated during its announcement
482 pub features: ChannelFeatures,
483 /// Source node of the first direction of a channel
484 pub node_one: PublicKey,
485 /// Details about the first direction of a channel
486 pub one_to_two: Option<DirectionalChannelInfo>,
487 /// Source node of the second direction of a channel
488 pub node_two: PublicKey,
489 /// Details about the second direction of a channel
490 pub two_to_one: Option<DirectionalChannelInfo>,
491 /// The channel capacity as seen on-chain, if chain lookup is available.
492 pub capacity_sats: Option<u64>,
493 /// An initial announcement of the channel
494 /// Mostly redundant with the data we store in fields explicitly.
495 /// Everything else is useful only for sending out for initial routing sync.
496 /// Not stored if contains excess data to prevent DoS.
497 pub announcement_message: Option<ChannelAnnouncement>,
500 impl fmt::Display for ChannelInfo {
501 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
502 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
503 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
508 impl_writeable_tlv_based!(ChannelInfo, {
509 (0, features, required),
510 (2, node_one, required),
511 (4, one_to_two, required),
512 (6, node_two, required),
513 (8, two_to_one, required),
514 (10, capacity_sats, required),
515 (12, announcement_message, required),
519 /// Fees for routing via a given channel or a node
520 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
521 pub struct RoutingFees {
522 /// Flat routing fee in satoshis
524 /// Liquidity-based routing fee in millionths of a routed amount.
525 /// In other words, 10000 is 1%.
526 pub proportional_millionths: u32,
529 impl_writeable_tlv_based!(RoutingFees, {
530 (0, base_msat, required),
531 (2, proportional_millionths, required)
534 #[derive(Clone, Debug, PartialEq)]
535 /// Information received in the latest node_announcement from this node.
536 pub struct NodeAnnouncementInfo {
537 /// Protocol features the node announced support for
538 pub features: NodeFeatures,
539 /// When the last known update to the node state was issued.
540 /// Value is opaque, as set in the announcement.
541 pub last_update: u32,
542 /// Color assigned to the node
544 /// Moniker assigned to the node.
545 /// May be invalid or malicious (eg control chars),
546 /// should not be exposed to the user.
548 /// Internet-level addresses via which one can connect to the node
549 pub addresses: Vec<NetAddress>,
550 /// An initial announcement of the node
551 /// Mostly redundant with the data we store in fields explicitly.
552 /// Everything else is useful only for sending out for initial routing sync.
553 /// Not stored if contains excess data to prevent DoS.
554 pub announcement_message: Option<NodeAnnouncement>
557 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
558 (0, features, required),
559 (2, last_update, required),
561 (6, alias, required),
562 (8, announcement_message, option),
563 (10, addresses, vec_type),
566 #[derive(Clone, Debug, PartialEq)]
567 /// Details about a node in the network, known from the network announcement.
568 pub struct NodeInfo {
569 /// All valid channels a node has announced
570 pub channels: Vec<u64>,
571 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
572 /// The two fields (flat and proportional fee) are independent,
573 /// meaning they don't have to refer to the same channel.
574 pub lowest_inbound_channel_fees: Option<RoutingFees>,
575 /// More information about a node from node_announcement.
576 /// Optional because we store a Node entry after learning about it from
577 /// a channel announcement, but before receiving a node announcement.
578 pub announcement_info: Option<NodeAnnouncementInfo>
581 impl fmt::Display for NodeInfo {
582 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
583 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
584 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
589 impl_writeable_tlv_based!(NodeInfo, {
590 (0, lowest_inbound_channel_fees, option),
591 (2, announcement_info, option),
592 (4, channels, vec_type),
595 const SERIALIZATION_VERSION: u8 = 1;
596 const MIN_SERIALIZATION_VERSION: u8 = 1;
598 impl Writeable for NetworkGraph {
599 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
600 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
602 self.genesis_hash.write(writer)?;
603 let channels = self.channels.read().unwrap();
604 (channels.len() as u64).write(writer)?;
605 for (ref chan_id, ref chan_info) in channels.iter() {
606 (*chan_id).write(writer)?;
607 chan_info.write(writer)?;
609 let nodes = self.nodes.read().unwrap();
610 (nodes.len() as u64).write(writer)?;
611 for (ref node_id, ref node_info) in nodes.iter() {
612 node_id.write(writer)?;
613 node_info.write(writer)?;
616 write_tlv_fields!(writer, {});
621 impl Readable for NetworkGraph {
622 fn read<R: io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
623 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
625 let genesis_hash: BlockHash = Readable::read(reader)?;
626 let channels_count: u64 = Readable::read(reader)?;
627 let mut channels = BTreeMap::new();
628 for _ in 0..channels_count {
629 let chan_id: u64 = Readable::read(reader)?;
630 let chan_info = Readable::read(reader)?;
631 channels.insert(chan_id, chan_info);
633 let nodes_count: u64 = Readable::read(reader)?;
634 let mut nodes = BTreeMap::new();
635 for _ in 0..nodes_count {
636 let node_id = Readable::read(reader)?;
637 let node_info = Readable::read(reader)?;
638 nodes.insert(node_id, node_info);
640 read_tlv_fields!(reader, {});
644 channels: RwLock::new(channels),
645 nodes: RwLock::new(nodes),
650 impl fmt::Display for NetworkGraph {
651 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
652 writeln!(f, "Network map\n[Channels]")?;
653 for (key, val) in self.channels.read().unwrap().iter() {
654 writeln!(f, " {}: {}", key, val)?;
656 writeln!(f, "[Nodes]")?;
657 for (key, val) in self.nodes.read().unwrap().iter() {
658 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
664 impl PartialEq for NetworkGraph {
665 fn eq(&self, other: &Self) -> bool {
666 self.genesis_hash == other.genesis_hash &&
667 *self.channels.read().unwrap() == *other.channels.read().unwrap() &&
668 *self.nodes.read().unwrap() == *other.nodes.read().unwrap()
673 /// Creates a new, empty, network graph.
674 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
677 channels: RwLock::new(BTreeMap::new()),
678 nodes: RwLock::new(BTreeMap::new()),
682 /// Returns a read-only view of the network graph.
683 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
684 let channels = self.channels.read().unwrap();
685 let nodes = self.nodes.read().unwrap();
686 ReadOnlyNetworkGraph {
692 /// For an already known node (from channel announcements), update its stored properties from a
693 /// given node announcement.
695 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
696 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
697 /// routing messages from a source using a protocol other than the lightning P2P protocol.
698 pub fn update_node_from_announcement<T: secp256k1::Verification>(&self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
699 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
700 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
701 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
704 /// For an already known node (from channel announcements), update its stored properties from a
705 /// given node announcement without verifying the associated signatures. Because we aren't
706 /// given the associated signatures here we cannot relay the node announcement to any of our
708 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
709 self.update_node_from_announcement_intern(msg, None)
712 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
713 match self.nodes.write().unwrap().get_mut(&msg.node_id) {
714 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
716 if let Some(node_info) = node.announcement_info.as_ref() {
717 if node_info.last_update >= msg.timestamp {
718 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
723 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
724 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
725 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
726 node.announcement_info = Some(NodeAnnouncementInfo {
727 features: msg.features.clone(),
728 last_update: msg.timestamp,
731 addresses: msg.addresses.clone(),
732 announcement_message: if should_relay { full_msg.cloned() } else { None },
740 /// Store or update channel info from a channel announcement.
742 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
743 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
744 /// routing messages from a source using a protocol other than the lightning P2P protocol.
746 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
747 /// the corresponding UTXO exists on chain and is correctly-formatted.
748 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>(
749 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>
750 ) -> Result<(), LightningError>
752 C::Target: chain::Access,
754 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
755 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
756 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
757 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
758 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
759 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
762 /// Store or update channel info from a channel announcement without verifying the associated
763 /// signatures. Because we aren't given the associated signatures here we cannot relay the
764 /// channel announcement to any of our peers.
766 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
767 /// the corresponding UTXO exists on chain and is correctly-formatted.
768 pub fn update_channel_from_unsigned_announcement<C: Deref>(
769 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
770 ) -> Result<(), LightningError>
772 C::Target: chain::Access,
774 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
777 fn update_channel_from_unsigned_announcement_intern<C: Deref>(
778 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
779 ) -> Result<(), LightningError>
781 C::Target: chain::Access,
783 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
784 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
787 let utxo_value = match &chain_access {
789 // Tentatively accept, potentially exposing us to DoS attacks
792 &Some(ref chain_access) => {
793 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
794 Ok(TxOut { value, script_pubkey }) => {
795 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
796 .push_slice(&msg.bitcoin_key_1.serialize())
797 .push_slice(&msg.bitcoin_key_2.serialize())
798 .push_opcode(opcodes::all::OP_PUSHNUM_2)
799 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
800 if script_pubkey != expected_script {
801 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});
803 //TODO: Check if value is worth storing, use it to inform routing, and compare it
804 //to the new HTLC max field in channel_update
807 Err(chain::AccessError::UnknownChain) => {
808 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
810 Err(chain::AccessError::UnknownTx) => {
811 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
817 let chan_info = ChannelInfo {
818 features: msg.features.clone(),
819 node_one: msg.node_id_1.clone(),
821 node_two: msg.node_id_2.clone(),
823 capacity_sats: utxo_value,
824 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
825 { full_msg.cloned() } else { None },
828 let mut channels = self.channels.write().unwrap();
829 let mut nodes = self.nodes.write().unwrap();
830 match channels.entry(msg.short_channel_id) {
831 BtreeEntry::Occupied(mut entry) => {
832 //TODO: because asking the blockchain if short_channel_id is valid is only optional
833 //in the blockchain API, we need to handle it smartly here, though it's unclear
835 if utxo_value.is_some() {
836 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
837 // only sometimes returns results. In any case remove the previous entry. Note
838 // that the spec expects us to "blacklist" the node_ids involved, but we can't
840 // a) we don't *require* a UTXO provider that always returns results.
841 // b) we don't track UTXOs of channels we know about and remove them if they
843 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
844 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), msg.short_channel_id);
845 *entry.get_mut() = chan_info;
847 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)})
850 BtreeEntry::Vacant(entry) => {
851 entry.insert(chan_info);
855 macro_rules! add_channel_to_node {
856 ( $node_id: expr ) => {
857 match nodes.entry($node_id) {
858 BtreeEntry::Occupied(node_entry) => {
859 node_entry.into_mut().channels.push(msg.short_channel_id);
861 BtreeEntry::Vacant(node_entry) => {
862 node_entry.insert(NodeInfo {
863 channels: vec!(msg.short_channel_id),
864 lowest_inbound_channel_fees: None,
865 announcement_info: None,
872 add_channel_to_node!(msg.node_id_1);
873 add_channel_to_node!(msg.node_id_2);
878 /// Close a channel if a corresponding HTLC fail was sent.
879 /// If permanent, removes a channel from the local storage.
880 /// May cause the removal of nodes too, if this was their last channel.
881 /// If not permanent, makes channels unavailable for routing.
882 pub fn close_channel_from_update(&self, short_channel_id: u64, is_permanent: bool) {
883 let mut channels = self.channels.write().unwrap();
885 if let Some(chan) = channels.remove(&short_channel_id) {
886 let mut nodes = self.nodes.write().unwrap();
887 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
890 if let Some(chan) = channels.get_mut(&short_channel_id) {
891 if let Some(one_to_two) = chan.one_to_two.as_mut() {
892 one_to_two.enabled = false;
894 if let Some(two_to_one) = chan.two_to_one.as_mut() {
895 two_to_one.enabled = false;
901 fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
903 // TODO: Wholly remove the node
905 // TODO: downgrade the node
909 /// For an already known (from announcement) channel, update info about one of the directions
912 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
913 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
914 /// routing messages from a source using a protocol other than the lightning P2P protocol.
915 pub fn update_channel<T: secp256k1::Verification>(&self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
916 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
919 /// For an already known (from announcement) channel, update info about one of the directions
920 /// of the channel without verifying the associated signatures. Because we aren't given the
921 /// associated signatures here we cannot relay the channel update to any of our peers.
922 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
923 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
926 fn update_channel_intern<T: secp256k1::Verification>(&self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate>, sig_info: Option<(&secp256k1::Signature, &Secp256k1<T>)>) -> Result<(), LightningError> {
928 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
929 let chan_was_enabled;
931 let mut channels = self.channels.write().unwrap();
932 match channels.get_mut(&msg.short_channel_id) {
933 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
935 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
936 if htlc_maximum_msat > MAX_VALUE_MSAT {
937 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
940 if let Some(capacity_sats) = channel.capacity_sats {
941 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
942 // Don't query UTXO set here to reduce DoS risks.
943 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
944 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
948 macro_rules! maybe_update_channel_info {
949 ( $target: expr, $src_node: expr) => {
950 if let Some(existing_chan_info) = $target.as_ref() {
951 if existing_chan_info.last_update >= msg.timestamp {
952 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
954 chan_was_enabled = existing_chan_info.enabled;
956 chan_was_enabled = false;
959 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
960 { full_msg.cloned() } else { None };
962 let updated_channel_dir_info = DirectionalChannelInfo {
963 enabled: chan_enabled,
964 last_update: msg.timestamp,
965 cltv_expiry_delta: msg.cltv_expiry_delta,
966 htlc_minimum_msat: msg.htlc_minimum_msat,
967 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
969 base_msat: msg.fee_base_msat,
970 proportional_millionths: msg.fee_proportional_millionths,
974 $target = Some(updated_channel_dir_info);
978 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
979 if msg.flags & 1 == 1 {
980 dest_node_id = channel.node_one.clone();
981 if let Some((sig, ctx)) = sig_info {
982 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
984 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
986 dest_node_id = channel.node_two.clone();
987 if let Some((sig, ctx)) = sig_info {
988 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
990 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
995 let mut nodes = self.nodes.write().unwrap();
997 let node = nodes.get_mut(&dest_node_id).unwrap();
998 let mut base_msat = msg.fee_base_msat;
999 let mut proportional_millionths = msg.fee_proportional_millionths;
1000 if let Some(fees) = node.lowest_inbound_channel_fees {
1001 base_msat = cmp::min(base_msat, fees.base_msat);
1002 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1004 node.lowest_inbound_channel_fees = Some(RoutingFees {
1006 proportional_millionths
1008 } else if chan_was_enabled {
1009 let node = nodes.get_mut(&dest_node_id).unwrap();
1010 let mut lowest_inbound_channel_fees = None;
1012 for chan_id in node.channels.iter() {
1013 let chan = channels.get(chan_id).unwrap();
1015 if chan.node_one == dest_node_id {
1016 chan_info_opt = chan.two_to_one.as_ref();
1018 chan_info_opt = chan.one_to_two.as_ref();
1020 if let Some(chan_info) = chan_info_opt {
1021 if chan_info.enabled {
1022 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1023 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1024 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1025 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1030 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1036 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1037 macro_rules! remove_from_node {
1038 ($node_id: expr) => {
1039 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1040 entry.get_mut().channels.retain(|chan_id| {
1041 short_channel_id != *chan_id
1043 if entry.get().channels.is_empty() {
1044 entry.remove_entry();
1047 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1052 remove_from_node!(chan.node_one);
1053 remove_from_node!(chan.node_two);
1057 impl ReadOnlyNetworkGraph<'_> {
1058 /// Returns all known valid channels' short ids along with announced channel info.
1060 /// (C-not exported) because we have no mapping for `BTreeMap`s
1061 pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1065 /// Returns all known nodes' public keys along with announced node info.
1067 /// (C-not exported) because we have no mapping for `BTreeMap`s
1068 pub fn nodes(&self) -> &BTreeMap<PublicKey, NodeInfo> {
1072 /// Get network addresses by node id.
1073 /// Returns None if the requested node is completely unknown,
1074 /// or if node announcement for the node was never received.
1076 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
1077 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<&Vec<NetAddress>> {
1078 if let Some(node) = self.nodes.get(pubkey) {
1079 if let Some(node_info) = node.announcement_info.as_ref() {
1080 return Some(&node_info.addresses)
1090 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1091 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
1092 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1093 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1094 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1095 use util::test_utils;
1096 use util::logger::Logger;
1097 use util::ser::{Readable, Writeable};
1098 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1099 use util::scid_utils::scid_from_parts;
1101 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1102 use bitcoin::hashes::Hash;
1103 use bitcoin::network::constants::Network;
1104 use bitcoin::blockdata::constants::genesis_block;
1105 use bitcoin::blockdata::script::Builder;
1106 use bitcoin::blockdata::transaction::TxOut;
1107 use bitcoin::blockdata::opcodes;
1111 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1112 use bitcoin::secp256k1::{All, Secp256k1};
1118 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1119 let secp_ctx = Secp256k1::new();
1120 let logger = Arc::new(test_utils::TestLogger::new());
1121 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1122 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1123 (secp_ctx, net_graph_msg_handler)
1127 fn request_full_sync_finite_times() {
1128 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1129 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1131 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1132 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1133 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1134 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1135 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1136 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1140 fn handling_node_announcements() {
1141 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1143 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1144 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1145 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1146 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1147 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1148 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1149 let zero_hash = Sha256dHash::hash(&[0; 32]);
1150 let first_announcement_time = 500;
1152 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1153 features: NodeFeatures::known(),
1154 timestamp: first_announcement_time,
1158 addresses: Vec::new(),
1159 excess_address_data: Vec::new(),
1160 excess_data: Vec::new(),
1162 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1163 let valid_announcement = NodeAnnouncement {
1164 signature: secp_ctx.sign(&msghash, node_1_privkey),
1165 contents: unsigned_announcement.clone()
1168 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1170 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1174 // Announce a channel to add a corresponding node.
1175 let unsigned_announcement = UnsignedChannelAnnouncement {
1176 features: ChannelFeatures::known(),
1177 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1178 short_channel_id: 0,
1181 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1182 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1183 excess_data: Vec::new(),
1186 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1187 let valid_announcement = ChannelAnnouncement {
1188 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1189 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1190 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1191 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1192 contents: unsigned_announcement.clone(),
1194 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1195 Ok(res) => assert!(res),
1200 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1201 Ok(res) => assert!(res),
1205 let fake_msghash = hash_to_message!(&zero_hash);
1206 match net_graph_msg_handler.handle_node_announcement(
1208 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1209 contents: unsigned_announcement.clone()
1212 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1215 unsigned_announcement.timestamp += 1000;
1216 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1217 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1218 let announcement_with_data = NodeAnnouncement {
1219 signature: secp_ctx.sign(&msghash, node_1_privkey),
1220 contents: unsigned_announcement.clone()
1222 // Return false because contains excess data.
1223 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1224 Ok(res) => assert!(!res),
1227 unsigned_announcement.excess_data = Vec::new();
1229 // Even though previous announcement was not relayed further, we still accepted it,
1230 // so we now won't accept announcements before the previous one.
1231 unsigned_announcement.timestamp -= 10;
1232 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1233 let outdated_announcement = NodeAnnouncement {
1234 signature: secp_ctx.sign(&msghash, node_1_privkey),
1235 contents: unsigned_announcement.clone()
1237 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1239 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1244 fn handling_channel_announcements() {
1245 let secp_ctx = Secp256k1::new();
1246 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1248 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1249 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1250 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1251 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1252 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1253 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1255 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1256 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1257 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1258 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1259 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1262 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1263 features: ChannelFeatures::known(),
1264 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1265 short_channel_id: 0,
1268 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1269 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1270 excess_data: Vec::new(),
1273 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1274 let valid_announcement = ChannelAnnouncement {
1275 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1276 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1277 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1278 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1279 contents: unsigned_announcement.clone(),
1282 // Test if the UTXO lookups were not supported
1283 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1284 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1285 Ok(res) => assert!(res),
1290 let network = &net_graph_msg_handler.network_graph;
1291 match network.read_only().channels().get(&unsigned_announcement.short_channel_id) {
1297 // If we receive announcement for the same channel (with UTXO lookups disabled),
1298 // drop new one on the floor, since we can't see any changes.
1299 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1301 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1304 // Test if an associated transaction were not on-chain (or not confirmed).
1305 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1306 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1307 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1308 unsigned_announcement.short_channel_id += 1;
1310 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1311 let valid_announcement = ChannelAnnouncement {
1312 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1313 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1314 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1315 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1316 contents: unsigned_announcement.clone(),
1319 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1321 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1324 // Now test if the transaction is found in the UTXO set and the script is correct.
1325 unsigned_announcement.short_channel_id += 1;
1326 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1328 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1329 let valid_announcement = ChannelAnnouncement {
1330 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1331 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1332 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1333 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1334 contents: unsigned_announcement.clone(),
1336 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1337 Ok(res) => assert!(res),
1342 let network = &net_graph_msg_handler.network_graph;
1343 match network.read_only().channels().get(&unsigned_announcement.short_channel_id) {
1349 // If we receive announcement for the same channel (but TX is not confirmed),
1350 // drop new one on the floor, since we can't see any changes.
1351 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1352 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1354 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1357 // But if it is confirmed, replace the channel
1358 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1359 unsigned_announcement.features = ChannelFeatures::empty();
1360 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1361 let valid_announcement = ChannelAnnouncement {
1362 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1363 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1364 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1365 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1366 contents: unsigned_announcement.clone(),
1368 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1369 Ok(res) => assert!(res),
1373 let network = &net_graph_msg_handler.network_graph;
1374 match network.read_only().channels().get(&unsigned_announcement.short_channel_id) {
1375 Some(channel_entry) => {
1376 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1382 // Don't relay valid channels with excess data
1383 unsigned_announcement.short_channel_id += 1;
1384 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1385 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1386 let valid_announcement = ChannelAnnouncement {
1387 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1388 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1389 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1390 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1391 contents: unsigned_announcement.clone(),
1393 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1394 Ok(res) => assert!(!res),
1398 unsigned_announcement.excess_data = Vec::new();
1399 let invalid_sig_announcement = ChannelAnnouncement {
1400 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1401 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1402 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1403 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1404 contents: unsigned_announcement.clone(),
1406 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1408 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1411 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1412 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1413 let channel_to_itself_announcement = ChannelAnnouncement {
1414 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1415 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1416 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1417 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1418 contents: unsigned_announcement.clone(),
1420 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1422 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1427 fn handling_channel_update() {
1428 let secp_ctx = Secp256k1::new();
1429 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1430 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1431 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1433 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1434 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1435 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1436 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1437 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1438 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1440 let zero_hash = Sha256dHash::hash(&[0; 32]);
1441 let short_channel_id = 0;
1442 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1443 let amount_sats = 1000_000;
1446 // Announce a channel we will update
1447 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1448 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1449 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1450 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1451 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1452 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1453 let unsigned_announcement = UnsignedChannelAnnouncement {
1454 features: ChannelFeatures::empty(),
1459 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1460 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1461 excess_data: Vec::new(),
1464 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1465 let valid_channel_announcement = ChannelAnnouncement {
1466 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1467 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1468 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1469 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1470 contents: unsigned_announcement.clone(),
1472 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1479 let mut unsigned_channel_update = UnsignedChannelUpdate {
1484 cltv_expiry_delta: 144,
1485 htlc_minimum_msat: 1000000,
1486 htlc_maximum_msat: OptionalField::Absent,
1487 fee_base_msat: 10000,
1488 fee_proportional_millionths: 20,
1489 excess_data: Vec::new()
1491 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1492 let valid_channel_update = ChannelUpdate {
1493 signature: secp_ctx.sign(&msghash, node_1_privkey),
1494 contents: unsigned_channel_update.clone()
1497 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1498 Ok(res) => assert!(res),
1503 let network = &net_graph_msg_handler.network_graph;
1504 match network.read_only().channels().get(&short_channel_id) {
1506 Some(channel_info) => {
1507 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1508 assert!(channel_info.two_to_one.is_none());
1513 unsigned_channel_update.timestamp += 100;
1514 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1515 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1516 let valid_channel_update = ChannelUpdate {
1517 signature: secp_ctx.sign(&msghash, node_1_privkey),
1518 contents: unsigned_channel_update.clone()
1520 // Return false because contains excess data
1521 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1522 Ok(res) => assert!(!res),
1525 unsigned_channel_update.timestamp += 10;
1527 unsigned_channel_update.short_channel_id += 1;
1528 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1529 let valid_channel_update = ChannelUpdate {
1530 signature: secp_ctx.sign(&msghash, node_1_privkey),
1531 contents: unsigned_channel_update.clone()
1534 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1536 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1538 unsigned_channel_update.short_channel_id = short_channel_id;
1540 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1541 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1542 let valid_channel_update = ChannelUpdate {
1543 signature: secp_ctx.sign(&msghash, node_1_privkey),
1544 contents: unsigned_channel_update.clone()
1547 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1549 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1551 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1553 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1554 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1555 let valid_channel_update = ChannelUpdate {
1556 signature: secp_ctx.sign(&msghash, node_1_privkey),
1557 contents: unsigned_channel_update.clone()
1560 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1562 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1564 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1566 // Even though previous update was not relayed further, we still accepted it,
1567 // so we now won't accept update before the previous one.
1568 unsigned_channel_update.timestamp -= 10;
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, "Update older than last processed update")
1579 unsigned_channel_update.timestamp += 500;
1581 let fake_msghash = hash_to_message!(&zero_hash);
1582 let invalid_sig_channel_update = ChannelUpdate {
1583 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1584 contents: unsigned_channel_update.clone()
1587 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1589 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1595 fn handling_htlc_fail_channel_update() {
1596 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1597 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1598 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1599 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1600 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1601 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1602 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1604 let short_channel_id = 0;
1605 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1608 // There is no nodes in the table at the beginning.
1609 let network = &net_graph_msg_handler.network_graph;
1610 assert_eq!(network.read_only().nodes().len(), 0);
1614 // Announce a channel we will update
1615 let unsigned_announcement = UnsignedChannelAnnouncement {
1616 features: ChannelFeatures::empty(),
1621 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1622 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1623 excess_data: Vec::new(),
1626 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1627 let valid_channel_announcement = ChannelAnnouncement {
1628 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1629 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1630 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1631 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1632 contents: unsigned_announcement.clone(),
1634 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1639 let unsigned_channel_update = UnsignedChannelUpdate {
1644 cltv_expiry_delta: 144,
1645 htlc_minimum_msat: 1000000,
1646 htlc_maximum_msat: OptionalField::Absent,
1647 fee_base_msat: 10000,
1648 fee_proportional_millionths: 20,
1649 excess_data: Vec::new()
1651 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1652 let valid_channel_update = ChannelUpdate {
1653 signature: secp_ctx.sign(&msghash, node_1_privkey),
1654 contents: unsigned_channel_update.clone()
1657 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1658 Ok(res) => assert!(res),
1663 // Non-permanent closing just disables a channel
1665 let network = &net_graph_msg_handler.network_graph;
1666 match network.read_only().channels().get(&short_channel_id) {
1668 Some(channel_info) => {
1669 assert!(channel_info.one_to_two.is_some());
1674 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1679 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1681 // Non-permanent closing just disables a channel
1683 let network = &net_graph_msg_handler.network_graph;
1684 match network.read_only().channels().get(&short_channel_id) {
1686 Some(channel_info) => {
1687 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1692 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1697 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1699 // Permanent closing deletes a channel
1701 let network = &net_graph_msg_handler.network_graph;
1702 assert_eq!(network.read_only().channels().len(), 0);
1703 // Nodes are also deleted because there are no associated channels anymore
1704 assert_eq!(network.read_only().nodes().len(), 0);
1706 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1710 fn getting_next_channel_announcements() {
1711 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1712 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1713 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1714 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1715 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1716 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1717 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1719 let short_channel_id = 1;
1720 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1722 // Channels were not announced yet.
1723 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1724 assert_eq!(channels_with_announcements.len(), 0);
1727 // Announce a channel we will update
1728 let unsigned_announcement = UnsignedChannelAnnouncement {
1729 features: ChannelFeatures::empty(),
1734 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1735 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1736 excess_data: Vec::new(),
1739 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1740 let valid_channel_announcement = ChannelAnnouncement {
1741 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1742 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1743 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1744 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1745 contents: unsigned_announcement.clone(),
1747 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1753 // Contains initial channel announcement now.
1754 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1755 assert_eq!(channels_with_announcements.len(), 1);
1756 if let Some(channel_announcements) = channels_with_announcements.first() {
1757 let &(_, ref update_1, ref update_2) = channel_announcements;
1758 assert_eq!(update_1, &None);
1759 assert_eq!(update_2, &None);
1766 // Valid channel update
1767 let unsigned_channel_update = UnsignedChannelUpdate {
1772 cltv_expiry_delta: 144,
1773 htlc_minimum_msat: 1000000,
1774 htlc_maximum_msat: OptionalField::Absent,
1775 fee_base_msat: 10000,
1776 fee_proportional_millionths: 20,
1777 excess_data: Vec::new()
1779 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1780 let valid_channel_update = ChannelUpdate {
1781 signature: secp_ctx.sign(&msghash, node_1_privkey),
1782 contents: unsigned_channel_update.clone()
1784 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1790 // Now contains an initial announcement and an update.
1791 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1792 assert_eq!(channels_with_announcements.len(), 1);
1793 if let Some(channel_announcements) = channels_with_announcements.first() {
1794 let &(_, ref update_1, ref update_2) = channel_announcements;
1795 assert_ne!(update_1, &None);
1796 assert_eq!(update_2, &None);
1803 // Channel update with excess data.
1804 let unsigned_channel_update = UnsignedChannelUpdate {
1809 cltv_expiry_delta: 144,
1810 htlc_minimum_msat: 1000000,
1811 htlc_maximum_msat: OptionalField::Absent,
1812 fee_base_msat: 10000,
1813 fee_proportional_millionths: 20,
1814 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1816 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1817 let valid_channel_update = ChannelUpdate {
1818 signature: secp_ctx.sign(&msghash, node_1_privkey),
1819 contents: unsigned_channel_update.clone()
1821 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1827 // Test that announcements with excess data won't be returned
1828 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1829 assert_eq!(channels_with_announcements.len(), 1);
1830 if let Some(channel_announcements) = channels_with_announcements.first() {
1831 let &(_, ref update_1, ref update_2) = channel_announcements;
1832 assert_eq!(update_1, &None);
1833 assert_eq!(update_2, &None);
1838 // Further starting point have no channels after it
1839 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1840 assert_eq!(channels_with_announcements.len(), 0);
1844 fn getting_next_node_announcements() {
1845 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1846 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1847 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1848 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1849 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1850 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1851 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1853 let short_channel_id = 1;
1854 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1857 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1858 assert_eq!(next_announcements.len(), 0);
1861 // Announce a channel to add 2 nodes
1862 let unsigned_announcement = UnsignedChannelAnnouncement {
1863 features: ChannelFeatures::empty(),
1868 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1869 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1870 excess_data: Vec::new(),
1873 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1874 let valid_channel_announcement = ChannelAnnouncement {
1875 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1876 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1877 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1878 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1879 contents: unsigned_announcement.clone(),
1881 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1888 // Nodes were never announced
1889 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1890 assert_eq!(next_announcements.len(), 0);
1893 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1894 features: NodeFeatures::known(),
1899 addresses: Vec::new(),
1900 excess_address_data: Vec::new(),
1901 excess_data: Vec::new(),
1903 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1904 let valid_announcement = NodeAnnouncement {
1905 signature: secp_ctx.sign(&msghash, node_1_privkey),
1906 contents: unsigned_announcement.clone()
1908 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1913 unsigned_announcement.node_id = node_id_2;
1914 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1915 let valid_announcement = NodeAnnouncement {
1916 signature: secp_ctx.sign(&msghash, node_2_privkey),
1917 contents: unsigned_announcement.clone()
1920 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1926 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1927 assert_eq!(next_announcements.len(), 2);
1929 // Skip the first node.
1930 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1931 assert_eq!(next_announcements.len(), 1);
1934 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1935 let unsigned_announcement = UnsignedNodeAnnouncement {
1936 features: NodeFeatures::known(),
1941 addresses: Vec::new(),
1942 excess_address_data: Vec::new(),
1943 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
1945 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1946 let valid_announcement = NodeAnnouncement {
1947 signature: secp_ctx.sign(&msghash, node_2_privkey),
1948 contents: unsigned_announcement.clone()
1950 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1951 Ok(res) => assert!(!res),
1956 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1957 assert_eq!(next_announcements.len(), 0);
1961 fn network_graph_serialization() {
1962 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1964 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1965 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1966 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1967 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1969 // Announce a channel to add a corresponding node.
1970 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1971 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1972 let unsigned_announcement = UnsignedChannelAnnouncement {
1973 features: ChannelFeatures::known(),
1974 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1975 short_channel_id: 0,
1978 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1979 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1980 excess_data: Vec::new(),
1983 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1984 let valid_announcement = ChannelAnnouncement {
1985 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1986 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1987 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1988 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1989 contents: unsigned_announcement.clone(),
1991 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1992 Ok(res) => assert!(res),
1997 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1998 let unsigned_announcement = UnsignedNodeAnnouncement {
1999 features: NodeFeatures::known(),
2004 addresses: Vec::new(),
2005 excess_address_data: Vec::new(),
2006 excess_data: Vec::new(),
2008 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2009 let valid_announcement = NodeAnnouncement {
2010 signature: secp_ctx.sign(&msghash, node_1_privkey),
2011 contents: unsigned_announcement.clone()
2014 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2019 let network = &net_graph_msg_handler.network_graph;
2020 let mut w = test_utils::TestVecWriter(Vec::new());
2021 assert!(!network.read_only().nodes().is_empty());
2022 assert!(!network.read_only().channels().is_empty());
2023 network.write(&mut w).unwrap();
2024 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == *network);
2028 fn calling_sync_routing_table() {
2029 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2030 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2031 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2033 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2034 let first_blocknum = 0;
2035 let number_of_blocks = 0xffff_ffff;
2037 // It should ignore if gossip_queries feature is not enabled
2039 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2040 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2041 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2042 assert_eq!(events.len(), 0);
2045 // It should send a query_channel_message with the correct information
2047 let init_msg = Init { features: InitFeatures::known() };
2048 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2049 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2050 assert_eq!(events.len(), 1);
2052 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2053 assert_eq!(node_id, &node_id_1);
2054 assert_eq!(msg.chain_hash, chain_hash);
2055 assert_eq!(msg.first_blocknum, first_blocknum);
2056 assert_eq!(msg.number_of_blocks, number_of_blocks);
2058 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2062 // It should not enqueue a query when should_request_full_sync return false.
2063 // The initial implementation allows syncing with the first 5 peers after
2064 // which should_request_full_sync will return false
2066 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2067 let init_msg = Init { features: InitFeatures::known() };
2069 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2070 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2071 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2072 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2074 assert_eq!(events.len(), 1);
2076 assert_eq!(events.len(), 0);
2084 fn handling_reply_channel_range() {
2085 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2086 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2087 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2089 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2091 // Test receipt of a single reply that should enqueue an SCID query
2092 // matching the SCIDs in the reply
2094 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2096 sync_complete: true,
2098 number_of_blocks: 2000,
2099 short_channel_ids: vec![
2100 0x0003e0_000000_0000, // 992x0x0
2101 0x0003e8_000000_0000, // 1000x0x0
2102 0x0003e9_000000_0000, // 1001x0x0
2103 0x0003f0_000000_0000, // 1008x0x0
2104 0x00044c_000000_0000, // 1100x0x0
2105 0x0006e0_000000_0000, // 1760x0x0
2108 assert!(result.is_ok());
2110 // We expect to emit a query_short_channel_ids message with the received scids
2111 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2112 assert_eq!(events.len(), 1);
2114 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2115 assert_eq!(node_id, &node_id_1);
2116 assert_eq!(msg.chain_hash, chain_hash);
2117 assert_eq!(msg.short_channel_ids, vec![
2118 0x0003e0_000000_0000, // 992x0x0
2119 0x0003e8_000000_0000, // 1000x0x0
2120 0x0003e9_000000_0000, // 1001x0x0
2121 0x0003f0_000000_0000, // 1008x0x0
2122 0x00044c_000000_0000, // 1100x0x0
2123 0x0006e0_000000_0000, // 1760x0x0
2126 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2132 fn handling_reply_short_channel_ids() {
2133 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2134 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2135 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2137 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2139 // Test receipt of a successful reply
2141 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2143 full_information: true,
2145 assert!(result.is_ok());
2148 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2149 // for the chain_hash requested in the query.
2151 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2153 full_information: false,
2155 assert!(result.is_err());
2156 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2161 fn handling_query_channel_range() {
2162 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2164 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2165 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2166 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2167 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2168 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2169 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2170 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2171 let bitcoin_key_1 = PublicKey::from_secret_key(&secp_ctx, node_1_btckey);
2172 let bitcoin_key_2 = PublicKey::from_secret_key(&secp_ctx, node_2_btckey);
2174 let mut scids: Vec<u64> = vec![
2175 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2176 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2179 // used for testing multipart reply across blocks
2180 for block in 100000..=108001 {
2181 scids.push(scid_from_parts(block, 0, 0).unwrap());
2184 // used for testing resumption on same block
2185 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2188 let unsigned_announcement = UnsignedChannelAnnouncement {
2189 features: ChannelFeatures::known(),
2190 chain_hash: chain_hash.clone(),
2191 short_channel_id: scid,
2196 excess_data: Vec::new(),
2199 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2200 let valid_announcement = ChannelAnnouncement {
2201 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2202 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2203 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2204 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2205 contents: unsigned_announcement.clone(),
2207 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2213 // Error when number_of_blocks=0
2214 do_handling_query_channel_range(
2215 &net_graph_msg_handler,
2218 chain_hash: chain_hash.clone(),
2220 number_of_blocks: 0,
2223 vec![ReplyChannelRange {
2224 chain_hash: chain_hash.clone(),
2226 number_of_blocks: 0,
2227 sync_complete: true,
2228 short_channel_ids: vec![]
2232 // Error when wrong chain
2233 do_handling_query_channel_range(
2234 &net_graph_msg_handler,
2237 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2239 number_of_blocks: 0xffff_ffff,
2242 vec![ReplyChannelRange {
2243 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2245 number_of_blocks: 0xffff_ffff,
2246 sync_complete: true,
2247 short_channel_ids: vec![],
2251 // Error when first_blocknum > 0xffffff
2252 do_handling_query_channel_range(
2253 &net_graph_msg_handler,
2256 chain_hash: chain_hash.clone(),
2257 first_blocknum: 0x01000000,
2258 number_of_blocks: 0xffff_ffff,
2261 vec![ReplyChannelRange {
2262 chain_hash: chain_hash.clone(),
2263 first_blocknum: 0x01000000,
2264 number_of_blocks: 0xffff_ffff,
2265 sync_complete: true,
2266 short_channel_ids: vec![]
2270 // Empty reply when max valid SCID block num
2271 do_handling_query_channel_range(
2272 &net_graph_msg_handler,
2275 chain_hash: chain_hash.clone(),
2276 first_blocknum: 0xffffff,
2277 number_of_blocks: 1,
2282 chain_hash: chain_hash.clone(),
2283 first_blocknum: 0xffffff,
2284 number_of_blocks: 1,
2285 sync_complete: true,
2286 short_channel_ids: vec![]
2291 // No results in valid query range
2292 do_handling_query_channel_range(
2293 &net_graph_msg_handler,
2296 chain_hash: chain_hash.clone(),
2297 first_blocknum: 1000,
2298 number_of_blocks: 1000,
2303 chain_hash: chain_hash.clone(),
2304 first_blocknum: 1000,
2305 number_of_blocks: 1000,
2306 sync_complete: true,
2307 short_channel_ids: vec![],
2312 // Overflow first_blocknum + number_of_blocks
2313 do_handling_query_channel_range(
2314 &net_graph_msg_handler,
2317 chain_hash: chain_hash.clone(),
2318 first_blocknum: 0xfe0000,
2319 number_of_blocks: 0xffffffff,
2324 chain_hash: chain_hash.clone(),
2325 first_blocknum: 0xfe0000,
2326 number_of_blocks: 0xffffffff - 0xfe0000,
2327 sync_complete: true,
2328 short_channel_ids: vec![
2329 0xfffffe_ffffff_ffff, // max
2335 // Single block exactly full
2336 do_handling_query_channel_range(
2337 &net_graph_msg_handler,
2340 chain_hash: chain_hash.clone(),
2341 first_blocknum: 100000,
2342 number_of_blocks: 8000,
2347 chain_hash: chain_hash.clone(),
2348 first_blocknum: 100000,
2349 number_of_blocks: 8000,
2350 sync_complete: true,
2351 short_channel_ids: (100000..=107999)
2352 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2358 // Multiple split on new block
2359 do_handling_query_channel_range(
2360 &net_graph_msg_handler,
2363 chain_hash: chain_hash.clone(),
2364 first_blocknum: 100000,
2365 number_of_blocks: 8001,
2370 chain_hash: chain_hash.clone(),
2371 first_blocknum: 100000,
2372 number_of_blocks: 7999,
2373 sync_complete: false,
2374 short_channel_ids: (100000..=107999)
2375 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2379 chain_hash: chain_hash.clone(),
2380 first_blocknum: 107999,
2381 number_of_blocks: 2,
2382 sync_complete: true,
2383 short_channel_ids: vec![
2384 scid_from_parts(108000, 0, 0).unwrap(),
2390 // Multiple split on same block
2391 do_handling_query_channel_range(
2392 &net_graph_msg_handler,
2395 chain_hash: chain_hash.clone(),
2396 first_blocknum: 100002,
2397 number_of_blocks: 8000,
2402 chain_hash: chain_hash.clone(),
2403 first_blocknum: 100002,
2404 number_of_blocks: 7999,
2405 sync_complete: false,
2406 short_channel_ids: (100002..=108001)
2407 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2411 chain_hash: chain_hash.clone(),
2412 first_blocknum: 108001,
2413 number_of_blocks: 1,
2414 sync_complete: true,
2415 short_channel_ids: vec![
2416 scid_from_parts(108001, 1, 0).unwrap(),
2423 fn do_handling_query_channel_range(
2424 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2425 test_node_id: &PublicKey,
2426 msg: QueryChannelRange,
2428 expected_replies: Vec<ReplyChannelRange>
2430 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2431 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2432 let query_end_blocknum = msg.end_blocknum();
2433 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2436 assert!(result.is_ok());
2438 assert!(result.is_err());
2441 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2442 assert_eq!(events.len(), expected_replies.len());
2444 for i in 0..events.len() {
2445 let expected_reply = &expected_replies[i];
2447 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2448 assert_eq!(node_id, test_node_id);
2449 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2450 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2451 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2452 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2453 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2455 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2456 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2457 assert!(msg.first_blocknum >= max_firstblocknum);
2458 max_firstblocknum = msg.first_blocknum;
2459 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2461 // Check that the last block count is >= the query's end_blocknum
2462 if i == events.len() - 1 {
2463 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2466 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2472 fn handling_query_short_channel_ids() {
2473 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2474 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2475 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2477 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2479 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2481 short_channel_ids: vec![0x0003e8_000000_0000],
2483 assert!(result.is_err());
2487 #[cfg(all(test, feature = "unstable"))]
2495 fn read_network_graph(bench: &mut Bencher) {
2496 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2497 let mut v = Vec::new();
2498 d.read_to_end(&mut v).unwrap();
2500 let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2505 fn write_network_graph(bench: &mut Bencher) {
2506 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2507 let net_graph = NetworkGraph::read(&mut d).unwrap();
2509 let _ = net_graph.encode();