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::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
33 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
37 use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
39 use sync::{RwLock, RwLockReadGuard};
40 use core::sync::atomic::{AtomicUsize, Ordering};
43 use bitcoin::hashes::hex::ToHex;
45 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
46 /// refuse to relay the message.
47 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
49 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
50 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
51 const MAX_SCIDS_PER_REPLY: usize = 8000;
53 /// Represents the network as nodes and channels between them
54 pub struct NetworkGraph {
55 genesis_hash: BlockHash,
56 // Lock order: channels -> nodes
57 channels: RwLock<BTreeMap<u64, ChannelInfo>>,
58 nodes: RwLock<BTreeMap<PublicKey, NodeInfo>>,
61 /// A read-only view of [`NetworkGraph`].
62 pub struct ReadOnlyNetworkGraph<'a> {
63 channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
64 nodes: RwLockReadGuard<'a, BTreeMap<PublicKey, NodeInfo>>,
67 /// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
68 /// return packet by a node along the route. See [BOLT #4] for details.
70 /// [BOLT #4]: https://github.com/lightningnetwork/lightning-rfc/blob/master/04-onion-routing.md
71 #[derive(Clone, Debug, PartialEq)]
72 pub enum NetworkUpdate {
73 /// An error indicating a `channel_update` messages should be applied via
74 /// [`NetworkGraph::update_channel`].
75 ChannelUpdateMessage {
76 /// The update to apply via [`NetworkGraph::update_channel`].
79 /// An error indicating only that a channel has been closed, which should be applied via
80 /// [`NetworkGraph::close_channel_from_update`].
82 /// The short channel id of the closed channel.
83 short_channel_id: u64,
84 /// Whether the channel should be permanently removed or temporarily disabled until a new
85 /// `channel_update` message is received.
88 /// An error indicating only that a node has failed, which should be applied via
89 /// [`NetworkGraph::fail_node`].
91 /// The node id of the failed node.
93 /// Whether the node should be permanently removed from consideration or can be restored
94 /// when a new `channel_update` message is received.
99 impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
100 (0, ChannelUpdateMessage) => {
103 (2, ChannelClosed) => {
104 (0, short_channel_id, required),
105 (2, is_permanent, required),
107 (4, NodeFailure) => {
108 (0, node_id, required),
109 (2, is_permanent, required),
113 impl<C: Deref, L: Deref> EventHandler for NetGraphMsgHandler<C, L>
114 where C::Target: chain::Access, L::Target: Logger {
115 fn handle_event(&self, event: &Event) {
116 if let Event::PaymentFailed { payment_hash: _, rejected_by_dest: _, network_update, .. } = event {
117 if let Some(network_update) = network_update {
118 self.handle_network_update(network_update);
124 /// Receives and validates network updates from peers,
125 /// stores authentic and relevant data as a network graph.
126 /// This network graph is then used for routing payments.
127 /// Provides interface to help with initial routing sync by
128 /// serving historical announcements.
130 /// Serves as an [`EventHandler`] for applying updates from [`Event::PaymentFailed`] to the
131 /// [`NetworkGraph`].
132 pub struct NetGraphMsgHandler<C: Deref, L: Deref>
133 where C::Target: chain::Access, L::Target: Logger
135 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
136 /// Representation of the payment channel network
137 pub network_graph: NetworkGraph,
138 chain_access: Option<C>,
139 full_syncs_requested: AtomicUsize,
140 pending_events: Mutex<Vec<MessageSendEvent>>,
144 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L>
145 where C::Target: chain::Access, L::Target: Logger
147 /// Creates a new tracker of the actual state of the network of channels and nodes,
148 /// assuming an existing Network Graph.
149 /// Chain monitor is used to make sure announced channels exist on-chain,
150 /// channel data is correct, and that the announcement is signed with
151 /// channel owners' keys.
152 pub fn new(network_graph: NetworkGraph, chain_access: Option<C>, logger: L) -> Self {
154 secp_ctx: Secp256k1::verification_only(),
156 full_syncs_requested: AtomicUsize::new(0),
158 pending_events: Mutex::new(vec![]),
163 /// Adds a provider used to check new announcements. Does not affect
164 /// existing announcements unless they are updated.
165 /// Add, update or remove the provider would replace the current one.
166 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
167 self.chain_access = chain_access;
170 /// Returns true when a full routing table sync should be performed with a peer.
171 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
172 //TODO: Determine whether to request a full sync based on the network map.
173 const FULL_SYNCS_TO_REQUEST: usize = 5;
174 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
175 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
182 /// Applies changes to the [`NetworkGraph`] from the given update.
183 fn handle_network_update(&self, update: &NetworkUpdate) {
185 NetworkUpdate::ChannelUpdateMessage { ref msg } => {
186 let short_channel_id = msg.contents.short_channel_id;
187 let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
188 let status = if is_enabled { "enabled" } else { "disabled" };
189 log_debug!(self.logger, "Updating channel with channel_update from a payment failure. Channel {} is {}.", short_channel_id, status);
190 let _ = self.network_graph.update_channel(msg, &self.secp_ctx);
192 NetworkUpdate::ChannelClosed { short_channel_id, is_permanent } => {
193 let action = if is_permanent { "Removing" } else { "Disabling" };
194 log_debug!(self.logger, "{} channel graph entry for {} due to a payment failure.", action, short_channel_id);
195 self.network_graph.close_channel_from_update(short_channel_id, is_permanent);
197 NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
198 let action = if is_permanent { "Removing" } else { "Disabling" };
199 log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", action, node_id);
200 self.network_graph.fail_node(node_id, is_permanent);
206 macro_rules! secp_verify_sig {
207 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
208 match $secp_ctx.verify($msg, $sig, $pubkey) {
210 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
215 impl<C: Deref, L: Deref> RoutingMessageHandler for NetGraphMsgHandler<C, L>
216 where C::Target: chain::Access, L::Target: Logger
218 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
219 self.network_graph.update_node_from_announcement(msg, &self.secp_ctx)?;
220 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
221 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
222 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
225 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
226 self.network_graph.update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
227 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 { "" });
228 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
231 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
232 self.network_graph.update_channel(msg, &self.secp_ctx)?;
233 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
236 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
237 let mut result = Vec::with_capacity(batch_amount as usize);
238 let channels = self.network_graph.channels.read().unwrap();
239 let mut iter = channels.range(starting_point..);
240 while result.len() < batch_amount as usize {
241 if let Some((_, ref chan)) = iter.next() {
242 if chan.announcement_message.is_some() {
243 let chan_announcement = chan.announcement_message.clone().unwrap();
244 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
245 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
246 if let Some(one_to_two) = chan.one_to_two.as_ref() {
247 one_to_two_announcement = one_to_two.last_update_message.clone();
249 if let Some(two_to_one) = chan.two_to_one.as_ref() {
250 two_to_one_announcement = two_to_one.last_update_message.clone();
252 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
254 // TODO: We may end up sending un-announced channel_updates if we are sending
255 // initial sync data while receiving announce/updates for this channel.
264 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
265 let mut result = Vec::with_capacity(batch_amount as usize);
266 let nodes = self.network_graph.nodes.read().unwrap();
267 let mut iter = if let Some(pubkey) = starting_point {
268 let mut iter = nodes.range((*pubkey)..);
274 while result.len() < batch_amount as usize {
275 if let Some((_, ref node)) = iter.next() {
276 if let Some(node_info) = node.announcement_info.as_ref() {
277 if node_info.announcement_message.is_some() {
278 result.push(node_info.announcement_message.clone().unwrap());
288 /// Initiates a stateless sync of routing gossip information with a peer
289 /// using gossip_queries. The default strategy used by this implementation
290 /// is to sync the full block range with several peers.
292 /// We should expect one or more reply_channel_range messages in response
293 /// to our query_channel_range. Each reply will enqueue a query_scid message
294 /// to request gossip messages for each channel. The sync is considered complete
295 /// when the final reply_scids_end message is received, though we are not
296 /// tracking this directly.
297 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
299 // We will only perform a sync with peers that support gossip_queries.
300 if !init_msg.features.supports_gossip_queries() {
304 // Check if we need to perform a full synchronization with this peer
305 if !self.should_request_full_sync(their_node_id) {
309 let first_blocknum = 0;
310 let number_of_blocks = 0xffffffff;
311 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
312 let mut pending_events = self.pending_events.lock().unwrap();
313 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
314 node_id: their_node_id.clone(),
315 msg: QueryChannelRange {
316 chain_hash: self.network_graph.genesis_hash,
323 /// Statelessly processes a reply to a channel range query by immediately
324 /// sending an SCID query with SCIDs in the reply. To keep this handler
325 /// stateless, it does not validate the sequencing of replies for multi-
326 /// reply ranges. It does not validate whether the reply(ies) cover the
327 /// queried range. It also does not filter SCIDs to only those in the
328 /// original query range. We also do not validate that the chain_hash
329 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
330 /// does not match our chain_hash will be rejected when the announcement is
332 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
333 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(),);
335 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
336 let mut pending_events = self.pending_events.lock().unwrap();
337 pending_events.push(MessageSendEvent::SendShortIdsQuery {
338 node_id: their_node_id.clone(),
339 msg: QueryShortChannelIds {
340 chain_hash: msg.chain_hash,
341 short_channel_ids: msg.short_channel_ids,
348 /// When an SCID query is initiated the remote peer will begin streaming
349 /// gossip messages. In the event of a failure, we may have received
350 /// some channel information. Before trying with another peer, the
351 /// caller should update its set of SCIDs that need to be queried.
352 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
353 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
355 // If the remote node does not have up-to-date information for the
356 // chain_hash they will set full_information=false. We can fail
357 // the result and try again with a different peer.
358 if !msg.full_information {
359 return Err(LightningError {
360 err: String::from("Received reply_short_channel_ids_end with no information"),
361 action: ErrorAction::IgnoreError
368 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
369 /// are in the specified block range. Due to message size limits, large range
370 /// queries may result in several reply messages. This implementation enqueues
371 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
372 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
373 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
374 /// memory constrained systems.
375 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
376 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);
378 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
380 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
381 // If so, we manually cap the ending block to avoid this overflow.
382 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
384 // Per spec, we must reply to a query. Send an empty message when things are invalid.
385 if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
386 let mut pending_events = self.pending_events.lock().unwrap();
387 pending_events.push(MessageSendEvent::SendReplyChannelRange {
388 node_id: their_node_id.clone(),
389 msg: ReplyChannelRange {
390 chain_hash: msg.chain_hash.clone(),
391 first_blocknum: msg.first_blocknum,
392 number_of_blocks: msg.number_of_blocks,
394 short_channel_ids: vec![],
397 return Err(LightningError {
398 err: String::from("query_channel_range could not be processed"),
399 action: ErrorAction::IgnoreError,
403 // Creates channel batches. We are not checking if the channel is routable
404 // (has at least one update). A peer may still want to know the channel
405 // exists even if its not yet routable.
406 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
407 let channels = self.network_graph.channels.read().unwrap();
408 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
409 if let Some(chan_announcement) = &chan.announcement_message {
410 // Construct a new batch if last one is full
411 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
412 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
415 let batch = batches.last_mut().unwrap();
416 batch.push(chan_announcement.contents.short_channel_id);
421 let mut pending_events = self.pending_events.lock().unwrap();
422 let batch_count = batches.len();
423 let mut prev_batch_endblock = msg.first_blocknum;
424 for (batch_index, batch) in batches.into_iter().enumerate() {
425 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
426 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
428 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
429 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
430 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
431 // significant diversion from the requirements set by the spec, and, in case of blocks
432 // with no channel opens (e.g. empty blocks), requires that we use the previous value
433 // and *not* derive the first_blocknum from the actual first block of the reply.
434 let first_blocknum = prev_batch_endblock;
436 // Each message carries the number of blocks (from the `first_blocknum`) its contents
437 // fit in. Though there is no requirement that we use exactly the number of blocks its
438 // contents are from, except for the bogus requirements c-lightning enforces, above.
440 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
441 // >= the query's end block. Thus, for the last reply, we calculate the difference
442 // between the query's end block and the start of the reply.
444 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
445 // first_blocknum will be either msg.first_blocknum or a higher block height.
446 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
447 (true, msg.end_blocknum() - first_blocknum)
449 // Prior replies should use the number of blocks that fit into the reply. Overflow
450 // safe since first_blocknum is always <= last SCID's block.
452 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
455 prev_batch_endblock = first_blocknum + number_of_blocks;
457 pending_events.push(MessageSendEvent::SendReplyChannelRange {
458 node_id: their_node_id.clone(),
459 msg: ReplyChannelRange {
460 chain_hash: msg.chain_hash.clone(),
464 short_channel_ids: batch,
472 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
475 err: String::from("Not implemented"),
476 action: ErrorAction::IgnoreError,
481 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
483 C::Target: chain::Access,
486 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
487 let mut ret = Vec::new();
488 let mut pending_events = self.pending_events.lock().unwrap();
489 core::mem::swap(&mut ret, &mut pending_events);
494 #[derive(Clone, Debug, PartialEq)]
495 /// Details about one direction of a channel. Received
496 /// within a channel update.
497 pub struct DirectionalChannelInfo {
498 /// When the last update to the channel direction was issued.
499 /// Value is opaque, as set in the announcement.
500 pub last_update: u32,
501 /// Whether the channel can be currently used for payments (in this one direction).
503 /// The difference in CLTV values that you must have when routing through this channel.
504 pub cltv_expiry_delta: u16,
505 /// The minimum value, which must be relayed to the next hop via the channel
506 pub htlc_minimum_msat: u64,
507 /// The maximum value which may be relayed to the next hop via the channel.
508 pub htlc_maximum_msat: Option<u64>,
509 /// Fees charged when the channel is used for routing
510 pub fees: RoutingFees,
511 /// Most recent update for the channel received from the network
512 /// Mostly redundant with the data we store in fields explicitly.
513 /// Everything else is useful only for sending out for initial routing sync.
514 /// Not stored if contains excess data to prevent DoS.
515 pub last_update_message: Option<ChannelUpdate>,
518 impl fmt::Display for DirectionalChannelInfo {
519 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
520 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)?;
525 impl_writeable_tlv_based!(DirectionalChannelInfo, {
526 (0, last_update, required),
527 (2, enabled, required),
528 (4, cltv_expiry_delta, required),
529 (6, htlc_minimum_msat, required),
530 (8, htlc_maximum_msat, required),
531 (10, fees, required),
532 (12, last_update_message, required),
535 #[derive(Clone, Debug, PartialEq)]
536 /// Details about a channel (both directions).
537 /// Received within a channel announcement.
538 pub struct ChannelInfo {
539 /// Protocol features of a channel communicated during its announcement
540 pub features: ChannelFeatures,
541 /// Source node of the first direction of a channel
542 pub node_one: PublicKey,
543 /// Details about the first direction of a channel
544 pub one_to_two: Option<DirectionalChannelInfo>,
545 /// Source node of the second direction of a channel
546 pub node_two: PublicKey,
547 /// Details about the second direction of a channel
548 pub two_to_one: Option<DirectionalChannelInfo>,
549 /// The channel capacity as seen on-chain, if chain lookup is available.
550 pub capacity_sats: Option<u64>,
551 /// An initial announcement of the channel
552 /// Mostly redundant with the data we store in fields explicitly.
553 /// Everything else is useful only for sending out for initial routing sync.
554 /// Not stored if contains excess data to prevent DoS.
555 pub announcement_message: Option<ChannelAnnouncement>,
558 impl fmt::Display for ChannelInfo {
559 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
560 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
561 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
566 impl_writeable_tlv_based!(ChannelInfo, {
567 (0, features, required),
568 (2, node_one, required),
569 (4, one_to_two, required),
570 (6, node_two, required),
571 (8, two_to_one, required),
572 (10, capacity_sats, required),
573 (12, announcement_message, required),
577 /// Fees for routing via a given channel or a node
578 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
579 pub struct RoutingFees {
580 /// Flat routing fee in satoshis
582 /// Liquidity-based routing fee in millionths of a routed amount.
583 /// In other words, 10000 is 1%.
584 pub proportional_millionths: u32,
587 impl_writeable_tlv_based!(RoutingFees, {
588 (0, base_msat, required),
589 (2, proportional_millionths, required)
592 #[derive(Clone, Debug, PartialEq)]
593 /// Information received in the latest node_announcement from this node.
594 pub struct NodeAnnouncementInfo {
595 /// Protocol features the node announced support for
596 pub features: NodeFeatures,
597 /// When the last known update to the node state was issued.
598 /// Value is opaque, as set in the announcement.
599 pub last_update: u32,
600 /// Color assigned to the node
602 /// Moniker assigned to the node.
603 /// May be invalid or malicious (eg control chars),
604 /// should not be exposed to the user.
606 /// Internet-level addresses via which one can connect to the node
607 pub addresses: Vec<NetAddress>,
608 /// An initial announcement of the node
609 /// Mostly redundant with the data we store in fields explicitly.
610 /// Everything else is useful only for sending out for initial routing sync.
611 /// Not stored if contains excess data to prevent DoS.
612 pub announcement_message: Option<NodeAnnouncement>
615 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
616 (0, features, required),
617 (2, last_update, required),
619 (6, alias, required),
620 (8, announcement_message, option),
621 (10, addresses, vec_type),
624 #[derive(Clone, Debug, PartialEq)]
625 /// Details about a node in the network, known from the network announcement.
626 pub struct NodeInfo {
627 /// All valid channels a node has announced
628 pub channels: Vec<u64>,
629 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
630 /// The two fields (flat and proportional fee) are independent,
631 /// meaning they don't have to refer to the same channel.
632 pub lowest_inbound_channel_fees: Option<RoutingFees>,
633 /// More information about a node from node_announcement.
634 /// Optional because we store a Node entry after learning about it from
635 /// a channel announcement, but before receiving a node announcement.
636 pub announcement_info: Option<NodeAnnouncementInfo>
639 impl fmt::Display for NodeInfo {
640 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
641 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
642 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
647 impl_writeable_tlv_based!(NodeInfo, {
648 (0, lowest_inbound_channel_fees, option),
649 (2, announcement_info, option),
650 (4, channels, vec_type),
653 const SERIALIZATION_VERSION: u8 = 1;
654 const MIN_SERIALIZATION_VERSION: u8 = 1;
656 impl Writeable for NetworkGraph {
657 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
658 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
660 self.genesis_hash.write(writer)?;
661 let channels = self.channels.read().unwrap();
662 (channels.len() as u64).write(writer)?;
663 for (ref chan_id, ref chan_info) in channels.iter() {
664 (*chan_id).write(writer)?;
665 chan_info.write(writer)?;
667 let nodes = self.nodes.read().unwrap();
668 (nodes.len() as u64).write(writer)?;
669 for (ref node_id, ref node_info) in nodes.iter() {
670 node_id.write(writer)?;
671 node_info.write(writer)?;
674 write_tlv_fields!(writer, {});
679 impl Readable for NetworkGraph {
680 fn read<R: io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
681 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
683 let genesis_hash: BlockHash = Readable::read(reader)?;
684 let channels_count: u64 = Readable::read(reader)?;
685 let mut channels = BTreeMap::new();
686 for _ in 0..channels_count {
687 let chan_id: u64 = Readable::read(reader)?;
688 let chan_info = Readable::read(reader)?;
689 channels.insert(chan_id, chan_info);
691 let nodes_count: u64 = Readable::read(reader)?;
692 let mut nodes = BTreeMap::new();
693 for _ in 0..nodes_count {
694 let node_id = Readable::read(reader)?;
695 let node_info = Readable::read(reader)?;
696 nodes.insert(node_id, node_info);
698 read_tlv_fields!(reader, {});
702 channels: RwLock::new(channels),
703 nodes: RwLock::new(nodes),
708 impl fmt::Display for NetworkGraph {
709 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
710 writeln!(f, "Network map\n[Channels]")?;
711 for (key, val) in self.channels.read().unwrap().iter() {
712 writeln!(f, " {}: {}", key, val)?;
714 writeln!(f, "[Nodes]")?;
715 for (key, val) in self.nodes.read().unwrap().iter() {
716 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
722 impl PartialEq for NetworkGraph {
723 fn eq(&self, other: &Self) -> bool {
724 self.genesis_hash == other.genesis_hash &&
725 *self.channels.read().unwrap() == *other.channels.read().unwrap() &&
726 *self.nodes.read().unwrap() == *other.nodes.read().unwrap()
731 /// Creates a new, empty, network graph.
732 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
735 channels: RwLock::new(BTreeMap::new()),
736 nodes: RwLock::new(BTreeMap::new()),
740 /// Returns a read-only view of the network graph.
741 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
742 let channels = self.channels.read().unwrap();
743 let nodes = self.nodes.read().unwrap();
744 ReadOnlyNetworkGraph {
750 /// For an already known node (from channel announcements), update its stored properties from a
751 /// given node announcement.
753 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
754 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
755 /// routing messages from a source using a protocol other than the lightning P2P protocol.
756 pub fn update_node_from_announcement<T: secp256k1::Verification>(&self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
757 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
758 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
759 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
762 /// For an already known node (from channel announcements), update its stored properties from a
763 /// given node announcement without verifying the associated signatures. Because we aren't
764 /// given the associated signatures here we cannot relay the node announcement to any of our
766 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
767 self.update_node_from_announcement_intern(msg, None)
770 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
771 match self.nodes.write().unwrap().get_mut(&msg.node_id) {
772 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
774 if let Some(node_info) = node.announcement_info.as_ref() {
775 if node_info.last_update >= msg.timestamp {
776 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
781 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
782 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
783 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
784 node.announcement_info = Some(NodeAnnouncementInfo {
785 features: msg.features.clone(),
786 last_update: msg.timestamp,
789 addresses: msg.addresses.clone(),
790 announcement_message: if should_relay { full_msg.cloned() } else { None },
798 /// Store or update channel info from a channel announcement.
800 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
801 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
802 /// routing messages from a source using a protocol other than the lightning P2P protocol.
804 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
805 /// the corresponding UTXO exists on chain and is correctly-formatted.
806 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>(
807 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>
808 ) -> Result<(), LightningError>
810 C::Target: chain::Access,
812 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
813 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
814 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
815 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
816 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
817 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
820 /// Store or update channel info from a channel announcement without verifying the associated
821 /// signatures. Because we aren't given the associated signatures here we cannot relay the
822 /// channel announcement to any of our peers.
824 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
825 /// the corresponding UTXO exists on chain and is correctly-formatted.
826 pub fn update_channel_from_unsigned_announcement<C: Deref>(
827 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
828 ) -> Result<(), LightningError>
830 C::Target: chain::Access,
832 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
835 fn update_channel_from_unsigned_announcement_intern<C: Deref>(
836 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
837 ) -> Result<(), LightningError>
839 C::Target: chain::Access,
841 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
842 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
845 let utxo_value = match &chain_access {
847 // Tentatively accept, potentially exposing us to DoS attacks
850 &Some(ref chain_access) => {
851 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
852 Ok(TxOut { value, script_pubkey }) => {
853 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
854 .push_slice(&msg.bitcoin_key_1.serialize())
855 .push_slice(&msg.bitcoin_key_2.serialize())
856 .push_opcode(opcodes::all::OP_PUSHNUM_2)
857 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
858 if script_pubkey != expected_script {
859 return Err(LightningError{err: format!("Channel announcement key ({}) didn't match on-chain script ({})", script_pubkey.to_hex(), expected_script.to_hex()), action: ErrorAction::IgnoreError});
861 //TODO: Check if value is worth storing, use it to inform routing, and compare it
862 //to the new HTLC max field in channel_update
865 Err(chain::AccessError::UnknownChain) => {
866 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
868 Err(chain::AccessError::UnknownTx) => {
869 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
875 let chan_info = ChannelInfo {
876 features: msg.features.clone(),
877 node_one: msg.node_id_1.clone(),
879 node_two: msg.node_id_2.clone(),
881 capacity_sats: utxo_value,
882 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
883 { full_msg.cloned() } else { None },
886 let mut channels = self.channels.write().unwrap();
887 let mut nodes = self.nodes.write().unwrap();
888 match channels.entry(msg.short_channel_id) {
889 BtreeEntry::Occupied(mut entry) => {
890 //TODO: because asking the blockchain if short_channel_id is valid is only optional
891 //in the blockchain API, we need to handle it smartly here, though it's unclear
893 if utxo_value.is_some() {
894 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
895 // only sometimes returns results. In any case remove the previous entry. Note
896 // that the spec expects us to "blacklist" the node_ids involved, but we can't
898 // a) we don't *require* a UTXO provider that always returns results.
899 // b) we don't track UTXOs of channels we know about and remove them if they
901 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
902 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), msg.short_channel_id);
903 *entry.get_mut() = chan_info;
905 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)})
908 BtreeEntry::Vacant(entry) => {
909 entry.insert(chan_info);
913 macro_rules! add_channel_to_node {
914 ( $node_id: expr ) => {
915 match nodes.entry($node_id) {
916 BtreeEntry::Occupied(node_entry) => {
917 node_entry.into_mut().channels.push(msg.short_channel_id);
919 BtreeEntry::Vacant(node_entry) => {
920 node_entry.insert(NodeInfo {
921 channels: vec!(msg.short_channel_id),
922 lowest_inbound_channel_fees: None,
923 announcement_info: None,
930 add_channel_to_node!(msg.node_id_1);
931 add_channel_to_node!(msg.node_id_2);
936 /// Close a channel if a corresponding HTLC fail was sent.
937 /// If permanent, removes a channel from the local storage.
938 /// May cause the removal of nodes too, if this was their last channel.
939 /// If not permanent, makes channels unavailable for routing.
940 pub fn close_channel_from_update(&self, short_channel_id: u64, is_permanent: bool) {
941 let mut channels = self.channels.write().unwrap();
943 if let Some(chan) = channels.remove(&short_channel_id) {
944 let mut nodes = self.nodes.write().unwrap();
945 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
948 if let Some(chan) = channels.get_mut(&short_channel_id) {
949 if let Some(one_to_two) = chan.one_to_two.as_mut() {
950 one_to_two.enabled = false;
952 if let Some(two_to_one) = chan.two_to_one.as_mut() {
953 two_to_one.enabled = false;
959 /// Marks a node in the graph as failed.
960 pub fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
962 // TODO: Wholly remove the node
964 // TODO: downgrade the node
968 /// For an already known (from announcement) channel, update info about one of the directions
971 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
972 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
973 /// routing messages from a source using a protocol other than the lightning P2P protocol.
974 pub fn update_channel<T: secp256k1::Verification>(&self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
975 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
978 /// For an already known (from announcement) channel, update info about one of the directions
979 /// of the channel without verifying the associated signatures. Because we aren't given the
980 /// associated signatures here we cannot relay the channel update to any of our peers.
981 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
982 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
985 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> {
987 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
988 let chan_was_enabled;
990 let mut channels = self.channels.write().unwrap();
991 match channels.get_mut(&msg.short_channel_id) {
992 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
994 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
995 if htlc_maximum_msat > MAX_VALUE_MSAT {
996 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
999 if let Some(capacity_sats) = channel.capacity_sats {
1000 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1001 // Don't query UTXO set here to reduce DoS risks.
1002 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1003 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1007 macro_rules! maybe_update_channel_info {
1008 ( $target: expr, $src_node: expr) => {
1009 if let Some(existing_chan_info) = $target.as_ref() {
1010 if existing_chan_info.last_update >= msg.timestamp {
1011 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
1013 chan_was_enabled = existing_chan_info.enabled;
1015 chan_was_enabled = false;
1018 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1019 { full_msg.cloned() } else { None };
1021 let updated_channel_dir_info = DirectionalChannelInfo {
1022 enabled: chan_enabled,
1023 last_update: msg.timestamp,
1024 cltv_expiry_delta: msg.cltv_expiry_delta,
1025 htlc_minimum_msat: msg.htlc_minimum_msat,
1026 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1028 base_msat: msg.fee_base_msat,
1029 proportional_millionths: msg.fee_proportional_millionths,
1033 $target = Some(updated_channel_dir_info);
1037 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1038 if msg.flags & 1 == 1 {
1039 dest_node_id = channel.node_one.clone();
1040 if let Some((sig, ctx)) = sig_info {
1041 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1043 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1045 dest_node_id = channel.node_two.clone();
1046 if let Some((sig, ctx)) = sig_info {
1047 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1049 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1054 let mut nodes = self.nodes.write().unwrap();
1056 let node = nodes.get_mut(&dest_node_id).unwrap();
1057 let mut base_msat = msg.fee_base_msat;
1058 let mut proportional_millionths = msg.fee_proportional_millionths;
1059 if let Some(fees) = node.lowest_inbound_channel_fees {
1060 base_msat = cmp::min(base_msat, fees.base_msat);
1061 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1063 node.lowest_inbound_channel_fees = Some(RoutingFees {
1065 proportional_millionths
1067 } else if chan_was_enabled {
1068 let node = nodes.get_mut(&dest_node_id).unwrap();
1069 let mut lowest_inbound_channel_fees = None;
1071 for chan_id in node.channels.iter() {
1072 let chan = channels.get(chan_id).unwrap();
1074 if chan.node_one == dest_node_id {
1075 chan_info_opt = chan.two_to_one.as_ref();
1077 chan_info_opt = chan.one_to_two.as_ref();
1079 if let Some(chan_info) = chan_info_opt {
1080 if chan_info.enabled {
1081 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1082 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1083 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1084 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1089 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1095 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1096 macro_rules! remove_from_node {
1097 ($node_id: expr) => {
1098 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1099 entry.get_mut().channels.retain(|chan_id| {
1100 short_channel_id != *chan_id
1102 if entry.get().channels.is_empty() {
1103 entry.remove_entry();
1106 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1111 remove_from_node!(chan.node_one);
1112 remove_from_node!(chan.node_two);
1116 impl ReadOnlyNetworkGraph<'_> {
1117 /// Returns all known valid channels' short ids along with announced channel info.
1119 /// (C-not exported) because we have no mapping for `BTreeMap`s
1120 pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1124 /// Returns all known nodes' public keys along with announced node info.
1126 /// (C-not exported) because we have no mapping for `BTreeMap`s
1127 pub fn nodes(&self) -> &BTreeMap<PublicKey, NodeInfo> {
1131 /// Get network addresses by node id.
1132 /// Returns None if the requested node is completely unknown,
1133 /// or if node announcement for the node was never received.
1135 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
1136 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<&Vec<NetAddress>> {
1137 if let Some(node) = self.nodes.get(pubkey) {
1138 if let Some(node_info) = node.announcement_info.as_ref() {
1139 return Some(&node_info.addresses)
1149 use ln::PaymentHash;
1150 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1151 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, NetworkUpdate, MAX_EXCESS_BYTES_FOR_RELAY};
1152 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1153 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
1154 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1155 use util::test_utils;
1156 use util::logger::Logger;
1157 use util::ser::{Readable, Writeable};
1158 use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
1159 use util::scid_utils::scid_from_parts;
1161 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1162 use bitcoin::hashes::Hash;
1163 use bitcoin::network::constants::Network;
1164 use bitcoin::blockdata::constants::genesis_block;
1165 use bitcoin::blockdata::script::Builder;
1166 use bitcoin::blockdata::transaction::TxOut;
1167 use bitcoin::blockdata::opcodes;
1171 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1172 use bitcoin::secp256k1::{All, Secp256k1};
1178 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1179 let secp_ctx = Secp256k1::new();
1180 let logger = Arc::new(test_utils::TestLogger::new());
1181 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1182 let network_graph = NetworkGraph::new(genesis_hash);
1183 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1184 (secp_ctx, net_graph_msg_handler)
1188 fn request_full_sync_finite_times() {
1189 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1190 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1192 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1193 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1194 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1195 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1196 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1197 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1201 fn handling_node_announcements() {
1202 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1204 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1205 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1206 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1207 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1208 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1209 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1210 let zero_hash = Sha256dHash::hash(&[0; 32]);
1211 let first_announcement_time = 500;
1213 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1214 features: NodeFeatures::known(),
1215 timestamp: first_announcement_time,
1219 addresses: Vec::new(),
1220 excess_address_data: Vec::new(),
1221 excess_data: Vec::new(),
1223 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1224 let valid_announcement = NodeAnnouncement {
1225 signature: secp_ctx.sign(&msghash, node_1_privkey),
1226 contents: unsigned_announcement.clone()
1229 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1231 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1235 // Announce a channel to add a corresponding node.
1236 let unsigned_announcement = UnsignedChannelAnnouncement {
1237 features: ChannelFeatures::known(),
1238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1239 short_channel_id: 0,
1242 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1243 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1244 excess_data: Vec::new(),
1247 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1248 let valid_announcement = ChannelAnnouncement {
1249 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1250 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1251 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1252 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1253 contents: unsigned_announcement.clone(),
1255 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1256 Ok(res) => assert!(res),
1261 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1262 Ok(res) => assert!(res),
1266 let fake_msghash = hash_to_message!(&zero_hash);
1267 match net_graph_msg_handler.handle_node_announcement(
1269 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1270 contents: unsigned_announcement.clone()
1273 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1276 unsigned_announcement.timestamp += 1000;
1277 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1278 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1279 let announcement_with_data = NodeAnnouncement {
1280 signature: secp_ctx.sign(&msghash, node_1_privkey),
1281 contents: unsigned_announcement.clone()
1283 // Return false because contains excess data.
1284 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1285 Ok(res) => assert!(!res),
1288 unsigned_announcement.excess_data = Vec::new();
1290 // Even though previous announcement was not relayed further, we still accepted it,
1291 // so we now won't accept announcements before the previous one.
1292 unsigned_announcement.timestamp -= 10;
1293 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1294 let outdated_announcement = NodeAnnouncement {
1295 signature: secp_ctx.sign(&msghash, node_1_privkey),
1296 contents: unsigned_announcement.clone()
1298 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1300 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1305 fn handling_channel_announcements() {
1306 let secp_ctx = Secp256k1::new();
1307 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1309 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1310 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1311 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1312 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1313 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1314 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1316 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1317 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1318 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1319 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1320 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1323 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1324 features: ChannelFeatures::known(),
1325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1326 short_channel_id: 0,
1329 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1330 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1331 excess_data: Vec::new(),
1334 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1335 let valid_announcement = ChannelAnnouncement {
1336 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1337 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1338 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1339 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1340 contents: unsigned_announcement.clone(),
1343 // Test if the UTXO lookups were not supported
1344 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1345 let mut net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1346 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1347 Ok(res) => assert!(res),
1352 let network = &net_graph_msg_handler.network_graph;
1353 match network.read_only().channels().get(&unsigned_announcement.short_channel_id) {
1359 // If we receive announcement for the same channel (with UTXO lookups disabled),
1360 // drop new one on the floor, since we can't see any changes.
1361 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1363 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1366 // Test if an associated transaction were not on-chain (or not confirmed).
1367 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1368 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1369 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1370 net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1371 unsigned_announcement.short_channel_id += 1;
1373 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1374 let valid_announcement = ChannelAnnouncement {
1375 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1376 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1377 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1378 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1379 contents: unsigned_announcement.clone(),
1382 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1384 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1387 // Now test if the transaction is found in the UTXO set and the script is correct.
1388 unsigned_announcement.short_channel_id += 1;
1389 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1391 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1392 let valid_announcement = ChannelAnnouncement {
1393 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1394 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1395 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1396 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1397 contents: unsigned_announcement.clone(),
1399 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1400 Ok(res) => assert!(res),
1405 let network = &net_graph_msg_handler.network_graph;
1406 match network.read_only().channels().get(&unsigned_announcement.short_channel_id) {
1412 // If we receive announcement for the same channel (but TX is not confirmed),
1413 // drop new one on the floor, since we can't see any changes.
1414 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1415 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1417 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1420 // But if it is confirmed, replace the channel
1421 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1422 unsigned_announcement.features = ChannelFeatures::empty();
1423 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1424 let valid_announcement = ChannelAnnouncement {
1425 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1426 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1427 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1428 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1429 contents: unsigned_announcement.clone(),
1431 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1432 Ok(res) => assert!(res),
1436 let network = &net_graph_msg_handler.network_graph;
1437 match network.read_only().channels().get(&unsigned_announcement.short_channel_id) {
1438 Some(channel_entry) => {
1439 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1445 // Don't relay valid channels with excess data
1446 unsigned_announcement.short_channel_id += 1;
1447 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1448 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1449 let valid_announcement = ChannelAnnouncement {
1450 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1451 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1452 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1453 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1454 contents: unsigned_announcement.clone(),
1456 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1457 Ok(res) => assert!(!res),
1461 unsigned_announcement.excess_data = Vec::new();
1462 let invalid_sig_announcement = ChannelAnnouncement {
1463 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1464 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1465 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1466 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1467 contents: unsigned_announcement.clone(),
1469 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1471 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1474 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1475 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1476 let channel_to_itself_announcement = ChannelAnnouncement {
1477 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1478 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1479 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1480 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1481 contents: unsigned_announcement.clone(),
1483 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1485 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1490 fn handling_channel_update() {
1491 let secp_ctx = Secp256k1::new();
1492 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1493 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1494 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1495 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1497 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1498 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1499 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1500 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1501 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1502 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1504 let zero_hash = Sha256dHash::hash(&[0; 32]);
1505 let short_channel_id = 0;
1506 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1507 let amount_sats = 1000_000;
1510 // Announce a channel we will update
1511 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1512 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1513 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1514 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1515 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1516 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1517 let unsigned_announcement = UnsignedChannelAnnouncement {
1518 features: ChannelFeatures::empty(),
1523 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1524 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1525 excess_data: Vec::new(),
1528 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1529 let valid_channel_announcement = ChannelAnnouncement {
1530 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1531 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1532 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1533 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1534 contents: unsigned_announcement.clone(),
1536 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1543 let mut unsigned_channel_update = UnsignedChannelUpdate {
1548 cltv_expiry_delta: 144,
1549 htlc_minimum_msat: 1000000,
1550 htlc_maximum_msat: OptionalField::Absent,
1551 fee_base_msat: 10000,
1552 fee_proportional_millionths: 20,
1553 excess_data: Vec::new()
1555 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1556 let valid_channel_update = ChannelUpdate {
1557 signature: secp_ctx.sign(&msghash, node_1_privkey),
1558 contents: unsigned_channel_update.clone()
1561 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1562 Ok(res) => assert!(res),
1567 let network = &net_graph_msg_handler.network_graph;
1568 match network.read_only().channels().get(&short_channel_id) {
1570 Some(channel_info) => {
1571 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1572 assert!(channel_info.two_to_one.is_none());
1577 unsigned_channel_update.timestamp += 100;
1578 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1579 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1580 let valid_channel_update = ChannelUpdate {
1581 signature: secp_ctx.sign(&msghash, node_1_privkey),
1582 contents: unsigned_channel_update.clone()
1584 // Return false because contains excess data
1585 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1586 Ok(res) => assert!(!res),
1589 unsigned_channel_update.timestamp += 10;
1591 unsigned_channel_update.short_channel_id += 1;
1592 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1593 let valid_channel_update = ChannelUpdate {
1594 signature: secp_ctx.sign(&msghash, node_1_privkey),
1595 contents: unsigned_channel_update.clone()
1598 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1600 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1602 unsigned_channel_update.short_channel_id = short_channel_id;
1604 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1605 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1606 let valid_channel_update = ChannelUpdate {
1607 signature: secp_ctx.sign(&msghash, node_1_privkey),
1608 contents: unsigned_channel_update.clone()
1611 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1613 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1615 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1617 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1618 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1619 let valid_channel_update = ChannelUpdate {
1620 signature: secp_ctx.sign(&msghash, node_1_privkey),
1621 contents: unsigned_channel_update.clone()
1624 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1626 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1628 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1630 // Even though previous update was not relayed further, we still accepted it,
1631 // so we now won't accept update before the previous one.
1632 unsigned_channel_update.timestamp -= 10;
1633 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1634 let valid_channel_update = ChannelUpdate {
1635 signature: secp_ctx.sign(&msghash, node_1_privkey),
1636 contents: unsigned_channel_update.clone()
1639 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1641 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1643 unsigned_channel_update.timestamp += 500;
1645 let fake_msghash = hash_to_message!(&zero_hash);
1646 let invalid_sig_channel_update = ChannelUpdate {
1647 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1648 contents: unsigned_channel_update.clone()
1651 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1653 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1659 fn handling_network_update() {
1660 let logger = test_utils::TestLogger::new();
1661 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1662 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1663 let network_graph = NetworkGraph::new(genesis_hash);
1664 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, Some(chain_source.clone()), &logger);
1665 let secp_ctx = Secp256k1::new();
1667 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1668 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1669 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1670 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1671 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1672 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1674 let short_channel_id = 0;
1675 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1676 let network_graph = &net_graph_msg_handler.network_graph;
1679 // There is no nodes in the table at the beginning.
1680 assert_eq!(network_graph.read_only().nodes().len(), 0);
1684 // Announce a channel we will update
1685 let unsigned_announcement = UnsignedChannelAnnouncement {
1686 features: ChannelFeatures::empty(),
1691 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1692 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1693 excess_data: Vec::new(),
1696 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1697 let valid_channel_announcement = ChannelAnnouncement {
1698 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1699 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1700 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1701 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1702 contents: unsigned_announcement.clone(),
1704 let chain_source: Option<&test_utils::TestChainSource> = None;
1705 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
1706 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
1708 let unsigned_channel_update = UnsignedChannelUpdate {
1713 cltv_expiry_delta: 144,
1714 htlc_minimum_msat: 1000000,
1715 htlc_maximum_msat: OptionalField::Absent,
1716 fee_base_msat: 10000,
1717 fee_proportional_millionths: 20,
1718 excess_data: Vec::new()
1720 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1721 let valid_channel_update = ChannelUpdate {
1722 signature: secp_ctx.sign(&msghash, node_1_privkey),
1723 contents: unsigned_channel_update.clone()
1726 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
1728 net_graph_msg_handler.handle_event(&Event::PaymentFailed {
1729 payment_hash: PaymentHash([0; 32]),
1730 rejected_by_dest: false,
1731 network_update: Some(NetworkUpdate::ChannelUpdateMessage {
1732 msg: valid_channel_update,
1738 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
1741 // Non-permanent closing just disables a channel
1743 match network_graph.read_only().channels().get(&short_channel_id) {
1745 Some(channel_info) => {
1746 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
1750 net_graph_msg_handler.handle_event(&Event::PaymentFailed {
1751 payment_hash: PaymentHash([0; 32]),
1752 rejected_by_dest: false,
1753 network_update: Some(NetworkUpdate::ChannelClosed {
1755 is_permanent: false,
1761 match network_graph.read_only().channels().get(&short_channel_id) {
1763 Some(channel_info) => {
1764 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1769 // Permanent closing deletes a channel
1771 net_graph_msg_handler.handle_event(&Event::PaymentFailed {
1772 payment_hash: PaymentHash([0; 32]),
1773 rejected_by_dest: false,
1774 network_update: Some(NetworkUpdate::ChannelClosed {
1782 assert_eq!(network_graph.read_only().channels().len(), 0);
1783 // Nodes are also deleted because there are no associated channels anymore
1784 assert_eq!(network_graph.read_only().nodes().len(), 0);
1786 // TODO: Test NetworkUpdate::NodeFailure, which is not implemented yet.
1790 fn getting_next_channel_announcements() {
1791 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1792 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1793 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1794 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1795 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1796 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1797 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1799 let short_channel_id = 1;
1800 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1802 // Channels were not announced yet.
1803 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1804 assert_eq!(channels_with_announcements.len(), 0);
1807 // Announce a channel we will update
1808 let unsigned_announcement = UnsignedChannelAnnouncement {
1809 features: ChannelFeatures::empty(),
1814 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1815 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1816 excess_data: Vec::new(),
1819 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1820 let valid_channel_announcement = ChannelAnnouncement {
1821 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1822 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1823 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1824 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1825 contents: unsigned_announcement.clone(),
1827 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1833 // Contains initial channel announcement now.
1834 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1835 assert_eq!(channels_with_announcements.len(), 1);
1836 if let Some(channel_announcements) = channels_with_announcements.first() {
1837 let &(_, ref update_1, ref update_2) = channel_announcements;
1838 assert_eq!(update_1, &None);
1839 assert_eq!(update_2, &None);
1846 // Valid channel update
1847 let unsigned_channel_update = UnsignedChannelUpdate {
1852 cltv_expiry_delta: 144,
1853 htlc_minimum_msat: 1000000,
1854 htlc_maximum_msat: OptionalField::Absent,
1855 fee_base_msat: 10000,
1856 fee_proportional_millionths: 20,
1857 excess_data: Vec::new()
1859 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1860 let valid_channel_update = ChannelUpdate {
1861 signature: secp_ctx.sign(&msghash, node_1_privkey),
1862 contents: unsigned_channel_update.clone()
1864 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1870 // Now contains an initial announcement and an update.
1871 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1872 assert_eq!(channels_with_announcements.len(), 1);
1873 if let Some(channel_announcements) = channels_with_announcements.first() {
1874 let &(_, ref update_1, ref update_2) = channel_announcements;
1875 assert_ne!(update_1, &None);
1876 assert_eq!(update_2, &None);
1883 // Channel update with excess data.
1884 let unsigned_channel_update = UnsignedChannelUpdate {
1889 cltv_expiry_delta: 144,
1890 htlc_minimum_msat: 1000000,
1891 htlc_maximum_msat: OptionalField::Absent,
1892 fee_base_msat: 10000,
1893 fee_proportional_millionths: 20,
1894 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1896 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1897 let valid_channel_update = ChannelUpdate {
1898 signature: secp_ctx.sign(&msghash, node_1_privkey),
1899 contents: unsigned_channel_update.clone()
1901 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1907 // Test that announcements with excess data won't be returned
1908 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1909 assert_eq!(channels_with_announcements.len(), 1);
1910 if let Some(channel_announcements) = channels_with_announcements.first() {
1911 let &(_, ref update_1, ref update_2) = channel_announcements;
1912 assert_eq!(update_1, &None);
1913 assert_eq!(update_2, &None);
1918 // Further starting point have no channels after it
1919 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1920 assert_eq!(channels_with_announcements.len(), 0);
1924 fn getting_next_node_announcements() {
1925 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1926 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1927 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1928 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1929 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1930 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1931 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1933 let short_channel_id = 1;
1934 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1937 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1938 assert_eq!(next_announcements.len(), 0);
1941 // Announce a channel to add 2 nodes
1942 let unsigned_announcement = UnsignedChannelAnnouncement {
1943 features: ChannelFeatures::empty(),
1948 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1949 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1950 excess_data: Vec::new(),
1953 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1954 let valid_channel_announcement = ChannelAnnouncement {
1955 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1956 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1957 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1958 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1959 contents: unsigned_announcement.clone(),
1961 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1968 // Nodes were never announced
1969 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1970 assert_eq!(next_announcements.len(), 0);
1973 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1974 features: NodeFeatures::known(),
1979 addresses: Vec::new(),
1980 excess_address_data: Vec::new(),
1981 excess_data: Vec::new(),
1983 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1984 let valid_announcement = NodeAnnouncement {
1985 signature: secp_ctx.sign(&msghash, node_1_privkey),
1986 contents: unsigned_announcement.clone()
1988 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1993 unsigned_announcement.node_id = node_id_2;
1994 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1995 let valid_announcement = NodeAnnouncement {
1996 signature: secp_ctx.sign(&msghash, node_2_privkey),
1997 contents: unsigned_announcement.clone()
2000 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2006 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2007 assert_eq!(next_announcements.len(), 2);
2009 // Skip the first node.
2010 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2011 assert_eq!(next_announcements.len(), 1);
2014 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2015 let unsigned_announcement = UnsignedNodeAnnouncement {
2016 features: NodeFeatures::known(),
2021 addresses: Vec::new(),
2022 excess_address_data: Vec::new(),
2023 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
2025 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2026 let valid_announcement = NodeAnnouncement {
2027 signature: secp_ctx.sign(&msghash, node_2_privkey),
2028 contents: unsigned_announcement.clone()
2030 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2031 Ok(res) => assert!(!res),
2036 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2037 assert_eq!(next_announcements.len(), 0);
2041 fn network_graph_serialization() {
2042 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2044 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2045 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2046 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2047 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2049 // Announce a channel to add a corresponding node.
2050 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2051 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2052 let unsigned_announcement = UnsignedChannelAnnouncement {
2053 features: ChannelFeatures::known(),
2054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2055 short_channel_id: 0,
2058 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2059 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2060 excess_data: Vec::new(),
2063 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2064 let valid_announcement = ChannelAnnouncement {
2065 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2066 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2067 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2068 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2069 contents: unsigned_announcement.clone(),
2071 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2072 Ok(res) => assert!(res),
2077 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2078 let unsigned_announcement = UnsignedNodeAnnouncement {
2079 features: NodeFeatures::known(),
2084 addresses: Vec::new(),
2085 excess_address_data: Vec::new(),
2086 excess_data: Vec::new(),
2088 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2089 let valid_announcement = NodeAnnouncement {
2090 signature: secp_ctx.sign(&msghash, node_1_privkey),
2091 contents: unsigned_announcement.clone()
2094 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2099 let network = &net_graph_msg_handler.network_graph;
2100 let mut w = test_utils::TestVecWriter(Vec::new());
2101 assert!(!network.read_only().nodes().is_empty());
2102 assert!(!network.read_only().channels().is_empty());
2103 network.write(&mut w).unwrap();
2104 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == *network);
2108 fn calling_sync_routing_table() {
2109 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2110 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2111 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2113 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2114 let first_blocknum = 0;
2115 let number_of_blocks = 0xffff_ffff;
2117 // It should ignore if gossip_queries feature is not enabled
2119 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2120 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2121 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2122 assert_eq!(events.len(), 0);
2125 // It should send a query_channel_message with the correct information
2127 let init_msg = Init { features: InitFeatures::known() };
2128 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2129 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2130 assert_eq!(events.len(), 1);
2132 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2133 assert_eq!(node_id, &node_id_1);
2134 assert_eq!(msg.chain_hash, chain_hash);
2135 assert_eq!(msg.first_blocknum, first_blocknum);
2136 assert_eq!(msg.number_of_blocks, number_of_blocks);
2138 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2142 // It should not enqueue a query when should_request_full_sync return false.
2143 // The initial implementation allows syncing with the first 5 peers after
2144 // which should_request_full_sync will return false
2146 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2147 let init_msg = Init { features: InitFeatures::known() };
2149 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2150 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2151 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2152 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2154 assert_eq!(events.len(), 1);
2156 assert_eq!(events.len(), 0);
2164 fn handling_reply_channel_range() {
2165 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2166 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2167 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2169 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2171 // Test receipt of a single reply that should enqueue an SCID query
2172 // matching the SCIDs in the reply
2174 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2176 sync_complete: true,
2178 number_of_blocks: 2000,
2179 short_channel_ids: vec![
2180 0x0003e0_000000_0000, // 992x0x0
2181 0x0003e8_000000_0000, // 1000x0x0
2182 0x0003e9_000000_0000, // 1001x0x0
2183 0x0003f0_000000_0000, // 1008x0x0
2184 0x00044c_000000_0000, // 1100x0x0
2185 0x0006e0_000000_0000, // 1760x0x0
2188 assert!(result.is_ok());
2190 // We expect to emit a query_short_channel_ids message with the received scids
2191 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2192 assert_eq!(events.len(), 1);
2194 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2195 assert_eq!(node_id, &node_id_1);
2196 assert_eq!(msg.chain_hash, chain_hash);
2197 assert_eq!(msg.short_channel_ids, vec![
2198 0x0003e0_000000_0000, // 992x0x0
2199 0x0003e8_000000_0000, // 1000x0x0
2200 0x0003e9_000000_0000, // 1001x0x0
2201 0x0003f0_000000_0000, // 1008x0x0
2202 0x00044c_000000_0000, // 1100x0x0
2203 0x0006e0_000000_0000, // 1760x0x0
2206 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2212 fn handling_reply_short_channel_ids() {
2213 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2214 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2215 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2217 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2219 // Test receipt of a successful reply
2221 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2223 full_information: true,
2225 assert!(result.is_ok());
2228 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2229 // for the chain_hash requested in the query.
2231 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2233 full_information: false,
2235 assert!(result.is_err());
2236 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2241 fn handling_query_channel_range() {
2242 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2244 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2245 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2246 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2247 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2248 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2249 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2250 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2251 let bitcoin_key_1 = PublicKey::from_secret_key(&secp_ctx, node_1_btckey);
2252 let bitcoin_key_2 = PublicKey::from_secret_key(&secp_ctx, node_2_btckey);
2254 let mut scids: Vec<u64> = vec![
2255 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2256 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2259 // used for testing multipart reply across blocks
2260 for block in 100000..=108001 {
2261 scids.push(scid_from_parts(block, 0, 0).unwrap());
2264 // used for testing resumption on same block
2265 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2268 let unsigned_announcement = UnsignedChannelAnnouncement {
2269 features: ChannelFeatures::known(),
2270 chain_hash: chain_hash.clone(),
2271 short_channel_id: scid,
2276 excess_data: Vec::new(),
2279 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2280 let valid_announcement = ChannelAnnouncement {
2281 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2282 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2283 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2284 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2285 contents: unsigned_announcement.clone(),
2287 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2293 // Error when number_of_blocks=0
2294 do_handling_query_channel_range(
2295 &net_graph_msg_handler,
2298 chain_hash: chain_hash.clone(),
2300 number_of_blocks: 0,
2303 vec![ReplyChannelRange {
2304 chain_hash: chain_hash.clone(),
2306 number_of_blocks: 0,
2307 sync_complete: true,
2308 short_channel_ids: vec![]
2312 // Error when wrong chain
2313 do_handling_query_channel_range(
2314 &net_graph_msg_handler,
2317 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2319 number_of_blocks: 0xffff_ffff,
2322 vec![ReplyChannelRange {
2323 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2325 number_of_blocks: 0xffff_ffff,
2326 sync_complete: true,
2327 short_channel_ids: vec![],
2331 // Error when first_blocknum > 0xffffff
2332 do_handling_query_channel_range(
2333 &net_graph_msg_handler,
2336 chain_hash: chain_hash.clone(),
2337 first_blocknum: 0x01000000,
2338 number_of_blocks: 0xffff_ffff,
2341 vec![ReplyChannelRange {
2342 chain_hash: chain_hash.clone(),
2343 first_blocknum: 0x01000000,
2344 number_of_blocks: 0xffff_ffff,
2345 sync_complete: true,
2346 short_channel_ids: vec![]
2350 // Empty reply when max valid SCID block num
2351 do_handling_query_channel_range(
2352 &net_graph_msg_handler,
2355 chain_hash: chain_hash.clone(),
2356 first_blocknum: 0xffffff,
2357 number_of_blocks: 1,
2362 chain_hash: chain_hash.clone(),
2363 first_blocknum: 0xffffff,
2364 number_of_blocks: 1,
2365 sync_complete: true,
2366 short_channel_ids: vec![]
2371 // No results in valid query range
2372 do_handling_query_channel_range(
2373 &net_graph_msg_handler,
2376 chain_hash: chain_hash.clone(),
2377 first_blocknum: 1000,
2378 number_of_blocks: 1000,
2383 chain_hash: chain_hash.clone(),
2384 first_blocknum: 1000,
2385 number_of_blocks: 1000,
2386 sync_complete: true,
2387 short_channel_ids: vec![],
2392 // Overflow first_blocknum + number_of_blocks
2393 do_handling_query_channel_range(
2394 &net_graph_msg_handler,
2397 chain_hash: chain_hash.clone(),
2398 first_blocknum: 0xfe0000,
2399 number_of_blocks: 0xffffffff,
2404 chain_hash: chain_hash.clone(),
2405 first_blocknum: 0xfe0000,
2406 number_of_blocks: 0xffffffff - 0xfe0000,
2407 sync_complete: true,
2408 short_channel_ids: vec![
2409 0xfffffe_ffffff_ffff, // max
2415 // Single block exactly full
2416 do_handling_query_channel_range(
2417 &net_graph_msg_handler,
2420 chain_hash: chain_hash.clone(),
2421 first_blocknum: 100000,
2422 number_of_blocks: 8000,
2427 chain_hash: chain_hash.clone(),
2428 first_blocknum: 100000,
2429 number_of_blocks: 8000,
2430 sync_complete: true,
2431 short_channel_ids: (100000..=107999)
2432 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2438 // Multiple split on new block
2439 do_handling_query_channel_range(
2440 &net_graph_msg_handler,
2443 chain_hash: chain_hash.clone(),
2444 first_blocknum: 100000,
2445 number_of_blocks: 8001,
2450 chain_hash: chain_hash.clone(),
2451 first_blocknum: 100000,
2452 number_of_blocks: 7999,
2453 sync_complete: false,
2454 short_channel_ids: (100000..=107999)
2455 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2459 chain_hash: chain_hash.clone(),
2460 first_blocknum: 107999,
2461 number_of_blocks: 2,
2462 sync_complete: true,
2463 short_channel_ids: vec![
2464 scid_from_parts(108000, 0, 0).unwrap(),
2470 // Multiple split on same block
2471 do_handling_query_channel_range(
2472 &net_graph_msg_handler,
2475 chain_hash: chain_hash.clone(),
2476 first_blocknum: 100002,
2477 number_of_blocks: 8000,
2482 chain_hash: chain_hash.clone(),
2483 first_blocknum: 100002,
2484 number_of_blocks: 7999,
2485 sync_complete: false,
2486 short_channel_ids: (100002..=108001)
2487 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2491 chain_hash: chain_hash.clone(),
2492 first_blocknum: 108001,
2493 number_of_blocks: 1,
2494 sync_complete: true,
2495 short_channel_ids: vec![
2496 scid_from_parts(108001, 1, 0).unwrap(),
2503 fn do_handling_query_channel_range(
2504 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2505 test_node_id: &PublicKey,
2506 msg: QueryChannelRange,
2508 expected_replies: Vec<ReplyChannelRange>
2510 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2511 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2512 let query_end_blocknum = msg.end_blocknum();
2513 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2516 assert!(result.is_ok());
2518 assert!(result.is_err());
2521 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2522 assert_eq!(events.len(), expected_replies.len());
2524 for i in 0..events.len() {
2525 let expected_reply = &expected_replies[i];
2527 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2528 assert_eq!(node_id, test_node_id);
2529 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2530 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2531 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2532 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2533 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2535 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2536 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2537 assert!(msg.first_blocknum >= max_firstblocknum);
2538 max_firstblocknum = msg.first_blocknum;
2539 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2541 // Check that the last block count is >= the query's end_blocknum
2542 if i == events.len() - 1 {
2543 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2546 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2552 fn handling_query_short_channel_ids() {
2553 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2554 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2555 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2557 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2559 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2561 short_channel_ids: vec![0x0003e8_000000_0000],
2563 assert!(result.is_err());
2567 #[cfg(all(test, feature = "unstable"))]
2575 fn read_network_graph(bench: &mut Bencher) {
2576 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2577 let mut v = Vec::new();
2578 d.read_to_end(&mut v).unwrap();
2580 let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2585 fn write_network_graph(bench: &mut Bencher) {
2586 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2587 let net_graph = NetworkGraph::read(&mut d).unwrap();
2589 let _ = net_graph.encode();