1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level network map tracking logic lives here.
12 use bitcoin::secp256k1::key::PublicKey;
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::secp256k1;
16 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
17 use bitcoin::hashes::Hash;
18 use bitcoin::blockdata::script::Builder;
19 use bitcoin::blockdata::transaction::TxOut;
20 use bitcoin::blockdata::opcodes;
21 use bitcoin::hash_types::BlockHash;
25 use ln::features::{ChannelFeatures, NodeFeatures};
26 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
27 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
28 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use util::ser::{Writeable, Readable, Writer};
31 use util::logger::{Logger, Level};
32 use util::events::{MessageSendEvent, MessageSendEventsProvider};
33 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
37 use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
39 use sync::{RwLock, RwLockReadGuard};
40 use core::sync::atomic::{AtomicUsize, Ordering};
43 use bitcoin::hashes::hex::ToHex;
45 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
46 /// refuse to relay the message.
47 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
49 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
50 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
51 const MAX_SCIDS_PER_REPLY: usize = 8000;
53 /// Represents the network as nodes and channels between them
54 pub struct NetworkGraph {
55 genesis_hash: BlockHash,
56 // Lock order: channels -> nodes
57 channels: RwLock<BTreeMap<u64, ChannelInfo>>,
58 nodes: RwLock<BTreeMap<PublicKey, NodeInfo>>,
61 /// A read-only view of [`NetworkGraph`].
62 pub struct ReadOnlyNetworkGraph<'a> {
63 channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
64 nodes: RwLockReadGuard<'a, BTreeMap<PublicKey, NodeInfo>>,
67 /// 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 /// Receives and validates network updates from peers,
114 /// stores authentic and relevant data as a network graph.
115 /// This network graph is then used for routing payments.
116 /// Provides interface to help with initial routing sync by
117 /// serving historical announcements.
118 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
119 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
120 /// Representation of the payment channel network
121 pub network_graph: NetworkGraph,
122 chain_access: Option<C>,
123 full_syncs_requested: AtomicUsize,
124 pending_events: Mutex<Vec<MessageSendEvent>>,
128 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
129 /// Creates a new tracker of the actual state of the network of channels and nodes,
130 /// assuming a fresh network graph.
131 /// Chain monitor is used to make sure announced channels exist on-chain,
132 /// channel data is correct, and that the announcement is signed with
133 /// channel owners' keys.
134 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
136 secp_ctx: Secp256k1::verification_only(),
137 network_graph: NetworkGraph::new(genesis_hash),
138 full_syncs_requested: AtomicUsize::new(0),
140 pending_events: Mutex::new(vec![]),
145 /// Creates a new tracker of the actual state of the network of channels and nodes,
146 /// assuming an existing Network Graph.
147 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
149 secp_ctx: Secp256k1::verification_only(),
151 full_syncs_requested: AtomicUsize::new(0),
153 pending_events: Mutex::new(vec![]),
158 /// Adds a provider used to check new announcements. Does not affect
159 /// existing announcements unless they are updated.
160 /// Add, update or remove the provider would replace the current one.
161 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
162 self.chain_access = chain_access;
165 /// Returns true when a full routing table sync should be performed with a peer.
166 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
167 //TODO: Determine whether to request a full sync based on the network map.
168 const FULL_SYNCS_TO_REQUEST: usize = 5;
169 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
170 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
178 macro_rules! secp_verify_sig {
179 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
180 match $secp_ctx.verify($msg, $sig, $pubkey) {
182 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
187 impl<C: Deref , L: Deref > RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
188 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
189 self.network_graph.update_node_from_announcement(msg, &self.secp_ctx)?;
190 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
191 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
192 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
195 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
196 self.network_graph.update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
197 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 { "" });
198 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
201 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
202 self.network_graph.update_channel(msg, &self.secp_ctx)?;
203 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
206 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
207 let mut result = Vec::with_capacity(batch_amount as usize);
208 let channels = self.network_graph.channels.read().unwrap();
209 let mut iter = channels.range(starting_point..);
210 while result.len() < batch_amount as usize {
211 if let Some((_, ref chan)) = iter.next() {
212 if chan.announcement_message.is_some() {
213 let chan_announcement = chan.announcement_message.clone().unwrap();
214 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
215 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
216 if let Some(one_to_two) = chan.one_to_two.as_ref() {
217 one_to_two_announcement = one_to_two.last_update_message.clone();
219 if let Some(two_to_one) = chan.two_to_one.as_ref() {
220 two_to_one_announcement = two_to_one.last_update_message.clone();
222 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
224 // TODO: We may end up sending un-announced channel_updates if we are sending
225 // initial sync data while receiving announce/updates for this channel.
234 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
235 let mut result = Vec::with_capacity(batch_amount as usize);
236 let nodes = self.network_graph.nodes.read().unwrap();
237 let mut iter = if let Some(pubkey) = starting_point {
238 let mut iter = nodes.range((*pubkey)..);
244 while result.len() < batch_amount as usize {
245 if let Some((_, ref node)) = iter.next() {
246 if let Some(node_info) = node.announcement_info.as_ref() {
247 if node_info.announcement_message.is_some() {
248 result.push(node_info.announcement_message.clone().unwrap());
258 /// Initiates a stateless sync of routing gossip information with a peer
259 /// using gossip_queries. The default strategy used by this implementation
260 /// is to sync the full block range with several peers.
262 /// We should expect one or more reply_channel_range messages in response
263 /// to our query_channel_range. Each reply will enqueue a query_scid message
264 /// to request gossip messages for each channel. The sync is considered complete
265 /// when the final reply_scids_end message is received, though we are not
266 /// tracking this directly.
267 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
269 // We will only perform a sync with peers that support gossip_queries.
270 if !init_msg.features.supports_gossip_queries() {
274 // Check if we need to perform a full synchronization with this peer
275 if !self.should_request_full_sync(their_node_id) {
279 let first_blocknum = 0;
280 let number_of_blocks = 0xffffffff;
281 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
282 let mut pending_events = self.pending_events.lock().unwrap();
283 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
284 node_id: their_node_id.clone(),
285 msg: QueryChannelRange {
286 chain_hash: self.network_graph.genesis_hash,
293 /// Statelessly processes a reply to a channel range query by immediately
294 /// sending an SCID query with SCIDs in the reply. To keep this handler
295 /// stateless, it does not validate the sequencing of replies for multi-
296 /// reply ranges. It does not validate whether the reply(ies) cover the
297 /// queried range. It also does not filter SCIDs to only those in the
298 /// original query range. We also do not validate that the chain_hash
299 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
300 /// does not match our chain_hash will be rejected when the announcement is
302 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
303 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(),);
305 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
306 let mut pending_events = self.pending_events.lock().unwrap();
307 pending_events.push(MessageSendEvent::SendShortIdsQuery {
308 node_id: their_node_id.clone(),
309 msg: QueryShortChannelIds {
310 chain_hash: msg.chain_hash,
311 short_channel_ids: msg.short_channel_ids,
318 /// When an SCID query is initiated the remote peer will begin streaming
319 /// gossip messages. In the event of a failure, we may have received
320 /// some channel information. Before trying with another peer, the
321 /// caller should update its set of SCIDs that need to be queried.
322 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
323 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
325 // If the remote node does not have up-to-date information for the
326 // chain_hash they will set full_information=false. We can fail
327 // the result and try again with a different peer.
328 if !msg.full_information {
329 return Err(LightningError {
330 err: String::from("Received reply_short_channel_ids_end with no information"),
331 action: ErrorAction::IgnoreError
338 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
339 /// are in the specified block range. Due to message size limits, large range
340 /// queries may result in several reply messages. This implementation enqueues
341 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
342 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
343 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
344 /// memory constrained systems.
345 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
346 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);
348 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
350 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
351 // If so, we manually cap the ending block to avoid this overflow.
352 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
354 // Per spec, we must reply to a query. Send an empty message when things are invalid.
355 if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
356 let mut pending_events = self.pending_events.lock().unwrap();
357 pending_events.push(MessageSendEvent::SendReplyChannelRange {
358 node_id: their_node_id.clone(),
359 msg: ReplyChannelRange {
360 chain_hash: msg.chain_hash.clone(),
361 first_blocknum: msg.first_blocknum,
362 number_of_blocks: msg.number_of_blocks,
364 short_channel_ids: vec![],
367 return Err(LightningError {
368 err: String::from("query_channel_range could not be processed"),
369 action: ErrorAction::IgnoreError,
373 // Creates channel batches. We are not checking if the channel is routable
374 // (has at least one update). A peer may still want to know the channel
375 // exists even if its not yet routable.
376 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
377 let channels = self.network_graph.channels.read().unwrap();
378 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
379 if let Some(chan_announcement) = &chan.announcement_message {
380 // Construct a new batch if last one is full
381 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
382 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
385 let batch = batches.last_mut().unwrap();
386 batch.push(chan_announcement.contents.short_channel_id);
391 let mut pending_events = self.pending_events.lock().unwrap();
392 let batch_count = batches.len();
393 let mut prev_batch_endblock = msg.first_blocknum;
394 for (batch_index, batch) in batches.into_iter().enumerate() {
395 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
396 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
398 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
399 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
400 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
401 // significant diversion from the requirements set by the spec, and, in case of blocks
402 // with no channel opens (e.g. empty blocks), requires that we use the previous value
403 // and *not* derive the first_blocknum from the actual first block of the reply.
404 let first_blocknum = prev_batch_endblock;
406 // Each message carries the number of blocks (from the `first_blocknum`) its contents
407 // fit in. Though there is no requirement that we use exactly the number of blocks its
408 // contents are from, except for the bogus requirements c-lightning enforces, above.
410 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
411 // >= the query's end block. Thus, for the last reply, we calculate the difference
412 // between the query's end block and the start of the reply.
414 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
415 // first_blocknum will be either msg.first_blocknum or a higher block height.
416 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
417 (true, msg.end_blocknum() - first_blocknum)
419 // Prior replies should use the number of blocks that fit into the reply. Overflow
420 // safe since first_blocknum is always <= last SCID's block.
422 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
425 prev_batch_endblock = first_blocknum + number_of_blocks;
427 pending_events.push(MessageSendEvent::SendReplyChannelRange {
428 node_id: their_node_id.clone(),
429 msg: ReplyChannelRange {
430 chain_hash: msg.chain_hash.clone(),
434 short_channel_ids: batch,
442 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
445 err: String::from("Not implemented"),
446 action: ErrorAction::IgnoreError,
451 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
453 C::Target: chain::Access,
456 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
457 let mut ret = Vec::new();
458 let mut pending_events = self.pending_events.lock().unwrap();
459 core::mem::swap(&mut ret, &mut pending_events);
464 #[derive(Clone, Debug, PartialEq)]
465 /// Details about one direction of a channel. Received
466 /// within a channel update.
467 pub struct DirectionalChannelInfo {
468 /// When the last update to the channel direction was issued.
469 /// Value is opaque, as set in the announcement.
470 pub last_update: u32,
471 /// Whether the channel can be currently used for payments (in this one direction).
473 /// The difference in CLTV values that you must have when routing through this channel.
474 pub cltv_expiry_delta: u16,
475 /// The minimum value, which must be relayed to the next hop via the channel
476 pub htlc_minimum_msat: u64,
477 /// The maximum value which may be relayed to the next hop via the channel.
478 pub htlc_maximum_msat: Option<u64>,
479 /// Fees charged when the channel is used for routing
480 pub fees: RoutingFees,
481 /// Most recent update for the channel received from the network
482 /// Mostly redundant with the data we store in fields explicitly.
483 /// Everything else is useful only for sending out for initial routing sync.
484 /// Not stored if contains excess data to prevent DoS.
485 pub last_update_message: Option<ChannelUpdate>,
488 impl fmt::Display for DirectionalChannelInfo {
489 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
490 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)?;
495 impl_writeable_tlv_based!(DirectionalChannelInfo, {
496 (0, last_update, required),
497 (2, enabled, required),
498 (4, cltv_expiry_delta, required),
499 (6, htlc_minimum_msat, required),
500 (8, htlc_maximum_msat, required),
501 (10, fees, required),
502 (12, last_update_message, required),
505 #[derive(Clone, Debug, PartialEq)]
506 /// Details about a channel (both directions).
507 /// Received within a channel announcement.
508 pub struct ChannelInfo {
509 /// Protocol features of a channel communicated during its announcement
510 pub features: ChannelFeatures,
511 /// Source node of the first direction of a channel
512 pub node_one: PublicKey,
513 /// Details about the first direction of a channel
514 pub one_to_two: Option<DirectionalChannelInfo>,
515 /// Source node of the second direction of a channel
516 pub node_two: PublicKey,
517 /// Details about the second direction of a channel
518 pub two_to_one: Option<DirectionalChannelInfo>,
519 /// The channel capacity as seen on-chain, if chain lookup is available.
520 pub capacity_sats: Option<u64>,
521 /// An initial announcement of the channel
522 /// Mostly redundant with the data we store in fields explicitly.
523 /// Everything else is useful only for sending out for initial routing sync.
524 /// Not stored if contains excess data to prevent DoS.
525 pub announcement_message: Option<ChannelAnnouncement>,
528 impl fmt::Display for ChannelInfo {
529 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
530 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
531 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
536 impl_writeable_tlv_based!(ChannelInfo, {
537 (0, features, required),
538 (2, node_one, required),
539 (4, one_to_two, required),
540 (6, node_two, required),
541 (8, two_to_one, required),
542 (10, capacity_sats, required),
543 (12, announcement_message, required),
547 /// Fees for routing via a given channel or a node
548 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
549 pub struct RoutingFees {
550 /// Flat routing fee in satoshis
552 /// Liquidity-based routing fee in millionths of a routed amount.
553 /// In other words, 10000 is 1%.
554 pub proportional_millionths: u32,
557 impl_writeable_tlv_based!(RoutingFees, {
558 (0, base_msat, required),
559 (2, proportional_millionths, required)
562 #[derive(Clone, Debug, PartialEq)]
563 /// Information received in the latest node_announcement from this node.
564 pub struct NodeAnnouncementInfo {
565 /// Protocol features the node announced support for
566 pub features: NodeFeatures,
567 /// When the last known update to the node state was issued.
568 /// Value is opaque, as set in the announcement.
569 pub last_update: u32,
570 /// Color assigned to the node
572 /// Moniker assigned to the node.
573 /// May be invalid or malicious (eg control chars),
574 /// should not be exposed to the user.
576 /// Internet-level addresses via which one can connect to the node
577 pub addresses: Vec<NetAddress>,
578 /// An initial announcement of the node
579 /// Mostly redundant with the data we store in fields explicitly.
580 /// Everything else is useful only for sending out for initial routing sync.
581 /// Not stored if contains excess data to prevent DoS.
582 pub announcement_message: Option<NodeAnnouncement>
585 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
586 (0, features, required),
587 (2, last_update, required),
589 (6, alias, required),
590 (8, announcement_message, option),
591 (10, addresses, vec_type),
594 #[derive(Clone, Debug, PartialEq)]
595 /// Details about a node in the network, known from the network announcement.
596 pub struct NodeInfo {
597 /// All valid channels a node has announced
598 pub channels: Vec<u64>,
599 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
600 /// The two fields (flat and proportional fee) are independent,
601 /// meaning they don't have to refer to the same channel.
602 pub lowest_inbound_channel_fees: Option<RoutingFees>,
603 /// More information about a node from node_announcement.
604 /// Optional because we store a Node entry after learning about it from
605 /// a channel announcement, but before receiving a node announcement.
606 pub announcement_info: Option<NodeAnnouncementInfo>
609 impl fmt::Display for NodeInfo {
610 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
611 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
612 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
617 impl_writeable_tlv_based!(NodeInfo, {
618 (0, lowest_inbound_channel_fees, option),
619 (2, announcement_info, option),
620 (4, channels, vec_type),
623 const SERIALIZATION_VERSION: u8 = 1;
624 const MIN_SERIALIZATION_VERSION: u8 = 1;
626 impl Writeable for NetworkGraph {
627 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
628 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
630 self.genesis_hash.write(writer)?;
631 let channels = self.channels.read().unwrap();
632 (channels.len() as u64).write(writer)?;
633 for (ref chan_id, ref chan_info) in channels.iter() {
634 (*chan_id).write(writer)?;
635 chan_info.write(writer)?;
637 let nodes = self.nodes.read().unwrap();
638 (nodes.len() as u64).write(writer)?;
639 for (ref node_id, ref node_info) in nodes.iter() {
640 node_id.write(writer)?;
641 node_info.write(writer)?;
644 write_tlv_fields!(writer, {});
649 impl Readable for NetworkGraph {
650 fn read<R: io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
651 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
653 let genesis_hash: BlockHash = Readable::read(reader)?;
654 let channels_count: u64 = Readable::read(reader)?;
655 let mut channels = BTreeMap::new();
656 for _ in 0..channels_count {
657 let chan_id: u64 = Readable::read(reader)?;
658 let chan_info = Readable::read(reader)?;
659 channels.insert(chan_id, chan_info);
661 let nodes_count: u64 = Readable::read(reader)?;
662 let mut nodes = BTreeMap::new();
663 for _ in 0..nodes_count {
664 let node_id = Readable::read(reader)?;
665 let node_info = Readable::read(reader)?;
666 nodes.insert(node_id, node_info);
668 read_tlv_fields!(reader, {});
672 channels: RwLock::new(channels),
673 nodes: RwLock::new(nodes),
678 impl fmt::Display for NetworkGraph {
679 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
680 writeln!(f, "Network map\n[Channels]")?;
681 for (key, val) in self.channels.read().unwrap().iter() {
682 writeln!(f, " {}: {}", key, val)?;
684 writeln!(f, "[Nodes]")?;
685 for (key, val) in self.nodes.read().unwrap().iter() {
686 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
692 impl PartialEq for NetworkGraph {
693 fn eq(&self, other: &Self) -> bool {
694 self.genesis_hash == other.genesis_hash &&
695 *self.channels.read().unwrap() == *other.channels.read().unwrap() &&
696 *self.nodes.read().unwrap() == *other.nodes.read().unwrap()
701 /// Creates a new, empty, network graph.
702 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
705 channels: RwLock::new(BTreeMap::new()),
706 nodes: RwLock::new(BTreeMap::new()),
710 /// Returns a read-only view of the network graph.
711 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
712 let channels = self.channels.read().unwrap();
713 let nodes = self.nodes.read().unwrap();
714 ReadOnlyNetworkGraph {
720 /// For an already known node (from channel announcements), update its stored properties from a
721 /// given node announcement.
723 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
724 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
725 /// routing messages from a source using a protocol other than the lightning P2P protocol.
726 pub fn update_node_from_announcement<T: secp256k1::Verification>(&self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
727 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
728 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
729 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
732 /// For an already known node (from channel announcements), update its stored properties from a
733 /// given node announcement without verifying the associated signatures. Because we aren't
734 /// given the associated signatures here we cannot relay the node announcement to any of our
736 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
737 self.update_node_from_announcement_intern(msg, None)
740 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
741 match self.nodes.write().unwrap().get_mut(&msg.node_id) {
742 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
744 if let Some(node_info) = node.announcement_info.as_ref() {
745 if node_info.last_update >= msg.timestamp {
746 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
751 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
752 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
753 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
754 node.announcement_info = Some(NodeAnnouncementInfo {
755 features: msg.features.clone(),
756 last_update: msg.timestamp,
759 addresses: msg.addresses.clone(),
760 announcement_message: if should_relay { full_msg.cloned() } else { None },
768 /// Store or update channel info from a channel announcement.
770 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
771 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
772 /// routing messages from a source using a protocol other than the lightning P2P protocol.
774 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
775 /// the corresponding UTXO exists on chain and is correctly-formatted.
776 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>(
777 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>
778 ) -> Result<(), LightningError>
780 C::Target: chain::Access,
782 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
783 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
784 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
785 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
786 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
787 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
790 /// Store or update channel info from a channel announcement without verifying the associated
791 /// signatures. Because we aren't given the associated signatures here we cannot relay the
792 /// channel announcement to any of our peers.
794 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
795 /// the corresponding UTXO exists on chain and is correctly-formatted.
796 pub fn update_channel_from_unsigned_announcement<C: Deref>(
797 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
798 ) -> Result<(), LightningError>
800 C::Target: chain::Access,
802 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
805 fn update_channel_from_unsigned_announcement_intern<C: Deref>(
806 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
807 ) -> Result<(), LightningError>
809 C::Target: chain::Access,
811 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
812 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
815 let utxo_value = match &chain_access {
817 // Tentatively accept, potentially exposing us to DoS attacks
820 &Some(ref chain_access) => {
821 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
822 Ok(TxOut { value, script_pubkey }) => {
823 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
824 .push_slice(&msg.bitcoin_key_1.serialize())
825 .push_slice(&msg.bitcoin_key_2.serialize())
826 .push_opcode(opcodes::all::OP_PUSHNUM_2)
827 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
828 if script_pubkey != expected_script {
829 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});
831 //TODO: Check if value is worth storing, use it to inform routing, and compare it
832 //to the new HTLC max field in channel_update
835 Err(chain::AccessError::UnknownChain) => {
836 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
838 Err(chain::AccessError::UnknownTx) => {
839 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
845 let chan_info = ChannelInfo {
846 features: msg.features.clone(),
847 node_one: msg.node_id_1.clone(),
849 node_two: msg.node_id_2.clone(),
851 capacity_sats: utxo_value,
852 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
853 { full_msg.cloned() } else { None },
856 let mut channels = self.channels.write().unwrap();
857 let mut nodes = self.nodes.write().unwrap();
858 match channels.entry(msg.short_channel_id) {
859 BtreeEntry::Occupied(mut entry) => {
860 //TODO: because asking the blockchain if short_channel_id is valid is only optional
861 //in the blockchain API, we need to handle it smartly here, though it's unclear
863 if utxo_value.is_some() {
864 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
865 // only sometimes returns results. In any case remove the previous entry. Note
866 // that the spec expects us to "blacklist" the node_ids involved, but we can't
868 // a) we don't *require* a UTXO provider that always returns results.
869 // b) we don't track UTXOs of channels we know about and remove them if they
871 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
872 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), msg.short_channel_id);
873 *entry.get_mut() = chan_info;
875 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)})
878 BtreeEntry::Vacant(entry) => {
879 entry.insert(chan_info);
883 macro_rules! add_channel_to_node {
884 ( $node_id: expr ) => {
885 match nodes.entry($node_id) {
886 BtreeEntry::Occupied(node_entry) => {
887 node_entry.into_mut().channels.push(msg.short_channel_id);
889 BtreeEntry::Vacant(node_entry) => {
890 node_entry.insert(NodeInfo {
891 channels: vec!(msg.short_channel_id),
892 lowest_inbound_channel_fees: None,
893 announcement_info: None,
900 add_channel_to_node!(msg.node_id_1);
901 add_channel_to_node!(msg.node_id_2);
906 /// Close a channel if a corresponding HTLC fail was sent.
907 /// If permanent, removes a channel from the local storage.
908 /// May cause the removal of nodes too, if this was their last channel.
909 /// If not permanent, makes channels unavailable for routing.
910 pub fn close_channel_from_update(&self, short_channel_id: u64, is_permanent: bool) {
911 let mut channels = self.channels.write().unwrap();
913 if let Some(chan) = channels.remove(&short_channel_id) {
914 let mut nodes = self.nodes.write().unwrap();
915 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
918 if let Some(chan) = channels.get_mut(&short_channel_id) {
919 if let Some(one_to_two) = chan.one_to_two.as_mut() {
920 one_to_two.enabled = false;
922 if let Some(two_to_one) = chan.two_to_one.as_mut() {
923 two_to_one.enabled = false;
929 /// Marks a node in the graph as failed.
930 pub fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
932 // TODO: Wholly remove the node
934 // TODO: downgrade the node
938 /// For an already known (from announcement) channel, update info about one of the directions
941 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
942 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
943 /// routing messages from a source using a protocol other than the lightning P2P protocol.
944 pub fn update_channel<T: secp256k1::Verification>(&self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
945 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
948 /// For an already known (from announcement) channel, update info about one of the directions
949 /// of the channel without verifying the associated signatures. Because we aren't given the
950 /// associated signatures here we cannot relay the channel update to any of our peers.
951 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
952 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
955 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> {
957 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
958 let chan_was_enabled;
960 let mut channels = self.channels.write().unwrap();
961 match channels.get_mut(&msg.short_channel_id) {
962 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
964 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
965 if htlc_maximum_msat > MAX_VALUE_MSAT {
966 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
969 if let Some(capacity_sats) = channel.capacity_sats {
970 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
971 // Don't query UTXO set here to reduce DoS risks.
972 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
973 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
977 macro_rules! maybe_update_channel_info {
978 ( $target: expr, $src_node: expr) => {
979 if let Some(existing_chan_info) = $target.as_ref() {
980 if existing_chan_info.last_update >= msg.timestamp {
981 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
983 chan_was_enabled = existing_chan_info.enabled;
985 chan_was_enabled = false;
988 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
989 { full_msg.cloned() } else { None };
991 let updated_channel_dir_info = DirectionalChannelInfo {
992 enabled: chan_enabled,
993 last_update: msg.timestamp,
994 cltv_expiry_delta: msg.cltv_expiry_delta,
995 htlc_minimum_msat: msg.htlc_minimum_msat,
996 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
998 base_msat: msg.fee_base_msat,
999 proportional_millionths: msg.fee_proportional_millionths,
1003 $target = Some(updated_channel_dir_info);
1007 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1008 if msg.flags & 1 == 1 {
1009 dest_node_id = channel.node_one.clone();
1010 if let Some((sig, ctx)) = sig_info {
1011 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1013 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1015 dest_node_id = channel.node_two.clone();
1016 if let Some((sig, ctx)) = sig_info {
1017 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1019 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1024 let mut nodes = self.nodes.write().unwrap();
1026 let node = nodes.get_mut(&dest_node_id).unwrap();
1027 let mut base_msat = msg.fee_base_msat;
1028 let mut proportional_millionths = msg.fee_proportional_millionths;
1029 if let Some(fees) = node.lowest_inbound_channel_fees {
1030 base_msat = cmp::min(base_msat, fees.base_msat);
1031 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1033 node.lowest_inbound_channel_fees = Some(RoutingFees {
1035 proportional_millionths
1037 } else if chan_was_enabled {
1038 let node = nodes.get_mut(&dest_node_id).unwrap();
1039 let mut lowest_inbound_channel_fees = None;
1041 for chan_id in node.channels.iter() {
1042 let chan = channels.get(chan_id).unwrap();
1044 if chan.node_one == dest_node_id {
1045 chan_info_opt = chan.two_to_one.as_ref();
1047 chan_info_opt = chan.one_to_two.as_ref();
1049 if let Some(chan_info) = chan_info_opt {
1050 if chan_info.enabled {
1051 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1052 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1053 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1054 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1059 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1065 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1066 macro_rules! remove_from_node {
1067 ($node_id: expr) => {
1068 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1069 entry.get_mut().channels.retain(|chan_id| {
1070 short_channel_id != *chan_id
1072 if entry.get().channels.is_empty() {
1073 entry.remove_entry();
1076 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1081 remove_from_node!(chan.node_one);
1082 remove_from_node!(chan.node_two);
1086 impl ReadOnlyNetworkGraph<'_> {
1087 /// Returns all known valid channels' short ids along with announced channel info.
1089 /// (C-not exported) because we have no mapping for `BTreeMap`s
1090 pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1094 /// Returns all known nodes' public keys along with announced node info.
1096 /// (C-not exported) because we have no mapping for `BTreeMap`s
1097 pub fn nodes(&self) -> &BTreeMap<PublicKey, NodeInfo> {
1101 /// Get network addresses by node id.
1102 /// Returns None if the requested node is completely unknown,
1103 /// or if node announcement for the node was never received.
1105 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
1106 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<&Vec<NetAddress>> {
1107 if let Some(node) = self.nodes.get(pubkey) {
1108 if let Some(node_info) = node.announcement_info.as_ref() {
1109 return Some(&node_info.addresses)
1119 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1120 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
1121 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1122 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
1123 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1124 use util::test_utils;
1125 use util::logger::Logger;
1126 use util::ser::{Readable, Writeable};
1127 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1128 use util::scid_utils::scid_from_parts;
1130 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1131 use bitcoin::hashes::Hash;
1132 use bitcoin::network::constants::Network;
1133 use bitcoin::blockdata::constants::genesis_block;
1134 use bitcoin::blockdata::script::Builder;
1135 use bitcoin::blockdata::transaction::TxOut;
1136 use bitcoin::blockdata::opcodes;
1140 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1141 use bitcoin::secp256k1::{All, Secp256k1};
1147 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1148 let secp_ctx = Secp256k1::new();
1149 let logger = Arc::new(test_utils::TestLogger::new());
1150 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1151 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1152 (secp_ctx, net_graph_msg_handler)
1156 fn request_full_sync_finite_times() {
1157 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1158 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1160 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1161 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1162 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1163 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1164 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1165 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1169 fn handling_node_announcements() {
1170 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1172 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1173 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1174 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1175 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1176 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1177 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1178 let zero_hash = Sha256dHash::hash(&[0; 32]);
1179 let first_announcement_time = 500;
1181 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1182 features: NodeFeatures::known(),
1183 timestamp: first_announcement_time,
1187 addresses: Vec::new(),
1188 excess_address_data: Vec::new(),
1189 excess_data: Vec::new(),
1191 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1192 let valid_announcement = NodeAnnouncement {
1193 signature: secp_ctx.sign(&msghash, node_1_privkey),
1194 contents: unsigned_announcement.clone()
1197 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1199 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1203 // Announce a channel to add a corresponding node.
1204 let unsigned_announcement = UnsignedChannelAnnouncement {
1205 features: ChannelFeatures::known(),
1206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1207 short_channel_id: 0,
1210 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1211 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1212 excess_data: Vec::new(),
1215 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1216 let valid_announcement = ChannelAnnouncement {
1217 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1218 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1219 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1220 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1221 contents: unsigned_announcement.clone(),
1223 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1224 Ok(res) => assert!(res),
1229 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1230 Ok(res) => assert!(res),
1234 let fake_msghash = hash_to_message!(&zero_hash);
1235 match net_graph_msg_handler.handle_node_announcement(
1237 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1238 contents: unsigned_announcement.clone()
1241 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1244 unsigned_announcement.timestamp += 1000;
1245 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1246 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1247 let announcement_with_data = NodeAnnouncement {
1248 signature: secp_ctx.sign(&msghash, node_1_privkey),
1249 contents: unsigned_announcement.clone()
1251 // Return false because contains excess data.
1252 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1253 Ok(res) => assert!(!res),
1256 unsigned_announcement.excess_data = Vec::new();
1258 // Even though previous announcement was not relayed further, we still accepted it,
1259 // so we now won't accept announcements before the previous one.
1260 unsigned_announcement.timestamp -= 10;
1261 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1262 let outdated_announcement = NodeAnnouncement {
1263 signature: secp_ctx.sign(&msghash, node_1_privkey),
1264 contents: unsigned_announcement.clone()
1266 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1268 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1273 fn handling_channel_announcements() {
1274 let secp_ctx = Secp256k1::new();
1275 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1277 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1278 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1279 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1280 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1281 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1282 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1284 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1285 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1286 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1287 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1288 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1291 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1292 features: ChannelFeatures::known(),
1293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1294 short_channel_id: 0,
1297 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1298 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1299 excess_data: Vec::new(),
1302 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1303 let valid_announcement = ChannelAnnouncement {
1304 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1305 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1306 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1307 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1308 contents: unsigned_announcement.clone(),
1311 // Test if the UTXO lookups were not supported
1312 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1313 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1314 Ok(res) => assert!(res),
1319 let network = &net_graph_msg_handler.network_graph;
1320 match network.read_only().channels().get(&unsigned_announcement.short_channel_id) {
1326 // If we receive announcement for the same channel (with UTXO lookups disabled),
1327 // drop new one on the floor, since we can't see any changes.
1328 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1330 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1333 // Test if an associated transaction were not on-chain (or not confirmed).
1334 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1335 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1336 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1337 unsigned_announcement.short_channel_id += 1;
1339 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1340 let valid_announcement = ChannelAnnouncement {
1341 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1342 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1343 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1344 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1345 contents: unsigned_announcement.clone(),
1348 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1350 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1353 // Now test if the transaction is found in the UTXO set and the script is correct.
1354 unsigned_announcement.short_channel_id += 1;
1355 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1357 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1358 let valid_announcement = ChannelAnnouncement {
1359 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1360 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1361 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1362 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1363 contents: unsigned_announcement.clone(),
1365 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1366 Ok(res) => assert!(res),
1371 let network = &net_graph_msg_handler.network_graph;
1372 match network.read_only().channels().get(&unsigned_announcement.short_channel_id) {
1378 // If we receive announcement for the same channel (but TX is not confirmed),
1379 // drop new one on the floor, since we can't see any changes.
1380 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1381 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1383 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1386 // But if it is confirmed, replace the channel
1387 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1388 unsigned_announcement.features = ChannelFeatures::empty();
1389 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1390 let valid_announcement = ChannelAnnouncement {
1391 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1392 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1393 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1394 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1395 contents: unsigned_announcement.clone(),
1397 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1398 Ok(res) => assert!(res),
1402 let network = &net_graph_msg_handler.network_graph;
1403 match network.read_only().channels().get(&unsigned_announcement.short_channel_id) {
1404 Some(channel_entry) => {
1405 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1411 // Don't relay valid channels with excess data
1412 unsigned_announcement.short_channel_id += 1;
1413 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1414 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1415 let valid_announcement = ChannelAnnouncement {
1416 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1417 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1418 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1419 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1420 contents: unsigned_announcement.clone(),
1422 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1423 Ok(res) => assert!(!res),
1427 unsigned_announcement.excess_data = Vec::new();
1428 let invalid_sig_announcement = ChannelAnnouncement {
1429 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1430 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1431 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1432 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1433 contents: unsigned_announcement.clone(),
1435 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1437 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1440 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1441 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1442 let channel_to_itself_announcement = ChannelAnnouncement {
1443 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1444 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1445 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1446 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1447 contents: unsigned_announcement.clone(),
1449 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1451 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1456 fn handling_channel_update() {
1457 let secp_ctx = Secp256k1::new();
1458 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1459 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1460 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1462 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1463 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1464 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1465 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1466 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1467 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1469 let zero_hash = Sha256dHash::hash(&[0; 32]);
1470 let short_channel_id = 0;
1471 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1472 let amount_sats = 1000_000;
1475 // Announce a channel we will update
1476 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1477 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1478 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1479 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1480 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1481 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1482 let unsigned_announcement = UnsignedChannelAnnouncement {
1483 features: ChannelFeatures::empty(),
1488 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1489 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1490 excess_data: Vec::new(),
1493 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1494 let valid_channel_announcement = ChannelAnnouncement {
1495 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1496 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1497 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1498 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1499 contents: unsigned_announcement.clone(),
1501 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1508 let mut unsigned_channel_update = UnsignedChannelUpdate {
1513 cltv_expiry_delta: 144,
1514 htlc_minimum_msat: 1000000,
1515 htlc_maximum_msat: OptionalField::Absent,
1516 fee_base_msat: 10000,
1517 fee_proportional_millionths: 20,
1518 excess_data: Vec::new()
1520 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1521 let valid_channel_update = ChannelUpdate {
1522 signature: secp_ctx.sign(&msghash, node_1_privkey),
1523 contents: unsigned_channel_update.clone()
1526 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1527 Ok(res) => assert!(res),
1532 let network = &net_graph_msg_handler.network_graph;
1533 match network.read_only().channels().get(&short_channel_id) {
1535 Some(channel_info) => {
1536 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1537 assert!(channel_info.two_to_one.is_none());
1542 unsigned_channel_update.timestamp += 100;
1543 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1544 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1545 let valid_channel_update = ChannelUpdate {
1546 signature: secp_ctx.sign(&msghash, node_1_privkey),
1547 contents: unsigned_channel_update.clone()
1549 // Return false because contains excess data
1550 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1551 Ok(res) => assert!(!res),
1554 unsigned_channel_update.timestamp += 10;
1556 unsigned_channel_update.short_channel_id += 1;
1557 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1558 let valid_channel_update = ChannelUpdate {
1559 signature: secp_ctx.sign(&msghash, node_1_privkey),
1560 contents: unsigned_channel_update.clone()
1563 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1565 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1567 unsigned_channel_update.short_channel_id = short_channel_id;
1569 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1570 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1571 let valid_channel_update = ChannelUpdate {
1572 signature: secp_ctx.sign(&msghash, node_1_privkey),
1573 contents: unsigned_channel_update.clone()
1576 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1578 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1580 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1582 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1583 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1584 let valid_channel_update = ChannelUpdate {
1585 signature: secp_ctx.sign(&msghash, node_1_privkey),
1586 contents: unsigned_channel_update.clone()
1589 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1591 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1593 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1595 // Even though previous update was not relayed further, we still accepted it,
1596 // so we now won't accept update before the previous one.
1597 unsigned_channel_update.timestamp -= 10;
1598 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1599 let valid_channel_update = ChannelUpdate {
1600 signature: secp_ctx.sign(&msghash, node_1_privkey),
1601 contents: unsigned_channel_update.clone()
1604 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1606 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1608 unsigned_channel_update.timestamp += 500;
1610 let fake_msghash = hash_to_message!(&zero_hash);
1611 let invalid_sig_channel_update = ChannelUpdate {
1612 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1613 contents: unsigned_channel_update.clone()
1616 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1618 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1624 fn handling_htlc_fail_channel_update() {
1625 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1626 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1627 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1628 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1629 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1630 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1631 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1633 let short_channel_id = 0;
1634 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1637 // There is no nodes in the table at the beginning.
1638 let network = &net_graph_msg_handler.network_graph;
1639 assert_eq!(network.read_only().nodes().len(), 0);
1643 // Announce a channel we will update
1644 let unsigned_announcement = UnsignedChannelAnnouncement {
1645 features: ChannelFeatures::empty(),
1650 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1651 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1652 excess_data: Vec::new(),
1655 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1656 let valid_channel_announcement = ChannelAnnouncement {
1657 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1658 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1659 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1660 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1661 contents: unsigned_announcement.clone(),
1663 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1668 let unsigned_channel_update = UnsignedChannelUpdate {
1673 cltv_expiry_delta: 144,
1674 htlc_minimum_msat: 1000000,
1675 htlc_maximum_msat: OptionalField::Absent,
1676 fee_base_msat: 10000,
1677 fee_proportional_millionths: 20,
1678 excess_data: Vec::new()
1680 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1681 let valid_channel_update = ChannelUpdate {
1682 signature: secp_ctx.sign(&msghash, node_1_privkey),
1683 contents: unsigned_channel_update.clone()
1686 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1687 Ok(res) => assert!(res),
1692 // Non-permanent closing just disables a channel
1694 let network = &net_graph_msg_handler.network_graph;
1695 match network.read_only().channels().get(&short_channel_id) {
1697 Some(channel_info) => {
1698 assert!(channel_info.one_to_two.is_some());
1703 net_graph_msg_handler.network_graph.close_channel_from_update(short_channel_id, false);
1705 // Non-permanent closing just disables a channel
1707 let network = &net_graph_msg_handler.network_graph;
1708 match network.read_only().channels().get(&short_channel_id) {
1710 Some(channel_info) => {
1711 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1716 net_graph_msg_handler.network_graph.close_channel_from_update(short_channel_id, true);
1718 // Permanent closing deletes a channel
1720 let network = &net_graph_msg_handler.network_graph;
1721 assert_eq!(network.read_only().channels().len(), 0);
1722 // Nodes are also deleted because there are no associated channels anymore
1723 assert_eq!(network.read_only().nodes().len(), 0);
1725 // TODO: Test NetworkUpdate::NodeFailure, which is not implemented yet.
1729 fn getting_next_channel_announcements() {
1730 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1731 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1732 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1733 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1734 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1735 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1736 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1738 let short_channel_id = 1;
1739 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1741 // Channels were not announced yet.
1742 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1743 assert_eq!(channels_with_announcements.len(), 0);
1746 // Announce a channel we will update
1747 let unsigned_announcement = UnsignedChannelAnnouncement {
1748 features: ChannelFeatures::empty(),
1753 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1754 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1755 excess_data: Vec::new(),
1758 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1759 let valid_channel_announcement = ChannelAnnouncement {
1760 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1761 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1762 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1763 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1764 contents: unsigned_announcement.clone(),
1766 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1772 // Contains initial channel announcement now.
1773 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1774 assert_eq!(channels_with_announcements.len(), 1);
1775 if let Some(channel_announcements) = channels_with_announcements.first() {
1776 let &(_, ref update_1, ref update_2) = channel_announcements;
1777 assert_eq!(update_1, &None);
1778 assert_eq!(update_2, &None);
1785 // Valid channel update
1786 let unsigned_channel_update = UnsignedChannelUpdate {
1791 cltv_expiry_delta: 144,
1792 htlc_minimum_msat: 1000000,
1793 htlc_maximum_msat: OptionalField::Absent,
1794 fee_base_msat: 10000,
1795 fee_proportional_millionths: 20,
1796 excess_data: Vec::new()
1798 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1799 let valid_channel_update = ChannelUpdate {
1800 signature: secp_ctx.sign(&msghash, node_1_privkey),
1801 contents: unsigned_channel_update.clone()
1803 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1809 // Now contains an initial announcement and an update.
1810 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1811 assert_eq!(channels_with_announcements.len(), 1);
1812 if let Some(channel_announcements) = channels_with_announcements.first() {
1813 let &(_, ref update_1, ref update_2) = channel_announcements;
1814 assert_ne!(update_1, &None);
1815 assert_eq!(update_2, &None);
1822 // Channel update with excess data.
1823 let unsigned_channel_update = UnsignedChannelUpdate {
1828 cltv_expiry_delta: 144,
1829 htlc_minimum_msat: 1000000,
1830 htlc_maximum_msat: OptionalField::Absent,
1831 fee_base_msat: 10000,
1832 fee_proportional_millionths: 20,
1833 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1835 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1836 let valid_channel_update = ChannelUpdate {
1837 signature: secp_ctx.sign(&msghash, node_1_privkey),
1838 contents: unsigned_channel_update.clone()
1840 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1846 // Test that announcements with excess data won't be returned
1847 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1848 assert_eq!(channels_with_announcements.len(), 1);
1849 if let Some(channel_announcements) = channels_with_announcements.first() {
1850 let &(_, ref update_1, ref update_2) = channel_announcements;
1851 assert_eq!(update_1, &None);
1852 assert_eq!(update_2, &None);
1857 // Further starting point have no channels after it
1858 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1859 assert_eq!(channels_with_announcements.len(), 0);
1863 fn getting_next_node_announcements() {
1864 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1865 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1866 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1867 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1868 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1869 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1870 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1872 let short_channel_id = 1;
1873 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1876 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1877 assert_eq!(next_announcements.len(), 0);
1880 // Announce a channel to add 2 nodes
1881 let unsigned_announcement = UnsignedChannelAnnouncement {
1882 features: ChannelFeatures::empty(),
1887 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1888 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1889 excess_data: Vec::new(),
1892 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1893 let valid_channel_announcement = ChannelAnnouncement {
1894 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1895 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1896 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1897 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1898 contents: unsigned_announcement.clone(),
1900 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1907 // Nodes were never announced
1908 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1909 assert_eq!(next_announcements.len(), 0);
1912 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1913 features: NodeFeatures::known(),
1918 addresses: Vec::new(),
1919 excess_address_data: Vec::new(),
1920 excess_data: Vec::new(),
1922 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1923 let valid_announcement = NodeAnnouncement {
1924 signature: secp_ctx.sign(&msghash, node_1_privkey),
1925 contents: unsigned_announcement.clone()
1927 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1932 unsigned_announcement.node_id = node_id_2;
1933 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1934 let valid_announcement = NodeAnnouncement {
1935 signature: secp_ctx.sign(&msghash, node_2_privkey),
1936 contents: unsigned_announcement.clone()
1939 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1945 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1946 assert_eq!(next_announcements.len(), 2);
1948 // Skip the first node.
1949 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1950 assert_eq!(next_announcements.len(), 1);
1953 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1954 let unsigned_announcement = UnsignedNodeAnnouncement {
1955 features: NodeFeatures::known(),
1960 addresses: Vec::new(),
1961 excess_address_data: Vec::new(),
1962 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
1964 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1965 let valid_announcement = NodeAnnouncement {
1966 signature: secp_ctx.sign(&msghash, node_2_privkey),
1967 contents: unsigned_announcement.clone()
1969 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1970 Ok(res) => assert!(!res),
1975 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1976 assert_eq!(next_announcements.len(), 0);
1980 fn network_graph_serialization() {
1981 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1983 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1984 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1985 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1986 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1988 // Announce a channel to add a corresponding node.
1989 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1990 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1991 let unsigned_announcement = UnsignedChannelAnnouncement {
1992 features: ChannelFeatures::known(),
1993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1994 short_channel_id: 0,
1997 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1998 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1999 excess_data: Vec::new(),
2002 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2003 let valid_announcement = ChannelAnnouncement {
2004 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2005 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2006 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2007 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2008 contents: unsigned_announcement.clone(),
2010 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2011 Ok(res) => assert!(res),
2016 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2017 let unsigned_announcement = UnsignedNodeAnnouncement {
2018 features: NodeFeatures::known(),
2023 addresses: Vec::new(),
2024 excess_address_data: Vec::new(),
2025 excess_data: Vec::new(),
2027 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2028 let valid_announcement = NodeAnnouncement {
2029 signature: secp_ctx.sign(&msghash, node_1_privkey),
2030 contents: unsigned_announcement.clone()
2033 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2038 let network = &net_graph_msg_handler.network_graph;
2039 let mut w = test_utils::TestVecWriter(Vec::new());
2040 assert!(!network.read_only().nodes().is_empty());
2041 assert!(!network.read_only().channels().is_empty());
2042 network.write(&mut w).unwrap();
2043 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == *network);
2047 fn calling_sync_routing_table() {
2048 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2049 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2050 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2052 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2053 let first_blocknum = 0;
2054 let number_of_blocks = 0xffff_ffff;
2056 // It should ignore if gossip_queries feature is not enabled
2058 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2059 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2060 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2061 assert_eq!(events.len(), 0);
2064 // It should send a query_channel_message with the correct information
2066 let init_msg = Init { features: InitFeatures::known() };
2067 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2068 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2069 assert_eq!(events.len(), 1);
2071 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2072 assert_eq!(node_id, &node_id_1);
2073 assert_eq!(msg.chain_hash, chain_hash);
2074 assert_eq!(msg.first_blocknum, first_blocknum);
2075 assert_eq!(msg.number_of_blocks, number_of_blocks);
2077 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2081 // It should not enqueue a query when should_request_full_sync return false.
2082 // The initial implementation allows syncing with the first 5 peers after
2083 // which should_request_full_sync will return false
2085 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2086 let init_msg = Init { features: InitFeatures::known() };
2088 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2089 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2090 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2091 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2093 assert_eq!(events.len(), 1);
2095 assert_eq!(events.len(), 0);
2103 fn handling_reply_channel_range() {
2104 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2105 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2106 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2108 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2110 // Test receipt of a single reply that should enqueue an SCID query
2111 // matching the SCIDs in the reply
2113 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2115 sync_complete: true,
2117 number_of_blocks: 2000,
2118 short_channel_ids: vec![
2119 0x0003e0_000000_0000, // 992x0x0
2120 0x0003e8_000000_0000, // 1000x0x0
2121 0x0003e9_000000_0000, // 1001x0x0
2122 0x0003f0_000000_0000, // 1008x0x0
2123 0x00044c_000000_0000, // 1100x0x0
2124 0x0006e0_000000_0000, // 1760x0x0
2127 assert!(result.is_ok());
2129 // We expect to emit a query_short_channel_ids message with the received scids
2130 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2131 assert_eq!(events.len(), 1);
2133 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2134 assert_eq!(node_id, &node_id_1);
2135 assert_eq!(msg.chain_hash, chain_hash);
2136 assert_eq!(msg.short_channel_ids, vec![
2137 0x0003e0_000000_0000, // 992x0x0
2138 0x0003e8_000000_0000, // 1000x0x0
2139 0x0003e9_000000_0000, // 1001x0x0
2140 0x0003f0_000000_0000, // 1008x0x0
2141 0x00044c_000000_0000, // 1100x0x0
2142 0x0006e0_000000_0000, // 1760x0x0
2145 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2151 fn handling_reply_short_channel_ids() {
2152 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2153 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2154 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2156 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2158 // Test receipt of a successful reply
2160 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2162 full_information: true,
2164 assert!(result.is_ok());
2167 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2168 // for the chain_hash requested in the query.
2170 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2172 full_information: false,
2174 assert!(result.is_err());
2175 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2180 fn handling_query_channel_range() {
2181 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2183 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2184 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2185 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2186 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2187 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2188 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2189 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2190 let bitcoin_key_1 = PublicKey::from_secret_key(&secp_ctx, node_1_btckey);
2191 let bitcoin_key_2 = PublicKey::from_secret_key(&secp_ctx, node_2_btckey);
2193 let mut scids: Vec<u64> = vec![
2194 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2195 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2198 // used for testing multipart reply across blocks
2199 for block in 100000..=108001 {
2200 scids.push(scid_from_parts(block, 0, 0).unwrap());
2203 // used for testing resumption on same block
2204 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2207 let unsigned_announcement = UnsignedChannelAnnouncement {
2208 features: ChannelFeatures::known(),
2209 chain_hash: chain_hash.clone(),
2210 short_channel_id: scid,
2215 excess_data: Vec::new(),
2218 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2219 let valid_announcement = ChannelAnnouncement {
2220 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2221 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2222 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2223 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2224 contents: unsigned_announcement.clone(),
2226 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2232 // Error when number_of_blocks=0
2233 do_handling_query_channel_range(
2234 &net_graph_msg_handler,
2237 chain_hash: chain_hash.clone(),
2239 number_of_blocks: 0,
2242 vec![ReplyChannelRange {
2243 chain_hash: chain_hash.clone(),
2245 number_of_blocks: 0,
2246 sync_complete: true,
2247 short_channel_ids: vec![]
2251 // Error when wrong chain
2252 do_handling_query_channel_range(
2253 &net_graph_msg_handler,
2256 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2258 number_of_blocks: 0xffff_ffff,
2261 vec![ReplyChannelRange {
2262 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2264 number_of_blocks: 0xffff_ffff,
2265 sync_complete: true,
2266 short_channel_ids: vec![],
2270 // Error when first_blocknum > 0xffffff
2271 do_handling_query_channel_range(
2272 &net_graph_msg_handler,
2275 chain_hash: chain_hash.clone(),
2276 first_blocknum: 0x01000000,
2277 number_of_blocks: 0xffff_ffff,
2280 vec![ReplyChannelRange {
2281 chain_hash: chain_hash.clone(),
2282 first_blocknum: 0x01000000,
2283 number_of_blocks: 0xffff_ffff,
2284 sync_complete: true,
2285 short_channel_ids: vec![]
2289 // Empty reply when max valid SCID block num
2290 do_handling_query_channel_range(
2291 &net_graph_msg_handler,
2294 chain_hash: chain_hash.clone(),
2295 first_blocknum: 0xffffff,
2296 number_of_blocks: 1,
2301 chain_hash: chain_hash.clone(),
2302 first_blocknum: 0xffffff,
2303 number_of_blocks: 1,
2304 sync_complete: true,
2305 short_channel_ids: vec![]
2310 // No results in valid query range
2311 do_handling_query_channel_range(
2312 &net_graph_msg_handler,
2315 chain_hash: chain_hash.clone(),
2316 first_blocknum: 1000,
2317 number_of_blocks: 1000,
2322 chain_hash: chain_hash.clone(),
2323 first_blocknum: 1000,
2324 number_of_blocks: 1000,
2325 sync_complete: true,
2326 short_channel_ids: vec![],
2331 // Overflow first_blocknum + number_of_blocks
2332 do_handling_query_channel_range(
2333 &net_graph_msg_handler,
2336 chain_hash: chain_hash.clone(),
2337 first_blocknum: 0xfe0000,
2338 number_of_blocks: 0xffffffff,
2343 chain_hash: chain_hash.clone(),
2344 first_blocknum: 0xfe0000,
2345 number_of_blocks: 0xffffffff - 0xfe0000,
2346 sync_complete: true,
2347 short_channel_ids: vec![
2348 0xfffffe_ffffff_ffff, // max
2354 // Single block exactly full
2355 do_handling_query_channel_range(
2356 &net_graph_msg_handler,
2359 chain_hash: chain_hash.clone(),
2360 first_blocknum: 100000,
2361 number_of_blocks: 8000,
2366 chain_hash: chain_hash.clone(),
2367 first_blocknum: 100000,
2368 number_of_blocks: 8000,
2369 sync_complete: true,
2370 short_channel_ids: (100000..=107999)
2371 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2377 // Multiple split on new block
2378 do_handling_query_channel_range(
2379 &net_graph_msg_handler,
2382 chain_hash: chain_hash.clone(),
2383 first_blocknum: 100000,
2384 number_of_blocks: 8001,
2389 chain_hash: chain_hash.clone(),
2390 first_blocknum: 100000,
2391 number_of_blocks: 7999,
2392 sync_complete: false,
2393 short_channel_ids: (100000..=107999)
2394 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2398 chain_hash: chain_hash.clone(),
2399 first_blocknum: 107999,
2400 number_of_blocks: 2,
2401 sync_complete: true,
2402 short_channel_ids: vec![
2403 scid_from_parts(108000, 0, 0).unwrap(),
2409 // Multiple split on same block
2410 do_handling_query_channel_range(
2411 &net_graph_msg_handler,
2414 chain_hash: chain_hash.clone(),
2415 first_blocknum: 100002,
2416 number_of_blocks: 8000,
2421 chain_hash: chain_hash.clone(),
2422 first_blocknum: 100002,
2423 number_of_blocks: 7999,
2424 sync_complete: false,
2425 short_channel_ids: (100002..=108001)
2426 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2430 chain_hash: chain_hash.clone(),
2431 first_blocknum: 108001,
2432 number_of_blocks: 1,
2433 sync_complete: true,
2434 short_channel_ids: vec![
2435 scid_from_parts(108001, 1, 0).unwrap(),
2442 fn do_handling_query_channel_range(
2443 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2444 test_node_id: &PublicKey,
2445 msg: QueryChannelRange,
2447 expected_replies: Vec<ReplyChannelRange>
2449 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2450 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2451 let query_end_blocknum = msg.end_blocknum();
2452 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2455 assert!(result.is_ok());
2457 assert!(result.is_err());
2460 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2461 assert_eq!(events.len(), expected_replies.len());
2463 for i in 0..events.len() {
2464 let expected_reply = &expected_replies[i];
2466 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2467 assert_eq!(node_id, test_node_id);
2468 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2469 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2470 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2471 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2472 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2474 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2475 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2476 assert!(msg.first_blocknum >= max_firstblocknum);
2477 max_firstblocknum = msg.first_blocknum;
2478 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2480 // Check that the last block count is >= the query's end_blocknum
2481 if i == events.len() - 1 {
2482 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2485 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2491 fn handling_query_short_channel_ids() {
2492 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2493 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2494 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2496 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2498 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2500 short_channel_ids: vec![0x0003e8_000000_0000],
2502 assert!(result.is_err());
2506 #[cfg(all(test, feature = "unstable"))]
2514 fn read_network_graph(bench: &mut Bencher) {
2515 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2516 let mut v = Vec::new();
2517 d.read_to_end(&mut v).unwrap();
2519 let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2524 fn write_network_graph(bench: &mut Bencher) {
2525 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2526 let net_graph = NetworkGraph::read(&mut d).unwrap();
2528 let _ = net_graph.encode();