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 /// Receives and validates network updates from peers,
62 /// stores authentic and relevant data as a network graph.
63 /// This network graph is then used for routing payments.
64 /// Provides interface to help with initial routing sync by
65 /// serving historical announcements.
66 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
67 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
68 /// Representation of the payment channel network
69 pub network_graph: NetworkGraph,
70 chain_access: Option<C>,
71 full_syncs_requested: AtomicUsize,
72 pending_events: Mutex<Vec<MessageSendEvent>>,
76 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
77 /// Creates a new tracker of the actual state of the network of channels and nodes,
78 /// assuming a fresh network graph.
79 /// Chain monitor is used to make sure announced channels exist on-chain,
80 /// channel data is correct, and that the announcement is signed with
81 /// channel owners' keys.
82 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
84 secp_ctx: Secp256k1::verification_only(),
85 network_graph: NetworkGraph::new(genesis_hash),
86 full_syncs_requested: AtomicUsize::new(0),
88 pending_events: Mutex::new(vec![]),
93 /// Creates a new tracker of the actual state of the network of channels and nodes,
94 /// assuming an existing Network Graph.
95 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
97 secp_ctx: Secp256k1::verification_only(),
99 full_syncs_requested: AtomicUsize::new(0),
101 pending_events: Mutex::new(vec![]),
106 /// Adds a provider used to check new announcements. Does not affect
107 /// existing announcements unless they are updated.
108 /// Add, update or remove the provider would replace the current one.
109 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
110 self.chain_access = chain_access;
113 /// Returns true when a full routing table sync should be performed with a peer.
114 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
115 //TODO: Determine whether to request a full sync based on the network map.
116 const FULL_SYNCS_TO_REQUEST: usize = 5;
117 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
118 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
126 macro_rules! secp_verify_sig {
127 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
128 match $secp_ctx.verify($msg, $sig, $pubkey) {
130 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
135 impl<C: Deref , L: Deref > RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
136 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
137 self.network_graph.update_node_from_announcement(msg, &self.secp_ctx)?;
138 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
139 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
140 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
143 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
144 self.network_graph.update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
145 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 { "" });
146 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
149 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
151 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
152 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
153 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" });
154 let _ = self.network_graph.update_channel(msg, &self.secp_ctx);
156 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
157 log_debug!(self.logger, "{} channel graph entry for {} due to a payment failure.", if is_permanent { "Removing" } else { "Disabling" }, short_channel_id);
158 self.network_graph.close_channel_from_update(short_channel_id, is_permanent);
160 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
161 log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", if is_permanent { "Removing" } else { "Disabling" }, node_id);
162 self.network_graph.fail_node(node_id, is_permanent);
167 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
168 self.network_graph.update_channel(msg, &self.secp_ctx)?;
169 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
172 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
173 let mut result = Vec::with_capacity(batch_amount as usize);
174 let channels = self.network_graph.get_channels();
175 let mut iter = channels.range(starting_point..);
176 while result.len() < batch_amount as usize {
177 if let Some((_, ref chan)) = iter.next() {
178 if chan.announcement_message.is_some() {
179 let chan_announcement = chan.announcement_message.clone().unwrap();
180 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
181 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
182 if let Some(one_to_two) = chan.one_to_two.as_ref() {
183 one_to_two_announcement = one_to_two.last_update_message.clone();
185 if let Some(two_to_one) = chan.two_to_one.as_ref() {
186 two_to_one_announcement = two_to_one.last_update_message.clone();
188 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
190 // TODO: We may end up sending un-announced channel_updates if we are sending
191 // initial sync data while receiving announce/updates for this channel.
200 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
201 let mut result = Vec::with_capacity(batch_amount as usize);
202 let nodes = self.network_graph.get_nodes();
203 let mut iter = if let Some(pubkey) = starting_point {
204 let mut iter = nodes.range((*pubkey)..);
210 while result.len() < batch_amount as usize {
211 if let Some((_, ref node)) = iter.next() {
212 if let Some(node_info) = node.announcement_info.as_ref() {
213 if node_info.announcement_message.is_some() {
214 result.push(node_info.announcement_message.clone().unwrap());
224 /// Initiates a stateless sync of routing gossip information with a peer
225 /// using gossip_queries. The default strategy used by this implementation
226 /// is to sync the full block range with several peers.
228 /// We should expect one or more reply_channel_range messages in response
229 /// to our query_channel_range. Each reply will enqueue a query_scid message
230 /// to request gossip messages for each channel. The sync is considered complete
231 /// when the final reply_scids_end message is received, though we are not
232 /// tracking this directly.
233 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
235 // We will only perform a sync with peers that support gossip_queries.
236 if !init_msg.features.supports_gossip_queries() {
240 // Check if we need to perform a full synchronization with this peer
241 if !self.should_request_full_sync(their_node_id) {
245 let first_blocknum = 0;
246 let number_of_blocks = 0xffffffff;
247 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
248 let mut pending_events = self.pending_events.lock().unwrap();
249 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
250 node_id: their_node_id.clone(),
251 msg: QueryChannelRange {
252 chain_hash: self.network_graph.genesis_hash,
259 /// Statelessly processes a reply to a channel range query by immediately
260 /// sending an SCID query with SCIDs in the reply. To keep this handler
261 /// stateless, it does not validate the sequencing of replies for multi-
262 /// reply ranges. It does not validate whether the reply(ies) cover the
263 /// queried range. It also does not filter SCIDs to only those in the
264 /// original query range. We also do not validate that the chain_hash
265 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
266 /// does not match our chain_hash will be rejected when the announcement is
268 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
269 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(),);
271 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
272 let mut pending_events = self.pending_events.lock().unwrap();
273 pending_events.push(MessageSendEvent::SendShortIdsQuery {
274 node_id: their_node_id.clone(),
275 msg: QueryShortChannelIds {
276 chain_hash: msg.chain_hash,
277 short_channel_ids: msg.short_channel_ids,
284 /// When an SCID query is initiated the remote peer will begin streaming
285 /// gossip messages. In the event of a failure, we may have received
286 /// some channel information. Before trying with another peer, the
287 /// caller should update its set of SCIDs that need to be queried.
288 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
289 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
291 // If the remote node does not have up-to-date information for the
292 // chain_hash they will set full_information=false. We can fail
293 // the result and try again with a different peer.
294 if !msg.full_information {
295 return Err(LightningError {
296 err: String::from("Received reply_short_channel_ids_end with no information"),
297 action: ErrorAction::IgnoreError
304 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
305 /// are in the specified block range. Due to message size limits, large range
306 /// queries may result in several reply messages. This implementation enqueues
307 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
308 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
309 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
310 /// memory constrained systems.
311 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
312 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);
314 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
316 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
317 // If so, we manually cap the ending block to avoid this overflow.
318 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
320 // Per spec, we must reply to a query. Send an empty message when things are invalid.
321 if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
322 let mut pending_events = self.pending_events.lock().unwrap();
323 pending_events.push(MessageSendEvent::SendReplyChannelRange {
324 node_id: their_node_id.clone(),
325 msg: ReplyChannelRange {
326 chain_hash: msg.chain_hash.clone(),
327 first_blocknum: msg.first_blocknum,
328 number_of_blocks: msg.number_of_blocks,
330 short_channel_ids: vec![],
333 return Err(LightningError {
334 err: String::from("query_channel_range could not be processed"),
335 action: ErrorAction::IgnoreError,
339 // Creates channel batches. We are not checking if the channel is routable
340 // (has at least one update). A peer may still want to know the channel
341 // exists even if its not yet routable.
342 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
343 for (_, ref chan) in self.network_graph.get_channels().range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
344 if let Some(chan_announcement) = &chan.announcement_message {
345 // Construct a new batch if last one is full
346 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
347 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
350 let batch = batches.last_mut().unwrap();
351 batch.push(chan_announcement.contents.short_channel_id);
355 let mut pending_events = self.pending_events.lock().unwrap();
356 let batch_count = batches.len();
357 let mut prev_batch_endblock = msg.first_blocknum;
358 for (batch_index, batch) in batches.into_iter().enumerate() {
359 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
360 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
362 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
363 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
364 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
365 // significant diversion from the requirements set by the spec, and, in case of blocks
366 // with no channel opens (e.g. empty blocks), requires that we use the previous value
367 // and *not* derive the first_blocknum from the actual first block of the reply.
368 let first_blocknum = prev_batch_endblock;
370 // Each message carries the number of blocks (from the `first_blocknum`) its contents
371 // fit in. Though there is no requirement that we use exactly the number of blocks its
372 // contents are from, except for the bogus requirements c-lightning enforces, above.
374 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
375 // >= the query's end block. Thus, for the last reply, we calculate the difference
376 // between the query's end block and the start of the reply.
378 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
379 // first_blocknum will be either msg.first_blocknum or a higher block height.
380 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
381 (true, msg.end_blocknum() - first_blocknum)
383 // Prior replies should use the number of blocks that fit into the reply. Overflow
384 // safe since first_blocknum is always <= last SCID's block.
386 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
389 prev_batch_endblock = first_blocknum + number_of_blocks;
391 pending_events.push(MessageSendEvent::SendReplyChannelRange {
392 node_id: their_node_id.clone(),
393 msg: ReplyChannelRange {
394 chain_hash: msg.chain_hash.clone(),
398 short_channel_ids: batch,
406 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
409 err: String::from("Not implemented"),
410 action: ErrorAction::IgnoreError,
415 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
417 C::Target: chain::Access,
420 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
421 let mut ret = Vec::new();
422 let mut pending_events = self.pending_events.lock().unwrap();
423 core::mem::swap(&mut ret, &mut pending_events);
428 #[derive(Clone, Debug, PartialEq)]
429 /// Details about one direction of a channel. Received
430 /// within a channel update.
431 pub struct DirectionalChannelInfo {
432 /// When the last update to the channel direction was issued.
433 /// Value is opaque, as set in the announcement.
434 pub last_update: u32,
435 /// Whether the channel can be currently used for payments (in this one direction).
437 /// The difference in CLTV values that you must have when routing through this channel.
438 pub cltv_expiry_delta: u16,
439 /// The minimum value, which must be relayed to the next hop via the channel
440 pub htlc_minimum_msat: u64,
441 /// The maximum value which may be relayed to the next hop via the channel.
442 pub htlc_maximum_msat: Option<u64>,
443 /// Fees charged when the channel is used for routing
444 pub fees: RoutingFees,
445 /// Most recent update for the channel received from the network
446 /// Mostly redundant with the data we store in fields explicitly.
447 /// Everything else is useful only for sending out for initial routing sync.
448 /// Not stored if contains excess data to prevent DoS.
449 pub last_update_message: Option<ChannelUpdate>,
452 impl fmt::Display for DirectionalChannelInfo {
453 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
454 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)?;
459 impl_writeable_tlv_based!(DirectionalChannelInfo, {
460 (0, last_update, required),
461 (2, enabled, required),
462 (4, cltv_expiry_delta, required),
463 (6, htlc_minimum_msat, required),
464 (8, htlc_maximum_msat, required),
465 (10, fees, required),
466 (12, last_update_message, required),
469 #[derive(Clone, Debug, PartialEq)]
470 /// Details about a channel (both directions).
471 /// Received within a channel announcement.
472 pub struct ChannelInfo {
473 /// Protocol features of a channel communicated during its announcement
474 pub features: ChannelFeatures,
475 /// Source node of the first direction of a channel
476 pub node_one: PublicKey,
477 /// Details about the first direction of a channel
478 pub one_to_two: Option<DirectionalChannelInfo>,
479 /// Source node of the second direction of a channel
480 pub node_two: PublicKey,
481 /// Details about the second direction of a channel
482 pub two_to_one: Option<DirectionalChannelInfo>,
483 /// The channel capacity as seen on-chain, if chain lookup is available.
484 pub capacity_sats: Option<u64>,
485 /// An initial announcement of the channel
486 /// Mostly redundant with the data we store in fields explicitly.
487 /// Everything else is useful only for sending out for initial routing sync.
488 /// Not stored if contains excess data to prevent DoS.
489 pub announcement_message: Option<ChannelAnnouncement>,
492 impl fmt::Display for ChannelInfo {
493 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
494 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
495 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
500 impl_writeable_tlv_based!(ChannelInfo, {
501 (0, features, required),
502 (2, node_one, required),
503 (4, one_to_two, required),
504 (6, node_two, required),
505 (8, two_to_one, required),
506 (10, capacity_sats, required),
507 (12, announcement_message, required),
511 /// Fees for routing via a given channel or a node
512 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
513 pub struct RoutingFees {
514 /// Flat routing fee in satoshis
516 /// Liquidity-based routing fee in millionths of a routed amount.
517 /// In other words, 10000 is 1%.
518 pub proportional_millionths: u32,
521 impl_writeable_tlv_based!(RoutingFees, {
522 (0, base_msat, required),
523 (2, proportional_millionths, required)
526 #[derive(Clone, Debug, PartialEq)]
527 /// Information received in the latest node_announcement from this node.
528 pub struct NodeAnnouncementInfo {
529 /// Protocol features the node announced support for
530 pub features: NodeFeatures,
531 /// When the last known update to the node state was issued.
532 /// Value is opaque, as set in the announcement.
533 pub last_update: u32,
534 /// Color assigned to the node
536 /// Moniker assigned to the node.
537 /// May be invalid or malicious (eg control chars),
538 /// should not be exposed to the user.
540 /// Internet-level addresses via which one can connect to the node
541 pub addresses: Vec<NetAddress>,
542 /// An initial announcement of the node
543 /// Mostly redundant with the data we store in fields explicitly.
544 /// Everything else is useful only for sending out for initial routing sync.
545 /// Not stored if contains excess data to prevent DoS.
546 pub announcement_message: Option<NodeAnnouncement>
549 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
550 (0, features, required),
551 (2, last_update, required),
553 (6, alias, required),
554 (8, announcement_message, option),
555 (10, addresses, vec_type),
558 #[derive(Clone, Debug, PartialEq)]
559 /// Details about a node in the network, known from the network announcement.
560 pub struct NodeInfo {
561 /// All valid channels a node has announced
562 pub channels: Vec<u64>,
563 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
564 /// The two fields (flat and proportional fee) are independent,
565 /// meaning they don't have to refer to the same channel.
566 pub lowest_inbound_channel_fees: Option<RoutingFees>,
567 /// More information about a node from node_announcement.
568 /// Optional because we store a Node entry after learning about it from
569 /// a channel announcement, but before receiving a node announcement.
570 pub announcement_info: Option<NodeAnnouncementInfo>
573 impl fmt::Display for NodeInfo {
574 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
575 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
576 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
581 impl_writeable_tlv_based!(NodeInfo, {
582 (0, lowest_inbound_channel_fees, option),
583 (2, announcement_info, option),
584 (4, channels, vec_type),
587 const SERIALIZATION_VERSION: u8 = 1;
588 const MIN_SERIALIZATION_VERSION: u8 = 1;
590 impl Writeable for NetworkGraph {
591 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
592 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
594 self.genesis_hash.write(writer)?;
595 let channels = self.channels.read().unwrap();
596 (channels.len() as u64).write(writer)?;
597 for (ref chan_id, ref chan_info) in channels.iter() {
598 (*chan_id).write(writer)?;
599 chan_info.write(writer)?;
601 let nodes = self.nodes.read().unwrap();
602 (nodes.len() as u64).write(writer)?;
603 for (ref node_id, ref node_info) in nodes.iter() {
604 node_id.write(writer)?;
605 node_info.write(writer)?;
608 write_tlv_fields!(writer, {});
613 impl Readable for NetworkGraph {
614 fn read<R: io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
615 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
617 let genesis_hash: BlockHash = Readable::read(reader)?;
618 let channels_count: u64 = Readable::read(reader)?;
619 let mut channels = BTreeMap::new();
620 for _ in 0..channels_count {
621 let chan_id: u64 = Readable::read(reader)?;
622 let chan_info = Readable::read(reader)?;
623 channels.insert(chan_id, chan_info);
625 let nodes_count: u64 = Readable::read(reader)?;
626 let mut nodes = BTreeMap::new();
627 for _ in 0..nodes_count {
628 let node_id = Readable::read(reader)?;
629 let node_info = Readable::read(reader)?;
630 nodes.insert(node_id, node_info);
632 read_tlv_fields!(reader, {});
636 channels: RwLock::new(channels),
637 nodes: RwLock::new(nodes),
642 impl fmt::Display for NetworkGraph {
643 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
644 writeln!(f, "Network map\n[Channels]")?;
645 for (key, val) in self.channels.read().unwrap().iter() {
646 writeln!(f, " {}: {}", key, val)?;
648 writeln!(f, "[Nodes]")?;
649 for (key, val) in self.nodes.read().unwrap().iter() {
650 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
656 impl PartialEq for NetworkGraph {
657 fn eq(&self, other: &Self) -> bool {
658 self.genesis_hash == other.genesis_hash &&
659 *self.channels.read().unwrap() == *other.channels.read().unwrap() &&
660 *self.nodes.read().unwrap() == *other.nodes.read().unwrap()
665 /// Returns all known valid channels' short ids along with announced channel info.
667 /// (C-not exported) because we have no mapping for `BTreeMap`s
668 pub fn get_channels(&self) -> RwLockReadGuard<'_, BTreeMap<u64, ChannelInfo>> {
669 self.channels.read().unwrap()
672 /// Returns all known nodes' public keys along with announced node info.
674 /// (C-not exported) because we have no mapping for `BTreeMap`s
675 pub fn get_nodes(&self) -> RwLockReadGuard<'_, BTreeMap<PublicKey, NodeInfo>> {
676 self.nodes.read().unwrap()
679 /// Get network addresses by node id.
680 /// Returns None if the requested node is completely unknown,
681 /// or if node announcement for the node was never received.
683 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
684 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
685 if let Some(node) = self.nodes.read().unwrap().get(pubkey) {
686 if let Some(node_info) = node.announcement_info.as_ref() {
687 return Some(node_info.addresses.clone())
693 /// Creates a new, empty, network graph.
694 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
697 channels: RwLock::new(BTreeMap::new()),
698 nodes: RwLock::new(BTreeMap::new()),
702 /// For an already known node (from channel announcements), update its stored properties from a
703 /// given node announcement.
705 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
706 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
707 /// routing messages from a source using a protocol other than the lightning P2P protocol.
708 pub fn update_node_from_announcement<T: secp256k1::Verification>(&self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
709 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
710 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
711 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
714 /// For an already known node (from channel announcements), update its stored properties from a
715 /// given node announcement without verifying the associated signatures. Because we aren't
716 /// given the associated signatures here we cannot relay the node announcement to any of our
718 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
719 self.update_node_from_announcement_intern(msg, None)
722 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
723 match self.nodes.write().unwrap().get_mut(&msg.node_id) {
724 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
726 if let Some(node_info) = node.announcement_info.as_ref() {
727 if node_info.last_update >= msg.timestamp {
728 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
733 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
734 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
735 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
736 node.announcement_info = Some(NodeAnnouncementInfo {
737 features: msg.features.clone(),
738 last_update: msg.timestamp,
741 addresses: msg.addresses.clone(),
742 announcement_message: if should_relay { full_msg.cloned() } else { None },
750 /// Store or update channel info from a channel announcement.
752 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
753 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
754 /// routing messages from a source using a protocol other than the lightning P2P protocol.
756 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
757 /// the corresponding UTXO exists on chain and is correctly-formatted.
758 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>(
759 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>
760 ) -> Result<(), LightningError>
762 C::Target: chain::Access,
764 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
765 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
766 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
767 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
768 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
769 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
772 /// Store or update channel info from a channel announcement without verifying the associated
773 /// signatures. Because we aren't given the associated signatures here we cannot relay the
774 /// channel announcement to any of our peers.
776 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
777 /// the corresponding UTXO exists on chain and is correctly-formatted.
778 pub fn update_channel_from_unsigned_announcement<C: Deref>(
779 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
780 ) -> Result<(), LightningError>
782 C::Target: chain::Access,
784 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
787 fn update_channel_from_unsigned_announcement_intern<C: Deref>(
788 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
789 ) -> Result<(), LightningError>
791 C::Target: chain::Access,
793 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
794 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
797 let utxo_value = match &chain_access {
799 // Tentatively accept, potentially exposing us to DoS attacks
802 &Some(ref chain_access) => {
803 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
804 Ok(TxOut { value, script_pubkey }) => {
805 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
806 .push_slice(&msg.bitcoin_key_1.serialize())
807 .push_slice(&msg.bitcoin_key_2.serialize())
808 .push_opcode(opcodes::all::OP_PUSHNUM_2)
809 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
810 if script_pubkey != expected_script {
811 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});
813 //TODO: Check if value is worth storing, use it to inform routing, and compare it
814 //to the new HTLC max field in channel_update
817 Err(chain::AccessError::UnknownChain) => {
818 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
820 Err(chain::AccessError::UnknownTx) => {
821 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
827 let chan_info = ChannelInfo {
828 features: msg.features.clone(),
829 node_one: msg.node_id_1.clone(),
831 node_two: msg.node_id_2.clone(),
833 capacity_sats: utxo_value,
834 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
835 { full_msg.cloned() } else { None },
838 let mut channels = self.channels.write().unwrap();
839 let mut nodes = self.nodes.write().unwrap();
840 match channels.entry(msg.short_channel_id) {
841 BtreeEntry::Occupied(mut entry) => {
842 //TODO: because asking the blockchain if short_channel_id is valid is only optional
843 //in the blockchain API, we need to handle it smartly here, though it's unclear
845 if utxo_value.is_some() {
846 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
847 // only sometimes returns results. In any case remove the previous entry. Note
848 // that the spec expects us to "blacklist" the node_ids involved, but we can't
850 // a) we don't *require* a UTXO provider that always returns results.
851 // b) we don't track UTXOs of channels we know about and remove them if they
853 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
854 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), msg.short_channel_id);
855 *entry.get_mut() = chan_info;
857 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)})
860 BtreeEntry::Vacant(entry) => {
861 entry.insert(chan_info);
865 macro_rules! add_channel_to_node {
866 ( $node_id: expr ) => {
867 match nodes.entry($node_id) {
868 BtreeEntry::Occupied(node_entry) => {
869 node_entry.into_mut().channels.push(msg.short_channel_id);
871 BtreeEntry::Vacant(node_entry) => {
872 node_entry.insert(NodeInfo {
873 channels: vec!(msg.short_channel_id),
874 lowest_inbound_channel_fees: None,
875 announcement_info: None,
882 add_channel_to_node!(msg.node_id_1);
883 add_channel_to_node!(msg.node_id_2);
888 /// Close a channel if a corresponding HTLC fail was sent.
889 /// If permanent, removes a channel from the local storage.
890 /// May cause the removal of nodes too, if this was their last channel.
891 /// If not permanent, makes channels unavailable for routing.
892 pub fn close_channel_from_update(&self, short_channel_id: u64, is_permanent: bool) {
893 let mut channels = self.channels.write().unwrap();
895 if let Some(chan) = channels.remove(&short_channel_id) {
896 let mut nodes = self.nodes.write().unwrap();
897 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
900 if let Some(chan) = channels.get_mut(&short_channel_id) {
901 if let Some(one_to_two) = chan.one_to_two.as_mut() {
902 one_to_two.enabled = false;
904 if let Some(two_to_one) = chan.two_to_one.as_mut() {
905 two_to_one.enabled = false;
911 fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
913 // TODO: Wholly remove the node
915 // TODO: downgrade the node
919 /// For an already known (from announcement) channel, update info about one of the directions
922 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
923 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
924 /// routing messages from a source using a protocol other than the lightning P2P protocol.
925 pub fn update_channel<T: secp256k1::Verification>(&self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
926 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
929 /// For an already known (from announcement) channel, update info about one of the directions
930 /// of the channel without verifying the associated signatures. Because we aren't given the
931 /// associated signatures here we cannot relay the channel update to any of our peers.
932 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
933 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
936 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> {
938 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
939 let chan_was_enabled;
941 let mut channels = self.channels.write().unwrap();
942 match channels.get_mut(&msg.short_channel_id) {
943 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
945 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
946 if htlc_maximum_msat > MAX_VALUE_MSAT {
947 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
950 if let Some(capacity_sats) = channel.capacity_sats {
951 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
952 // Don't query UTXO set here to reduce DoS risks.
953 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
954 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
958 macro_rules! maybe_update_channel_info {
959 ( $target: expr, $src_node: expr) => {
960 if let Some(existing_chan_info) = $target.as_ref() {
961 if existing_chan_info.last_update >= msg.timestamp {
962 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
964 chan_was_enabled = existing_chan_info.enabled;
966 chan_was_enabled = false;
969 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
970 { full_msg.cloned() } else { None };
972 let updated_channel_dir_info = DirectionalChannelInfo {
973 enabled: chan_enabled,
974 last_update: msg.timestamp,
975 cltv_expiry_delta: msg.cltv_expiry_delta,
976 htlc_minimum_msat: msg.htlc_minimum_msat,
977 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
979 base_msat: msg.fee_base_msat,
980 proportional_millionths: msg.fee_proportional_millionths,
984 $target = Some(updated_channel_dir_info);
988 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
989 if msg.flags & 1 == 1 {
990 dest_node_id = channel.node_one.clone();
991 if let Some((sig, ctx)) = sig_info {
992 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
994 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
996 dest_node_id = channel.node_two.clone();
997 if let Some((sig, ctx)) = sig_info {
998 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1000 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1005 let mut nodes = self.nodes.write().unwrap();
1007 let node = nodes.get_mut(&dest_node_id).unwrap();
1008 let mut base_msat = msg.fee_base_msat;
1009 let mut proportional_millionths = msg.fee_proportional_millionths;
1010 if let Some(fees) = node.lowest_inbound_channel_fees {
1011 base_msat = cmp::min(base_msat, fees.base_msat);
1012 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1014 node.lowest_inbound_channel_fees = Some(RoutingFees {
1016 proportional_millionths
1018 } else if chan_was_enabled {
1019 let node = nodes.get_mut(&dest_node_id).unwrap();
1020 let mut lowest_inbound_channel_fees = None;
1022 for chan_id in node.channels.iter() {
1023 let chan = channels.get(chan_id).unwrap();
1025 if chan.node_one == dest_node_id {
1026 chan_info_opt = chan.two_to_one.as_ref();
1028 chan_info_opt = chan.one_to_two.as_ref();
1030 if let Some(chan_info) = chan_info_opt {
1031 if chan_info.enabled {
1032 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1033 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1034 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1035 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1040 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1046 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1047 macro_rules! remove_from_node {
1048 ($node_id: expr) => {
1049 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1050 entry.get_mut().channels.retain(|chan_id| {
1051 short_channel_id != *chan_id
1053 if entry.get().channels.is_empty() {
1054 entry.remove_entry();
1057 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1062 remove_from_node!(chan.node_one);
1063 remove_from_node!(chan.node_two);
1070 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1071 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
1072 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1073 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1074 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1075 use util::test_utils;
1076 use util::logger::Logger;
1077 use util::ser::{Readable, Writeable};
1078 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1079 use util::scid_utils::scid_from_parts;
1081 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1082 use bitcoin::hashes::Hash;
1083 use bitcoin::network::constants::Network;
1084 use bitcoin::blockdata::constants::genesis_block;
1085 use bitcoin::blockdata::script::Builder;
1086 use bitcoin::blockdata::transaction::TxOut;
1087 use bitcoin::blockdata::opcodes;
1091 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1092 use bitcoin::secp256k1::{All, Secp256k1};
1098 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1099 let secp_ctx = Secp256k1::new();
1100 let logger = Arc::new(test_utils::TestLogger::new());
1101 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1102 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1103 (secp_ctx, net_graph_msg_handler)
1107 fn request_full_sync_finite_times() {
1108 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1109 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1111 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1112 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1113 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1114 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1115 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1116 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1120 fn handling_node_announcements() {
1121 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1123 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1124 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1125 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1126 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1127 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1128 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1129 let zero_hash = Sha256dHash::hash(&[0; 32]);
1130 let first_announcement_time = 500;
1132 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1133 features: NodeFeatures::known(),
1134 timestamp: first_announcement_time,
1138 addresses: Vec::new(),
1139 excess_address_data: Vec::new(),
1140 excess_data: Vec::new(),
1142 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1143 let valid_announcement = NodeAnnouncement {
1144 signature: secp_ctx.sign(&msghash, node_1_privkey),
1145 contents: unsigned_announcement.clone()
1148 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1150 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1154 // Announce a channel to add a corresponding node.
1155 let unsigned_announcement = UnsignedChannelAnnouncement {
1156 features: ChannelFeatures::known(),
1157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1158 short_channel_id: 0,
1161 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1162 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1163 excess_data: Vec::new(),
1166 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1167 let valid_announcement = ChannelAnnouncement {
1168 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1169 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1170 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1171 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1172 contents: unsigned_announcement.clone(),
1174 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1175 Ok(res) => assert!(res),
1180 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1181 Ok(res) => assert!(res),
1185 let fake_msghash = hash_to_message!(&zero_hash);
1186 match net_graph_msg_handler.handle_node_announcement(
1188 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1189 contents: unsigned_announcement.clone()
1192 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1195 unsigned_announcement.timestamp += 1000;
1196 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1197 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1198 let announcement_with_data = NodeAnnouncement {
1199 signature: secp_ctx.sign(&msghash, node_1_privkey),
1200 contents: unsigned_announcement.clone()
1202 // Return false because contains excess data.
1203 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1204 Ok(res) => assert!(!res),
1207 unsigned_announcement.excess_data = Vec::new();
1209 // Even though previous announcement was not relayed further, we still accepted it,
1210 // so we now won't accept announcements before the previous one.
1211 unsigned_announcement.timestamp -= 10;
1212 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1213 let outdated_announcement = NodeAnnouncement {
1214 signature: secp_ctx.sign(&msghash, node_1_privkey),
1215 contents: unsigned_announcement.clone()
1217 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1219 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1224 fn handling_channel_announcements() {
1225 let secp_ctx = Secp256k1::new();
1226 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1228 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1229 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1230 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1231 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1232 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1233 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1235 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1236 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1237 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1238 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1239 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1242 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1243 features: ChannelFeatures::known(),
1244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1245 short_channel_id: 0,
1248 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1249 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1250 excess_data: Vec::new(),
1253 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1254 let valid_announcement = ChannelAnnouncement {
1255 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1256 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1257 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1258 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1259 contents: unsigned_announcement.clone(),
1262 // Test if the UTXO lookups were not supported
1263 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1264 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1265 Ok(res) => assert!(res),
1270 let network = &net_graph_msg_handler.network_graph;
1271 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1277 // If we receive announcement for the same channel (with UTXO lookups disabled),
1278 // drop new one on the floor, since we can't see any changes.
1279 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1281 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1284 // Test if an associated transaction were not on-chain (or not confirmed).
1285 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1286 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1287 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1288 unsigned_announcement.short_channel_id += 1;
1290 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1291 let valid_announcement = ChannelAnnouncement {
1292 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1293 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1294 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1295 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1296 contents: unsigned_announcement.clone(),
1299 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1301 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1304 // Now test if the transaction is found in the UTXO set and the script is correct.
1305 unsigned_announcement.short_channel_id += 1;
1306 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1308 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1309 let valid_announcement = ChannelAnnouncement {
1310 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1311 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1312 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1313 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1314 contents: unsigned_announcement.clone(),
1316 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1317 Ok(res) => assert!(res),
1322 let network = &net_graph_msg_handler.network_graph;
1323 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1329 // If we receive announcement for the same channel (but TX is not confirmed),
1330 // drop new one on the floor, since we can't see any changes.
1331 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1332 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1334 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1337 // But if it is confirmed, replace the channel
1338 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1339 unsigned_announcement.features = ChannelFeatures::empty();
1340 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1341 let valid_announcement = ChannelAnnouncement {
1342 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1343 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1344 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1345 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1346 contents: unsigned_announcement.clone(),
1348 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1349 Ok(res) => assert!(res),
1353 let network = &net_graph_msg_handler.network_graph;
1354 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1355 Some(channel_entry) => {
1356 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1362 // Don't relay valid channels with excess data
1363 unsigned_announcement.short_channel_id += 1;
1364 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1365 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1366 let valid_announcement = ChannelAnnouncement {
1367 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1368 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1369 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1370 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1371 contents: unsigned_announcement.clone(),
1373 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1374 Ok(res) => assert!(!res),
1378 unsigned_announcement.excess_data = Vec::new();
1379 let invalid_sig_announcement = ChannelAnnouncement {
1380 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1381 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1382 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1383 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1384 contents: unsigned_announcement.clone(),
1386 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1388 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1391 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1392 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1393 let channel_to_itself_announcement = ChannelAnnouncement {
1394 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1395 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1396 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1397 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1398 contents: unsigned_announcement.clone(),
1400 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1402 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1407 fn handling_channel_update() {
1408 let secp_ctx = Secp256k1::new();
1409 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1410 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1411 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1413 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1414 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1415 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1416 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1417 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1418 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1420 let zero_hash = Sha256dHash::hash(&[0; 32]);
1421 let short_channel_id = 0;
1422 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1423 let amount_sats = 1000_000;
1426 // Announce a channel we will update
1427 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1428 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1429 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1430 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1431 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1432 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1433 let unsigned_announcement = UnsignedChannelAnnouncement {
1434 features: ChannelFeatures::empty(),
1439 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1440 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1441 excess_data: Vec::new(),
1444 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1445 let valid_channel_announcement = ChannelAnnouncement {
1446 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1447 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1448 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1449 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1450 contents: unsigned_announcement.clone(),
1452 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1459 let mut unsigned_channel_update = UnsignedChannelUpdate {
1464 cltv_expiry_delta: 144,
1465 htlc_minimum_msat: 1000000,
1466 htlc_maximum_msat: OptionalField::Absent,
1467 fee_base_msat: 10000,
1468 fee_proportional_millionths: 20,
1469 excess_data: Vec::new()
1471 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1472 let valid_channel_update = ChannelUpdate {
1473 signature: secp_ctx.sign(&msghash, node_1_privkey),
1474 contents: unsigned_channel_update.clone()
1477 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1478 Ok(res) => assert!(res),
1483 let network = &net_graph_msg_handler.network_graph;
1484 match network.get_channels().get(&short_channel_id) {
1486 Some(channel_info) => {
1487 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1488 assert!(channel_info.two_to_one.is_none());
1493 unsigned_channel_update.timestamp += 100;
1494 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1495 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1496 let valid_channel_update = ChannelUpdate {
1497 signature: secp_ctx.sign(&msghash, node_1_privkey),
1498 contents: unsigned_channel_update.clone()
1500 // Return false because contains excess data
1501 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1502 Ok(res) => assert!(!res),
1505 unsigned_channel_update.timestamp += 10;
1507 unsigned_channel_update.short_channel_id += 1;
1508 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1509 let valid_channel_update = ChannelUpdate {
1510 signature: secp_ctx.sign(&msghash, node_1_privkey),
1511 contents: unsigned_channel_update.clone()
1514 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1516 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1518 unsigned_channel_update.short_channel_id = short_channel_id;
1520 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1521 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1522 let valid_channel_update = ChannelUpdate {
1523 signature: secp_ctx.sign(&msghash, node_1_privkey),
1524 contents: unsigned_channel_update.clone()
1527 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1529 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1531 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1533 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1534 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1535 let valid_channel_update = ChannelUpdate {
1536 signature: secp_ctx.sign(&msghash, node_1_privkey),
1537 contents: unsigned_channel_update.clone()
1540 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1542 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1544 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1546 // Even though previous update was not relayed further, we still accepted it,
1547 // so we now won't accept update before the previous one.
1548 unsigned_channel_update.timestamp -= 10;
1549 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1550 let valid_channel_update = ChannelUpdate {
1551 signature: secp_ctx.sign(&msghash, node_1_privkey),
1552 contents: unsigned_channel_update.clone()
1555 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1557 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1559 unsigned_channel_update.timestamp += 500;
1561 let fake_msghash = hash_to_message!(&zero_hash);
1562 let invalid_sig_channel_update = ChannelUpdate {
1563 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1564 contents: unsigned_channel_update.clone()
1567 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1569 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1575 fn handling_htlc_fail_channel_update() {
1576 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1577 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1578 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1579 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1580 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1581 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1582 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1584 let short_channel_id = 0;
1585 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1588 // There is no nodes in the table at the beginning.
1589 let network = &net_graph_msg_handler.network_graph;
1590 assert_eq!(network.get_nodes().len(), 0);
1594 // Announce a channel we will update
1595 let unsigned_announcement = UnsignedChannelAnnouncement {
1596 features: ChannelFeatures::empty(),
1601 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1602 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1603 excess_data: Vec::new(),
1606 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1607 let valid_channel_announcement = ChannelAnnouncement {
1608 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1609 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1610 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1611 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1612 contents: unsigned_announcement.clone(),
1614 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1619 let unsigned_channel_update = UnsignedChannelUpdate {
1624 cltv_expiry_delta: 144,
1625 htlc_minimum_msat: 1000000,
1626 htlc_maximum_msat: OptionalField::Absent,
1627 fee_base_msat: 10000,
1628 fee_proportional_millionths: 20,
1629 excess_data: Vec::new()
1631 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1632 let valid_channel_update = ChannelUpdate {
1633 signature: secp_ctx.sign(&msghash, node_1_privkey),
1634 contents: unsigned_channel_update.clone()
1637 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1638 Ok(res) => assert!(res),
1643 // Non-permanent closing just disables a channel
1645 let network = &net_graph_msg_handler.network_graph;
1646 match network.get_channels().get(&short_channel_id) {
1648 Some(channel_info) => {
1649 assert!(channel_info.one_to_two.is_some());
1654 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1659 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1661 // Non-permanent closing just disables a channel
1663 let network = &net_graph_msg_handler.network_graph;
1664 match network.get_channels().get(&short_channel_id) {
1666 Some(channel_info) => {
1667 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1672 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1677 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1679 // Permanent closing deletes a channel
1681 let network = &net_graph_msg_handler.network_graph;
1682 assert_eq!(network.get_channels().len(), 0);
1683 // Nodes are also deleted because there are no associated channels anymore
1684 assert_eq!(network.get_nodes().len(), 0);
1686 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1690 fn getting_next_channel_announcements() {
1691 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1692 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1693 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1694 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1695 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1696 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1697 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1699 let short_channel_id = 1;
1700 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1702 // Channels were not announced yet.
1703 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1704 assert_eq!(channels_with_announcements.len(), 0);
1707 // Announce a channel we will update
1708 let unsigned_announcement = UnsignedChannelAnnouncement {
1709 features: ChannelFeatures::empty(),
1714 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1715 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1716 excess_data: Vec::new(),
1719 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1720 let valid_channel_announcement = ChannelAnnouncement {
1721 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1722 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1723 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1724 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1725 contents: unsigned_announcement.clone(),
1727 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1733 // Contains initial channel announcement now.
1734 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1735 assert_eq!(channels_with_announcements.len(), 1);
1736 if let Some(channel_announcements) = channels_with_announcements.first() {
1737 let &(_, ref update_1, ref update_2) = channel_announcements;
1738 assert_eq!(update_1, &None);
1739 assert_eq!(update_2, &None);
1746 // Valid channel update
1747 let unsigned_channel_update = UnsignedChannelUpdate {
1752 cltv_expiry_delta: 144,
1753 htlc_minimum_msat: 1000000,
1754 htlc_maximum_msat: OptionalField::Absent,
1755 fee_base_msat: 10000,
1756 fee_proportional_millionths: 20,
1757 excess_data: Vec::new()
1759 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1760 let valid_channel_update = ChannelUpdate {
1761 signature: secp_ctx.sign(&msghash, node_1_privkey),
1762 contents: unsigned_channel_update.clone()
1764 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1770 // Now contains an initial announcement and an update.
1771 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1772 assert_eq!(channels_with_announcements.len(), 1);
1773 if let Some(channel_announcements) = channels_with_announcements.first() {
1774 let &(_, ref update_1, ref update_2) = channel_announcements;
1775 assert_ne!(update_1, &None);
1776 assert_eq!(update_2, &None);
1783 // Channel update with excess data.
1784 let unsigned_channel_update = UnsignedChannelUpdate {
1789 cltv_expiry_delta: 144,
1790 htlc_minimum_msat: 1000000,
1791 htlc_maximum_msat: OptionalField::Absent,
1792 fee_base_msat: 10000,
1793 fee_proportional_millionths: 20,
1794 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1796 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1797 let valid_channel_update = ChannelUpdate {
1798 signature: secp_ctx.sign(&msghash, node_1_privkey),
1799 contents: unsigned_channel_update.clone()
1801 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1807 // Test that announcements with excess data won't be returned
1808 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1809 assert_eq!(channels_with_announcements.len(), 1);
1810 if let Some(channel_announcements) = channels_with_announcements.first() {
1811 let &(_, ref update_1, ref update_2) = channel_announcements;
1812 assert_eq!(update_1, &None);
1813 assert_eq!(update_2, &None);
1818 // Further starting point have no channels after it
1819 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1820 assert_eq!(channels_with_announcements.len(), 0);
1824 fn getting_next_node_announcements() {
1825 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1826 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1827 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1828 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1829 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1830 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1831 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1833 let short_channel_id = 1;
1834 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1837 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1838 assert_eq!(next_announcements.len(), 0);
1841 // Announce a channel to add 2 nodes
1842 let unsigned_announcement = UnsignedChannelAnnouncement {
1843 features: ChannelFeatures::empty(),
1848 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1849 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1850 excess_data: Vec::new(),
1853 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1854 let valid_channel_announcement = ChannelAnnouncement {
1855 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1856 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1857 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1858 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1859 contents: unsigned_announcement.clone(),
1861 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1868 // Nodes were never announced
1869 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1870 assert_eq!(next_announcements.len(), 0);
1873 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1874 features: NodeFeatures::known(),
1879 addresses: Vec::new(),
1880 excess_address_data: Vec::new(),
1881 excess_data: Vec::new(),
1883 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1884 let valid_announcement = NodeAnnouncement {
1885 signature: secp_ctx.sign(&msghash, node_1_privkey),
1886 contents: unsigned_announcement.clone()
1888 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1893 unsigned_announcement.node_id = node_id_2;
1894 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1895 let valid_announcement = NodeAnnouncement {
1896 signature: secp_ctx.sign(&msghash, node_2_privkey),
1897 contents: unsigned_announcement.clone()
1900 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1906 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1907 assert_eq!(next_announcements.len(), 2);
1909 // Skip the first node.
1910 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1911 assert_eq!(next_announcements.len(), 1);
1914 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1915 let unsigned_announcement = UnsignedNodeAnnouncement {
1916 features: NodeFeatures::known(),
1921 addresses: Vec::new(),
1922 excess_address_data: Vec::new(),
1923 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
1925 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1926 let valid_announcement = NodeAnnouncement {
1927 signature: secp_ctx.sign(&msghash, node_2_privkey),
1928 contents: unsigned_announcement.clone()
1930 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1931 Ok(res) => assert!(!res),
1936 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1937 assert_eq!(next_announcements.len(), 0);
1941 fn network_graph_serialization() {
1942 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1944 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1945 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1946 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1947 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1949 // Announce a channel to add a corresponding node.
1950 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1951 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1952 let unsigned_announcement = UnsignedChannelAnnouncement {
1953 features: ChannelFeatures::known(),
1954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1955 short_channel_id: 0,
1958 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1959 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1960 excess_data: Vec::new(),
1963 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1964 let valid_announcement = ChannelAnnouncement {
1965 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1966 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1967 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1968 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1969 contents: unsigned_announcement.clone(),
1971 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1972 Ok(res) => assert!(res),
1977 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1978 let unsigned_announcement = UnsignedNodeAnnouncement {
1979 features: NodeFeatures::known(),
1984 addresses: Vec::new(),
1985 excess_address_data: Vec::new(),
1986 excess_data: Vec::new(),
1988 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1989 let valid_announcement = NodeAnnouncement {
1990 signature: secp_ctx.sign(&msghash, node_1_privkey),
1991 contents: unsigned_announcement.clone()
1994 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1999 let network = &net_graph_msg_handler.network_graph;
2000 let mut w = test_utils::TestVecWriter(Vec::new());
2001 assert!(!network.get_nodes().is_empty());
2002 assert!(!network.get_channels().is_empty());
2003 network.write(&mut w).unwrap();
2004 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == *network);
2008 fn calling_sync_routing_table() {
2009 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2010 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2011 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2013 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2014 let first_blocknum = 0;
2015 let number_of_blocks = 0xffff_ffff;
2017 // It should ignore if gossip_queries feature is not enabled
2019 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2020 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2021 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2022 assert_eq!(events.len(), 0);
2025 // It should send a query_channel_message with the correct information
2027 let init_msg = Init { features: InitFeatures::known() };
2028 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2029 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2030 assert_eq!(events.len(), 1);
2032 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2033 assert_eq!(node_id, &node_id_1);
2034 assert_eq!(msg.chain_hash, chain_hash);
2035 assert_eq!(msg.first_blocknum, first_blocknum);
2036 assert_eq!(msg.number_of_blocks, number_of_blocks);
2038 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2042 // It should not enqueue a query when should_request_full_sync return false.
2043 // The initial implementation allows syncing with the first 5 peers after
2044 // which should_request_full_sync will return false
2046 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2047 let init_msg = Init { features: InitFeatures::known() };
2049 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2050 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2051 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2052 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2054 assert_eq!(events.len(), 1);
2056 assert_eq!(events.len(), 0);
2064 fn handling_reply_channel_range() {
2065 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2066 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2067 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2069 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2071 // Test receipt of a single reply that should enqueue an SCID query
2072 // matching the SCIDs in the reply
2074 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2076 sync_complete: true,
2078 number_of_blocks: 2000,
2079 short_channel_ids: vec![
2080 0x0003e0_000000_0000, // 992x0x0
2081 0x0003e8_000000_0000, // 1000x0x0
2082 0x0003e9_000000_0000, // 1001x0x0
2083 0x0003f0_000000_0000, // 1008x0x0
2084 0x00044c_000000_0000, // 1100x0x0
2085 0x0006e0_000000_0000, // 1760x0x0
2088 assert!(result.is_ok());
2090 // We expect to emit a query_short_channel_ids message with the received scids
2091 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2092 assert_eq!(events.len(), 1);
2094 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2095 assert_eq!(node_id, &node_id_1);
2096 assert_eq!(msg.chain_hash, chain_hash);
2097 assert_eq!(msg.short_channel_ids, vec![
2098 0x0003e0_000000_0000, // 992x0x0
2099 0x0003e8_000000_0000, // 1000x0x0
2100 0x0003e9_000000_0000, // 1001x0x0
2101 0x0003f0_000000_0000, // 1008x0x0
2102 0x00044c_000000_0000, // 1100x0x0
2103 0x0006e0_000000_0000, // 1760x0x0
2106 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2112 fn handling_reply_short_channel_ids() {
2113 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2114 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2115 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2117 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2119 // Test receipt of a successful reply
2121 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2123 full_information: true,
2125 assert!(result.is_ok());
2128 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2129 // for the chain_hash requested in the query.
2131 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2133 full_information: false,
2135 assert!(result.is_err());
2136 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2141 fn handling_query_channel_range() {
2142 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2144 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2145 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2146 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2147 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2148 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2149 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2150 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2151 let bitcoin_key_1 = PublicKey::from_secret_key(&secp_ctx, node_1_btckey);
2152 let bitcoin_key_2 = PublicKey::from_secret_key(&secp_ctx, node_2_btckey);
2154 let mut scids: Vec<u64> = vec![
2155 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2156 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2159 // used for testing multipart reply across blocks
2160 for block in 100000..=108001 {
2161 scids.push(scid_from_parts(block, 0, 0).unwrap());
2164 // used for testing resumption on same block
2165 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2168 let unsigned_announcement = UnsignedChannelAnnouncement {
2169 features: ChannelFeatures::known(),
2170 chain_hash: chain_hash.clone(),
2171 short_channel_id: scid,
2176 excess_data: Vec::new(),
2179 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2180 let valid_announcement = ChannelAnnouncement {
2181 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2182 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2183 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2184 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2185 contents: unsigned_announcement.clone(),
2187 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2193 // Error when number_of_blocks=0
2194 do_handling_query_channel_range(
2195 &net_graph_msg_handler,
2198 chain_hash: chain_hash.clone(),
2200 number_of_blocks: 0,
2203 vec![ReplyChannelRange {
2204 chain_hash: chain_hash.clone(),
2206 number_of_blocks: 0,
2207 sync_complete: true,
2208 short_channel_ids: vec![]
2212 // Error when wrong chain
2213 do_handling_query_channel_range(
2214 &net_graph_msg_handler,
2217 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2219 number_of_blocks: 0xffff_ffff,
2222 vec![ReplyChannelRange {
2223 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2225 number_of_blocks: 0xffff_ffff,
2226 sync_complete: true,
2227 short_channel_ids: vec![],
2231 // Error when first_blocknum > 0xffffff
2232 do_handling_query_channel_range(
2233 &net_graph_msg_handler,
2236 chain_hash: chain_hash.clone(),
2237 first_blocknum: 0x01000000,
2238 number_of_blocks: 0xffff_ffff,
2241 vec![ReplyChannelRange {
2242 chain_hash: chain_hash.clone(),
2243 first_blocknum: 0x01000000,
2244 number_of_blocks: 0xffff_ffff,
2245 sync_complete: true,
2246 short_channel_ids: vec![]
2250 // Empty reply when max valid SCID block num
2251 do_handling_query_channel_range(
2252 &net_graph_msg_handler,
2255 chain_hash: chain_hash.clone(),
2256 first_blocknum: 0xffffff,
2257 number_of_blocks: 1,
2262 chain_hash: chain_hash.clone(),
2263 first_blocknum: 0xffffff,
2264 number_of_blocks: 1,
2265 sync_complete: true,
2266 short_channel_ids: vec![]
2271 // No results in valid query range
2272 do_handling_query_channel_range(
2273 &net_graph_msg_handler,
2276 chain_hash: chain_hash.clone(),
2277 first_blocknum: 1000,
2278 number_of_blocks: 1000,
2283 chain_hash: chain_hash.clone(),
2284 first_blocknum: 1000,
2285 number_of_blocks: 1000,
2286 sync_complete: true,
2287 short_channel_ids: vec![],
2292 // Overflow first_blocknum + number_of_blocks
2293 do_handling_query_channel_range(
2294 &net_graph_msg_handler,
2297 chain_hash: chain_hash.clone(),
2298 first_blocknum: 0xfe0000,
2299 number_of_blocks: 0xffffffff,
2304 chain_hash: chain_hash.clone(),
2305 first_blocknum: 0xfe0000,
2306 number_of_blocks: 0xffffffff - 0xfe0000,
2307 sync_complete: true,
2308 short_channel_ids: vec![
2309 0xfffffe_ffffff_ffff, // max
2315 // Single block exactly full
2316 do_handling_query_channel_range(
2317 &net_graph_msg_handler,
2320 chain_hash: chain_hash.clone(),
2321 first_blocknum: 100000,
2322 number_of_blocks: 8000,
2327 chain_hash: chain_hash.clone(),
2328 first_blocknum: 100000,
2329 number_of_blocks: 8000,
2330 sync_complete: true,
2331 short_channel_ids: (100000..=107999)
2332 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2338 // Multiple split on new block
2339 do_handling_query_channel_range(
2340 &net_graph_msg_handler,
2343 chain_hash: chain_hash.clone(),
2344 first_blocknum: 100000,
2345 number_of_blocks: 8001,
2350 chain_hash: chain_hash.clone(),
2351 first_blocknum: 100000,
2352 number_of_blocks: 7999,
2353 sync_complete: false,
2354 short_channel_ids: (100000..=107999)
2355 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2359 chain_hash: chain_hash.clone(),
2360 first_blocknum: 107999,
2361 number_of_blocks: 2,
2362 sync_complete: true,
2363 short_channel_ids: vec![
2364 scid_from_parts(108000, 0, 0).unwrap(),
2370 // Multiple split on same block
2371 do_handling_query_channel_range(
2372 &net_graph_msg_handler,
2375 chain_hash: chain_hash.clone(),
2376 first_blocknum: 100002,
2377 number_of_blocks: 8000,
2382 chain_hash: chain_hash.clone(),
2383 first_blocknum: 100002,
2384 number_of_blocks: 7999,
2385 sync_complete: false,
2386 short_channel_ids: (100002..=108001)
2387 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2391 chain_hash: chain_hash.clone(),
2392 first_blocknum: 108001,
2393 number_of_blocks: 1,
2394 sync_complete: true,
2395 short_channel_ids: vec![
2396 scid_from_parts(108001, 1, 0).unwrap(),
2403 fn do_handling_query_channel_range(
2404 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2405 test_node_id: &PublicKey,
2406 msg: QueryChannelRange,
2408 expected_replies: Vec<ReplyChannelRange>
2410 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2411 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2412 let query_end_blocknum = msg.end_blocknum();
2413 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2416 assert!(result.is_ok());
2418 assert!(result.is_err());
2421 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2422 assert_eq!(events.len(), expected_replies.len());
2424 for i in 0..events.len() {
2425 let expected_reply = &expected_replies[i];
2427 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2428 assert_eq!(node_id, test_node_id);
2429 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2430 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2431 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2432 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2433 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2435 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2436 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2437 assert!(msg.first_blocknum >= max_firstblocknum);
2438 max_firstblocknum = msg.first_blocknum;
2439 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2441 // Check that the last block count is >= the query's end_blocknum
2442 if i == events.len() - 1 {
2443 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2446 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2452 fn handling_query_short_channel_ids() {
2453 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2454 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2455 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2457 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2459 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2461 short_channel_ids: vec![0x0003e8_000000_0000],
2463 assert!(result.is_err());
2467 #[cfg(all(test, feature = "unstable"))]
2475 fn read_network_graph(bench: &mut Bencher) {
2476 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2477 let mut v = Vec::new();
2478 d.read_to_end(&mut v).unwrap();
2480 let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2485 fn write_network_graph(bench: &mut Bencher) {
2486 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2487 let net_graph = NetworkGraph::read(&mut d).unwrap();
2489 let _ = net_graph.encode();