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::constants::PUBLIC_KEY_SIZE;
13 use bitcoin::secp256k1::key::PublicKey;
14 use bitcoin::secp256k1::Secp256k1;
15 use bitcoin::secp256k1;
17 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
18 use bitcoin::hashes::Hash;
19 use bitcoin::blockdata::script::Builder;
20 use bitcoin::blockdata::transaction::TxOut;
21 use bitcoin::blockdata::opcodes;
22 use bitcoin::hash_types::BlockHash;
26 use ln::features::{ChannelFeatures, NodeFeatures};
27 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
28 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
29 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
31 use util::ser::{Writeable, Readable, Writer};
32 use util::logger::{Logger, Level};
33 use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
34 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
38 use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
40 use sync::{RwLock, RwLockReadGuard};
41 use core::sync::atomic::{AtomicUsize, Ordering};
44 use bitcoin::hashes::hex::ToHex;
46 #[cfg(feature = "std")]
47 use std::time::{SystemTime, UNIX_EPOCH};
49 /// We remove stale channel directional info two weeks after the last update, per BOLT 7's
51 const STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14;
53 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
54 /// refuse to relay the message.
55 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
57 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
58 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
59 const MAX_SCIDS_PER_REPLY: usize = 8000;
61 /// Represents the compressed public key of a node
62 #[derive(Clone, Copy)]
63 pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
66 /// Create a new NodeId from a public key
67 pub fn from_pubkey(pubkey: &PublicKey) -> Self {
68 NodeId(pubkey.serialize())
71 /// Get the public key slice from this NodeId
72 pub fn as_slice(&self) -> &[u8] {
77 impl fmt::Debug for NodeId {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 write!(f, "NodeId({})", log_bytes!(self.0))
83 impl core::hash::Hash for NodeId {
84 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
91 impl PartialEq for NodeId {
92 fn eq(&self, other: &Self) -> bool {
93 self.0[..] == other.0[..]
97 impl cmp::PartialOrd for NodeId {
98 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
103 impl Ord for NodeId {
104 fn cmp(&self, other: &Self) -> cmp::Ordering {
105 self.0[..].cmp(&other.0[..])
109 impl Writeable for NodeId {
110 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
111 writer.write_all(&self.0)?;
116 impl Readable for NodeId {
117 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
118 let mut buf = [0; PUBLIC_KEY_SIZE];
119 reader.read_exact(&mut buf)?;
124 /// Represents the network as nodes and channels between them
125 pub struct NetworkGraph {
126 genesis_hash: BlockHash,
127 // Lock order: channels -> nodes
128 channels: RwLock<BTreeMap<u64, ChannelInfo>>,
129 nodes: RwLock<BTreeMap<NodeId, NodeInfo>>,
132 impl Clone for NetworkGraph {
133 fn clone(&self) -> Self {
134 let channels = self.channels.read().unwrap();
135 let nodes = self.nodes.read().unwrap();
137 genesis_hash: self.genesis_hash.clone(),
138 channels: RwLock::new(channels.clone()),
139 nodes: RwLock::new(nodes.clone()),
144 /// A read-only view of [`NetworkGraph`].
145 pub struct ReadOnlyNetworkGraph<'a> {
146 channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
147 nodes: RwLockReadGuard<'a, BTreeMap<NodeId, NodeInfo>>,
150 /// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
151 /// return packet by a node along the route. See [BOLT #4] for details.
153 /// [BOLT #4]: https://github.com/lightningnetwork/lightning-rfc/blob/master/04-onion-routing.md
154 #[derive(Clone, Debug, PartialEq)]
155 pub enum NetworkUpdate {
156 /// An error indicating a `channel_update` messages should be applied via
157 /// [`NetworkGraph::update_channel`].
158 ChannelUpdateMessage {
159 /// The update to apply via [`NetworkGraph::update_channel`].
162 /// An error indicating only that a channel has been closed, which should be applied via
163 /// [`NetworkGraph::close_channel_from_update`].
165 /// The short channel id of the closed channel.
166 short_channel_id: u64,
167 /// Whether the channel should be permanently removed or temporarily disabled until a new
168 /// `channel_update` message is received.
171 /// An error indicating only that a node has failed, which should be applied via
172 /// [`NetworkGraph::fail_node`].
174 /// The node id of the failed node.
176 /// Whether the node should be permanently removed from consideration or can be restored
177 /// when a new `channel_update` message is received.
182 impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
183 (0, ChannelUpdateMessage) => {
186 (2, ChannelClosed) => {
187 (0, short_channel_id, required),
188 (2, is_permanent, required),
190 (4, NodeFailure) => {
191 (0, node_id, required),
192 (2, is_permanent, required),
196 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> EventHandler for NetGraphMsgHandler<G, C, L>
197 where C::Target: chain::Access, L::Target: Logger {
198 fn handle_event(&self, event: &Event) {
199 if let Event::PaymentPathFailed { payment_hash: _, rejected_by_dest: _, network_update, .. } = event {
200 if let Some(network_update) = network_update {
201 self.handle_network_update(network_update);
207 /// Receives and validates network updates from peers,
208 /// stores authentic and relevant data as a network graph.
209 /// This network graph is then used for routing payments.
210 /// Provides interface to help with initial routing sync by
211 /// serving historical announcements.
213 /// Serves as an [`EventHandler`] for applying updates from [`Event::PaymentPathFailed`] to the
214 /// [`NetworkGraph`].
215 pub struct NetGraphMsgHandler<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref>
216 where C::Target: chain::Access, L::Target: Logger
218 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
220 chain_access: Option<C>,
221 full_syncs_requested: AtomicUsize,
222 pending_events: Mutex<Vec<MessageSendEvent>>,
226 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> NetGraphMsgHandler<G, C, L>
227 where C::Target: chain::Access, L::Target: Logger
229 /// Creates a new tracker of the actual state of the network of channels and nodes,
230 /// assuming an existing Network Graph.
231 /// Chain monitor is used to make sure announced channels exist on-chain,
232 /// channel data is correct, and that the announcement is signed with
233 /// channel owners' keys.
234 pub fn new(network_graph: G, chain_access: Option<C>, logger: L) -> Self {
236 secp_ctx: Secp256k1::verification_only(),
238 full_syncs_requested: AtomicUsize::new(0),
240 pending_events: Mutex::new(vec![]),
245 /// Adds a provider used to check new announcements. Does not affect
246 /// existing announcements unless they are updated.
247 /// Add, update or remove the provider would replace the current one.
248 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
249 self.chain_access = chain_access;
252 /// Gets a reference to the underlying [`NetworkGraph`] which was provided in
253 /// [`NetGraphMsgHandler::new`].
255 /// (C-not exported) as bindings don't support a reference-to-a-reference yet
256 pub fn network_graph(&self) -> &G {
260 /// Returns true when a full routing table sync should be performed with a peer.
261 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
262 //TODO: Determine whether to request a full sync based on the network map.
263 const FULL_SYNCS_TO_REQUEST: usize = 5;
264 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
265 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
272 /// Applies changes to the [`NetworkGraph`] from the given update.
273 fn handle_network_update(&self, update: &NetworkUpdate) {
275 NetworkUpdate::ChannelUpdateMessage { ref msg } => {
276 let short_channel_id = msg.contents.short_channel_id;
277 let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
278 let status = if is_enabled { "enabled" } else { "disabled" };
279 log_debug!(self.logger, "Updating channel with channel_update from a payment failure. Channel {} is {}.", short_channel_id, status);
280 let _ = self.network_graph.update_channel(msg, &self.secp_ctx);
282 NetworkUpdate::ChannelClosed { short_channel_id, is_permanent } => {
283 let action = if is_permanent { "Removing" } else { "Disabling" };
284 log_debug!(self.logger, "{} channel graph entry for {} due to a payment failure.", action, short_channel_id);
285 self.network_graph.close_channel_from_update(short_channel_id, is_permanent);
287 NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
288 let action = if is_permanent { "Removing" } else { "Disabling" };
289 log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", action, node_id);
290 self.network_graph.fail_node(node_id, is_permanent);
296 macro_rules! secp_verify_sig {
297 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
298 match $secp_ctx.verify($msg, $sig, $pubkey) {
300 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
305 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> RoutingMessageHandler for NetGraphMsgHandler<G, C, L>
306 where C::Target: chain::Access, L::Target: Logger
308 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
309 self.network_graph.update_node_from_announcement(msg, &self.secp_ctx)?;
310 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
311 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
312 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
315 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
316 self.network_graph.update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
317 log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
318 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
321 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
322 self.network_graph.update_channel(msg, &self.secp_ctx)?;
323 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
326 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
327 let mut result = Vec::with_capacity(batch_amount as usize);
328 let channels = self.network_graph.channels.read().unwrap();
329 let mut iter = channels.range(starting_point..);
330 while result.len() < batch_amount as usize {
331 if let Some((_, ref chan)) = iter.next() {
332 if chan.announcement_message.is_some() {
333 let chan_announcement = chan.announcement_message.clone().unwrap();
334 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
335 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
336 if let Some(one_to_two) = chan.one_to_two.as_ref() {
337 one_to_two_announcement = one_to_two.last_update_message.clone();
339 if let Some(two_to_one) = chan.two_to_one.as_ref() {
340 two_to_one_announcement = two_to_one.last_update_message.clone();
342 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
344 // TODO: We may end up sending un-announced channel_updates if we are sending
345 // initial sync data while receiving announce/updates for this channel.
354 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
355 let mut result = Vec::with_capacity(batch_amount as usize);
356 let nodes = self.network_graph.nodes.read().unwrap();
357 let mut iter = if let Some(pubkey) = starting_point {
358 let mut iter = nodes.range(NodeId::from_pubkey(pubkey)..);
362 nodes.range::<NodeId, _>(..)
364 while result.len() < batch_amount as usize {
365 if let Some((_, ref node)) = iter.next() {
366 if let Some(node_info) = node.announcement_info.as_ref() {
367 if node_info.announcement_message.is_some() {
368 result.push(node_info.announcement_message.clone().unwrap());
378 /// Initiates a stateless sync of routing gossip information with a peer
379 /// using gossip_queries. The default strategy used by this implementation
380 /// is to sync the full block range with several peers.
382 /// We should expect one or more reply_channel_range messages in response
383 /// to our query_channel_range. Each reply will enqueue a query_scid message
384 /// to request gossip messages for each channel. The sync is considered complete
385 /// when the final reply_scids_end message is received, though we are not
386 /// tracking this directly.
387 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
389 // We will only perform a sync with peers that support gossip_queries.
390 if !init_msg.features.supports_gossip_queries() {
394 // Check if we need to perform a full synchronization with this peer
395 if !self.should_request_full_sync(&their_node_id) {
399 let first_blocknum = 0;
400 let number_of_blocks = 0xffffffff;
401 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
402 let mut pending_events = self.pending_events.lock().unwrap();
403 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
404 node_id: their_node_id.clone(),
405 msg: QueryChannelRange {
406 chain_hash: self.network_graph.genesis_hash,
413 /// Statelessly processes a reply to a channel range query by immediately
414 /// sending an SCID query with SCIDs in the reply. To keep this handler
415 /// stateless, it does not validate the sequencing of replies for multi-
416 /// reply ranges. It does not validate whether the reply(ies) cover the
417 /// queried range. It also does not filter SCIDs to only those in the
418 /// original query range. We also do not validate that the chain_hash
419 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
420 /// does not match our chain_hash will be rejected when the announcement is
422 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
423 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(),);
425 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
426 let mut pending_events = self.pending_events.lock().unwrap();
427 pending_events.push(MessageSendEvent::SendShortIdsQuery {
428 node_id: their_node_id.clone(),
429 msg: QueryShortChannelIds {
430 chain_hash: msg.chain_hash,
431 short_channel_ids: msg.short_channel_ids,
438 /// When an SCID query is initiated the remote peer will begin streaming
439 /// gossip messages. In the event of a failure, we may have received
440 /// some channel information. Before trying with another peer, the
441 /// caller should update its set of SCIDs that need to be queried.
442 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
443 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
445 // If the remote node does not have up-to-date information for the
446 // chain_hash they will set full_information=false. We can fail
447 // the result and try again with a different peer.
448 if !msg.full_information {
449 return Err(LightningError {
450 err: String::from("Received reply_short_channel_ids_end with no information"),
451 action: ErrorAction::IgnoreError
458 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
459 /// are in the specified block range. Due to message size limits, large range
460 /// queries may result in several reply messages. This implementation enqueues
461 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
462 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
463 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
464 /// memory constrained systems.
465 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
466 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);
468 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
470 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
471 // If so, we manually cap the ending block to avoid this overflow.
472 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
474 // Per spec, we must reply to a query. Send an empty message when things are invalid.
475 if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
476 let mut pending_events = self.pending_events.lock().unwrap();
477 pending_events.push(MessageSendEvent::SendReplyChannelRange {
478 node_id: their_node_id.clone(),
479 msg: ReplyChannelRange {
480 chain_hash: msg.chain_hash.clone(),
481 first_blocknum: msg.first_blocknum,
482 number_of_blocks: msg.number_of_blocks,
484 short_channel_ids: vec![],
487 return Err(LightningError {
488 err: String::from("query_channel_range could not be processed"),
489 action: ErrorAction::IgnoreError,
493 // Creates channel batches. We are not checking if the channel is routable
494 // (has at least one update). A peer may still want to know the channel
495 // exists even if its not yet routable.
496 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
497 let channels = self.network_graph.channels.read().unwrap();
498 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
499 if let Some(chan_announcement) = &chan.announcement_message {
500 // Construct a new batch if last one is full
501 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
502 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
505 let batch = batches.last_mut().unwrap();
506 batch.push(chan_announcement.contents.short_channel_id);
511 let mut pending_events = self.pending_events.lock().unwrap();
512 let batch_count = batches.len();
513 let mut prev_batch_endblock = msg.first_blocknum;
514 for (batch_index, batch) in batches.into_iter().enumerate() {
515 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
516 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
518 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
519 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
520 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
521 // significant diversion from the requirements set by the spec, and, in case of blocks
522 // with no channel opens (e.g. empty blocks), requires that we use the previous value
523 // and *not* derive the first_blocknum from the actual first block of the reply.
524 let first_blocknum = prev_batch_endblock;
526 // Each message carries the number of blocks (from the `first_blocknum`) its contents
527 // fit in. Though there is no requirement that we use exactly the number of blocks its
528 // contents are from, except for the bogus requirements c-lightning enforces, above.
530 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
531 // >= the query's end block. Thus, for the last reply, we calculate the difference
532 // between the query's end block and the start of the reply.
534 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
535 // first_blocknum will be either msg.first_blocknum or a higher block height.
536 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
537 (true, msg.end_blocknum() - first_blocknum)
539 // Prior replies should use the number of blocks that fit into the reply. Overflow
540 // safe since first_blocknum is always <= last SCID's block.
542 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
545 prev_batch_endblock = first_blocknum + number_of_blocks;
547 pending_events.push(MessageSendEvent::SendReplyChannelRange {
548 node_id: their_node_id.clone(),
549 msg: ReplyChannelRange {
550 chain_hash: msg.chain_hash.clone(),
554 short_channel_ids: batch,
562 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
565 err: String::from("Not implemented"),
566 action: ErrorAction::IgnoreError,
571 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<G, C, L>
573 C::Target: chain::Access,
576 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
577 let mut ret = Vec::new();
578 let mut pending_events = self.pending_events.lock().unwrap();
579 core::mem::swap(&mut ret, &mut pending_events);
584 #[derive(Clone, Debug, PartialEq)]
585 /// Details about one direction of a channel. Received
586 /// within a channel update.
587 pub struct DirectionalChannelInfo {
588 /// When the last update to the channel direction was issued.
589 /// Value is opaque, as set in the announcement.
590 pub last_update: u32,
591 /// Whether the channel can be currently used for payments (in this one direction).
593 /// The difference in CLTV values that you must have when routing through this channel.
594 pub cltv_expiry_delta: u16,
595 /// The minimum value, which must be relayed to the next hop via the channel
596 pub htlc_minimum_msat: u64,
597 /// The maximum value which may be relayed to the next hop via the channel.
598 pub htlc_maximum_msat: Option<u64>,
599 /// Fees charged when the channel is used for routing
600 pub fees: RoutingFees,
601 /// Most recent update for the channel received from the network
602 /// Mostly redundant with the data we store in fields explicitly.
603 /// Everything else is useful only for sending out for initial routing sync.
604 /// Not stored if contains excess data to prevent DoS.
605 pub last_update_message: Option<ChannelUpdate>,
608 impl fmt::Display for DirectionalChannelInfo {
609 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
610 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)?;
615 impl_writeable_tlv_based!(DirectionalChannelInfo, {
616 (0, last_update, required),
617 (2, enabled, required),
618 (4, cltv_expiry_delta, required),
619 (6, htlc_minimum_msat, required),
620 (8, htlc_maximum_msat, required),
621 (10, fees, required),
622 (12, last_update_message, required),
625 #[derive(Clone, Debug, PartialEq)]
626 /// Details about a channel (both directions).
627 /// Received within a channel announcement.
628 pub struct ChannelInfo {
629 /// Protocol features of a channel communicated during its announcement
630 pub features: ChannelFeatures,
631 /// Source node of the first direction of a channel
632 pub node_one: NodeId,
633 /// Details about the first direction of a channel
634 pub one_to_two: Option<DirectionalChannelInfo>,
635 /// Source node of the second direction of a channel
636 pub node_two: NodeId,
637 /// Details about the second direction of a channel
638 pub two_to_one: Option<DirectionalChannelInfo>,
639 /// The channel capacity as seen on-chain, if chain lookup is available.
640 pub capacity_sats: Option<u64>,
641 /// An initial announcement of the channel
642 /// Mostly redundant with the data we store in fields explicitly.
643 /// Everything else is useful only for sending out for initial routing sync.
644 /// Not stored if contains excess data to prevent DoS.
645 pub announcement_message: Option<ChannelAnnouncement>,
646 /// The timestamp when we received the announcement, if we are running with feature = "std"
647 /// (which we can probably assume we are - no-std environments probably won't have a full
648 /// network graph in memory!).
649 announcement_received_time: u64,
652 impl fmt::Display for ChannelInfo {
653 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
654 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
655 log_bytes!(self.features.encode()), log_bytes!(self.node_one.as_slice()), self.one_to_two, log_bytes!(self.node_two.as_slice()), self.two_to_one)?;
660 impl_writeable_tlv_based!(ChannelInfo, {
661 (0, features, required),
662 (1, announcement_received_time, (default_value, 0)),
663 (2, node_one, required),
664 (4, one_to_two, required),
665 (6, node_two, required),
666 (8, two_to_one, required),
667 (10, capacity_sats, required),
668 (12, announcement_message, required),
672 /// Fees for routing via a given channel or a node
673 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
674 pub struct RoutingFees {
675 /// Flat routing fee in satoshis
677 /// Liquidity-based routing fee in millionths of a routed amount.
678 /// In other words, 10000 is 1%.
679 pub proportional_millionths: u32,
682 impl_writeable_tlv_based!(RoutingFees, {
683 (0, base_msat, required),
684 (2, proportional_millionths, required)
687 #[derive(Clone, Debug, PartialEq)]
688 /// Information received in the latest node_announcement from this node.
689 pub struct NodeAnnouncementInfo {
690 /// Protocol features the node announced support for
691 pub features: NodeFeatures,
692 /// When the last known update to the node state was issued.
693 /// Value is opaque, as set in the announcement.
694 pub last_update: u32,
695 /// Color assigned to the node
697 /// Moniker assigned to the node.
698 /// May be invalid or malicious (eg control chars),
699 /// should not be exposed to the user.
701 /// Internet-level addresses via which one can connect to the node
702 pub addresses: Vec<NetAddress>,
703 /// An initial announcement of the node
704 /// Mostly redundant with the data we store in fields explicitly.
705 /// Everything else is useful only for sending out for initial routing sync.
706 /// Not stored if contains excess data to prevent DoS.
707 pub announcement_message: Option<NodeAnnouncement>
710 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
711 (0, features, required),
712 (2, last_update, required),
714 (6, alias, required),
715 (8, announcement_message, option),
716 (10, addresses, vec_type),
719 #[derive(Clone, Debug, PartialEq)]
720 /// Details about a node in the network, known from the network announcement.
721 pub struct NodeInfo {
722 /// All valid channels a node has announced
723 pub channels: Vec<u64>,
724 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
725 /// The two fields (flat and proportional fee) are independent,
726 /// meaning they don't have to refer to the same channel.
727 pub lowest_inbound_channel_fees: Option<RoutingFees>,
728 /// More information about a node from node_announcement.
729 /// Optional because we store a Node entry after learning about it from
730 /// a channel announcement, but before receiving a node announcement.
731 pub announcement_info: Option<NodeAnnouncementInfo>
734 impl fmt::Display for NodeInfo {
735 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
736 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
737 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
742 impl_writeable_tlv_based!(NodeInfo, {
743 (0, lowest_inbound_channel_fees, option),
744 (2, announcement_info, option),
745 (4, channels, vec_type),
748 const SERIALIZATION_VERSION: u8 = 1;
749 const MIN_SERIALIZATION_VERSION: u8 = 1;
751 impl Writeable for NetworkGraph {
752 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
753 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
755 self.genesis_hash.write(writer)?;
756 let channels = self.channels.read().unwrap();
757 (channels.len() as u64).write(writer)?;
758 for (ref chan_id, ref chan_info) in channels.iter() {
759 (*chan_id).write(writer)?;
760 chan_info.write(writer)?;
762 let nodes = self.nodes.read().unwrap();
763 (nodes.len() as u64).write(writer)?;
764 for (ref node_id, ref node_info) in nodes.iter() {
765 node_id.write(writer)?;
766 node_info.write(writer)?;
769 write_tlv_fields!(writer, {});
774 impl Readable for NetworkGraph {
775 fn read<R: io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
776 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
778 let genesis_hash: BlockHash = Readable::read(reader)?;
779 let channels_count: u64 = Readable::read(reader)?;
780 let mut channels = BTreeMap::new();
781 for _ in 0..channels_count {
782 let chan_id: u64 = Readable::read(reader)?;
783 let chan_info = Readable::read(reader)?;
784 channels.insert(chan_id, chan_info);
786 let nodes_count: u64 = Readable::read(reader)?;
787 let mut nodes = BTreeMap::new();
788 for _ in 0..nodes_count {
789 let node_id = Readable::read(reader)?;
790 let node_info = Readable::read(reader)?;
791 nodes.insert(node_id, node_info);
793 read_tlv_fields!(reader, {});
797 channels: RwLock::new(channels),
798 nodes: RwLock::new(nodes),
803 impl fmt::Display for NetworkGraph {
804 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
805 writeln!(f, "Network map\n[Channels]")?;
806 for (key, val) in self.channels.read().unwrap().iter() {
807 writeln!(f, " {}: {}", key, val)?;
809 writeln!(f, "[Nodes]")?;
810 for (&node_id, val) in self.nodes.read().unwrap().iter() {
811 writeln!(f, " {}: {}", log_bytes!(node_id.as_slice()), val)?;
817 impl PartialEq for NetworkGraph {
818 fn eq(&self, other: &Self) -> bool {
819 self.genesis_hash == other.genesis_hash &&
820 *self.channels.read().unwrap() == *other.channels.read().unwrap() &&
821 *self.nodes.read().unwrap() == *other.nodes.read().unwrap()
826 /// Creates a new, empty, network graph.
827 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
830 channels: RwLock::new(BTreeMap::new()),
831 nodes: RwLock::new(BTreeMap::new()),
835 /// Returns a read-only view of the network graph.
836 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
837 let channels = self.channels.read().unwrap();
838 let nodes = self.nodes.read().unwrap();
839 ReadOnlyNetworkGraph {
845 /// For an already known node (from channel announcements), update its stored properties from a
846 /// given node announcement.
848 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
849 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
850 /// routing messages from a source using a protocol other than the lightning P2P protocol.
851 pub fn update_node_from_announcement<T: secp256k1::Verification>(&self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
852 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
853 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
854 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
857 /// For an already known node (from channel announcements), update its stored properties from a
858 /// given node announcement without verifying the associated signatures. Because we aren't
859 /// given the associated signatures here we cannot relay the node announcement to any of our
861 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
862 self.update_node_from_announcement_intern(msg, None)
865 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
866 match self.nodes.write().unwrap().get_mut(&NodeId::from_pubkey(&msg.node_id)) {
867 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
869 if let Some(node_info) = node.announcement_info.as_ref() {
870 // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
871 // updates to ensure you always have the latest one, only vaguely suggesting
872 // that it be at least the current time.
873 if node_info.last_update > msg.timestamp {
874 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
875 } else if node_info.last_update == msg.timestamp {
876 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
881 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
882 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
883 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
884 node.announcement_info = Some(NodeAnnouncementInfo {
885 features: msg.features.clone(),
886 last_update: msg.timestamp,
889 addresses: msg.addresses.clone(),
890 announcement_message: if should_relay { full_msg.cloned() } else { None },
898 /// Store or update channel info from a channel announcement.
900 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
901 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
902 /// routing messages from a source using a protocol other than the lightning P2P protocol.
904 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
905 /// the corresponding UTXO exists on chain and is correctly-formatted.
906 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>(
907 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>
908 ) -> Result<(), LightningError>
910 C::Target: chain::Access,
912 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
913 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
914 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
915 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
916 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
917 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
920 /// Store or update channel info from a channel announcement without verifying the associated
921 /// signatures. Because we aren't given the associated signatures here we cannot relay the
922 /// channel announcement to any of our peers.
924 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
925 /// the corresponding UTXO exists on chain and is correctly-formatted.
926 pub fn update_channel_from_unsigned_announcement<C: Deref>(
927 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
928 ) -> Result<(), LightningError>
930 C::Target: chain::Access,
932 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
935 fn update_channel_from_unsigned_announcement_intern<C: Deref>(
936 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
937 ) -> Result<(), LightningError>
939 C::Target: chain::Access,
941 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
942 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
945 let utxo_value = match &chain_access {
947 // Tentatively accept, potentially exposing us to DoS attacks
950 &Some(ref chain_access) => {
951 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
952 Ok(TxOut { value, script_pubkey }) => {
953 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
954 .push_slice(&msg.bitcoin_key_1.serialize())
955 .push_slice(&msg.bitcoin_key_2.serialize())
956 .push_opcode(opcodes::all::OP_PUSHNUM_2)
957 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
958 if script_pubkey != expected_script {
959 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});
961 //TODO: Check if value is worth storing, use it to inform routing, and compare it
962 //to the new HTLC max field in channel_update
965 Err(chain::AccessError::UnknownChain) => {
966 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
968 Err(chain::AccessError::UnknownTx) => {
969 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
975 #[allow(unused_mut, unused_assignments)]
976 let mut announcement_received_time = 0;
977 #[cfg(feature = "std")]
979 announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
982 let chan_info = ChannelInfo {
983 features: msg.features.clone(),
984 node_one: NodeId::from_pubkey(&msg.node_id_1),
986 node_two: NodeId::from_pubkey(&msg.node_id_2),
988 capacity_sats: utxo_value,
989 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
990 { full_msg.cloned() } else { None },
991 announcement_received_time,
994 let mut channels = self.channels.write().unwrap();
995 let mut nodes = self.nodes.write().unwrap();
996 match channels.entry(msg.short_channel_id) {
997 BtreeEntry::Occupied(mut entry) => {
998 //TODO: because asking the blockchain if short_channel_id is valid is only optional
999 //in the blockchain API, we need to handle it smartly here, though it's unclear
1001 if utxo_value.is_some() {
1002 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1003 // only sometimes returns results. In any case remove the previous entry. Note
1004 // that the spec expects us to "blacklist" the node_ids involved, but we can't
1006 // a) we don't *require* a UTXO provider that always returns results.
1007 // b) we don't track UTXOs of channels we know about and remove them if they
1009 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1010 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), msg.short_channel_id);
1011 *entry.get_mut() = chan_info;
1013 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1016 BtreeEntry::Vacant(entry) => {
1017 entry.insert(chan_info);
1021 macro_rules! add_channel_to_node {
1022 ( $node_id: expr ) => {
1023 match nodes.entry($node_id) {
1024 BtreeEntry::Occupied(node_entry) => {
1025 node_entry.into_mut().channels.push(msg.short_channel_id);
1027 BtreeEntry::Vacant(node_entry) => {
1028 node_entry.insert(NodeInfo {
1029 channels: vec!(msg.short_channel_id),
1030 lowest_inbound_channel_fees: None,
1031 announcement_info: None,
1038 add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_1));
1039 add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_2));
1044 /// Close a channel if a corresponding HTLC fail was sent.
1045 /// If permanent, removes a channel from the local storage.
1046 /// May cause the removal of nodes too, if this was their last channel.
1047 /// If not permanent, makes channels unavailable for routing.
1048 pub fn close_channel_from_update(&self, short_channel_id: u64, is_permanent: bool) {
1049 let mut channels = self.channels.write().unwrap();
1051 if let Some(chan) = channels.remove(&short_channel_id) {
1052 let mut nodes = self.nodes.write().unwrap();
1053 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1056 if let Some(chan) = channels.get_mut(&short_channel_id) {
1057 if let Some(one_to_two) = chan.one_to_two.as_mut() {
1058 one_to_two.enabled = false;
1060 if let Some(two_to_one) = chan.two_to_one.as_mut() {
1061 two_to_one.enabled = false;
1067 /// Marks a node in the graph as failed.
1068 pub fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
1070 // TODO: Wholly remove the node
1072 // TODO: downgrade the node
1076 #[cfg(feature = "std")]
1077 /// Removes information about channels that we haven't heard any updates about in some time.
1078 /// This can be used regularly to prune the network graph of channels that likely no longer
1081 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1082 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1083 /// pruning occur for updates which are at least two weeks old, which we implement here.
1085 /// Note that for users of the `lightning-background-processor` crate this method may be
1086 /// automatically called regularly for you.
1088 /// This method is only available with the `std` feature. See
1089 /// [`NetworkGraph::remove_stale_channels_with_time`] for `no-std` use.
1090 pub fn remove_stale_channels(&self) {
1091 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1092 self.remove_stale_channels_with_time(time);
1095 /// Removes information about channels that we haven't heard any updates about in some time.
1096 /// This can be used regularly to prune the network graph of channels that likely no longer
1099 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1100 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1101 /// pruning occur for updates which are at least two weeks old, which we implement here.
1103 /// This function takes the current unix time as an argument. For users with the `std` feature
1104 /// enabled, [`NetworkGraph::remove_stale_channels`] may be preferable.
1105 pub fn remove_stale_channels_with_time(&self, current_time_unix: u64) {
1106 let mut channels = self.channels.write().unwrap();
1107 // Time out if we haven't received an update in at least 14 days.
1108 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1109 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1110 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1111 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1113 let mut scids_to_remove = Vec::new();
1114 for (scid, info) in channels.iter_mut() {
1115 if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1116 info.one_to_two = None;
1118 if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1119 info.two_to_one = None;
1121 if info.one_to_two.is_none() && info.two_to_one.is_none() {
1122 // We check the announcement_received_time here to ensure we don't drop
1123 // announcements that we just received and are just waiting for our peer to send a
1124 // channel_update for.
1125 if info.announcement_received_time < min_time_unix as u64 {
1126 scids_to_remove.push(*scid);
1130 if !scids_to_remove.is_empty() {
1131 let mut nodes = self.nodes.write().unwrap();
1132 for scid in scids_to_remove {
1133 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1134 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
1139 /// For an already known (from announcement) channel, update info about one of the directions
1142 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1143 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1144 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1146 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1147 /// materially in the future will be rejected.
1148 pub fn update_channel<T: secp256k1::Verification>(&self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
1149 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
1152 /// For an already known (from announcement) channel, update info about one of the directions
1153 /// of the channel without verifying the associated signatures. Because we aren't given the
1154 /// associated signatures here we cannot relay the channel update to any of our peers.
1156 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1157 /// materially in the future will be rejected.
1158 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1159 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
1162 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> {
1164 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
1165 let chan_was_enabled;
1167 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
1169 // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
1170 // disable this check during tests!
1171 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1172 if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
1173 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreError});
1175 if msg.timestamp as u64 > time + 60 * 60 * 24 {
1176 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreError});
1180 let mut channels = self.channels.write().unwrap();
1181 match channels.get_mut(&msg.short_channel_id) {
1182 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
1184 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
1185 if htlc_maximum_msat > MAX_VALUE_MSAT {
1186 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
1189 if let Some(capacity_sats) = channel.capacity_sats {
1190 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1191 // Don't query UTXO set here to reduce DoS risks.
1192 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1193 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1197 macro_rules! maybe_update_channel_info {
1198 ( $target: expr, $src_node: expr) => {
1199 if let Some(existing_chan_info) = $target.as_ref() {
1200 // The timestamp field is somewhat of a misnomer - the BOLTs use it to
1201 // order updates to ensure you always have the latest one, only
1202 // suggesting that it be at least the current time. For
1203 // channel_updates specifically, the BOLTs discuss the possibility of
1204 // pruning based on the timestamp field being more than two weeks old,
1205 // but only in the non-normative section.
1206 if existing_chan_info.last_update > msg.timestamp {
1207 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1208 } else if existing_chan_info.last_update == msg.timestamp {
1209 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1211 chan_was_enabled = existing_chan_info.enabled;
1213 chan_was_enabled = false;
1216 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1217 { full_msg.cloned() } else { None };
1219 let updated_channel_dir_info = DirectionalChannelInfo {
1220 enabled: chan_enabled,
1221 last_update: msg.timestamp,
1222 cltv_expiry_delta: msg.cltv_expiry_delta,
1223 htlc_minimum_msat: msg.htlc_minimum_msat,
1224 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1226 base_msat: msg.fee_base_msat,
1227 proportional_millionths: msg.fee_proportional_millionths,
1231 $target = Some(updated_channel_dir_info);
1235 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1236 if msg.flags & 1 == 1 {
1237 dest_node_id = channel.node_one.clone();
1238 if let Some((sig, ctx)) = sig_info {
1239 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
1240 err: "Couldn't parse source node pubkey".to_owned(),
1241 action: ErrorAction::IgnoreAndLog(Level::Debug)
1244 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1246 dest_node_id = channel.node_two.clone();
1247 if let Some((sig, ctx)) = sig_info {
1248 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
1249 err: "Couldn't parse destination node pubkey".to_owned(),
1250 action: ErrorAction::IgnoreAndLog(Level::Debug)
1253 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1258 let mut nodes = self.nodes.write().unwrap();
1260 let node = nodes.get_mut(&dest_node_id).unwrap();
1261 let mut base_msat = msg.fee_base_msat;
1262 let mut proportional_millionths = msg.fee_proportional_millionths;
1263 if let Some(fees) = node.lowest_inbound_channel_fees {
1264 base_msat = cmp::min(base_msat, fees.base_msat);
1265 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1267 node.lowest_inbound_channel_fees = Some(RoutingFees {
1269 proportional_millionths
1271 } else if chan_was_enabled {
1272 let node = nodes.get_mut(&dest_node_id).unwrap();
1273 let mut lowest_inbound_channel_fees = None;
1275 for chan_id in node.channels.iter() {
1276 let chan = channels.get(chan_id).unwrap();
1278 if chan.node_one == dest_node_id {
1279 chan_info_opt = chan.two_to_one.as_ref();
1281 chan_info_opt = chan.one_to_two.as_ref();
1283 if let Some(chan_info) = chan_info_opt {
1284 if chan_info.enabled {
1285 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1286 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1287 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1288 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1293 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1299 fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1300 macro_rules! remove_from_node {
1301 ($node_id: expr) => {
1302 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1303 entry.get_mut().channels.retain(|chan_id| {
1304 short_channel_id != *chan_id
1306 if entry.get().channels.is_empty() {
1307 entry.remove_entry();
1310 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1315 remove_from_node!(chan.node_one);
1316 remove_from_node!(chan.node_two);
1320 impl ReadOnlyNetworkGraph<'_> {
1321 /// Returns all known valid channels' short ids along with announced channel info.
1323 /// (C-not exported) because we have no mapping for `BTreeMap`s
1324 pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1328 /// Returns all known nodes' public keys along with announced node info.
1330 /// (C-not exported) because we have no mapping for `BTreeMap`s
1331 pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
1335 /// Get network addresses by node id.
1336 /// Returns None if the requested node is completely unknown,
1337 /// or if node announcement for the node was never received.
1338 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
1339 if let Some(node) = self.nodes.get(&NodeId::from_pubkey(&pubkey)) {
1340 if let Some(node_info) = node.announcement_info.as_ref() {
1341 return Some(node_info.addresses.clone())
1351 use ln::PaymentHash;
1352 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1353 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, NetworkUpdate, MAX_EXCESS_BYTES_FOR_RELAY};
1354 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1355 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
1356 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1357 use util::test_utils;
1358 use util::logger::Logger;
1359 use util::ser::{Readable, Writeable};
1360 use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
1361 use util::scid_utils::scid_from_parts;
1363 use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
1365 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1366 use bitcoin::hashes::Hash;
1367 use bitcoin::network::constants::Network;
1368 use bitcoin::blockdata::constants::genesis_block;
1369 use bitcoin::blockdata::script::{Builder, Script};
1370 use bitcoin::blockdata::transaction::TxOut;
1371 use bitcoin::blockdata::opcodes;
1375 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1376 use bitcoin::secp256k1::{All, Secp256k1};
1382 fn create_network_graph() -> NetworkGraph {
1383 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1384 NetworkGraph::new(genesis_hash)
1387 fn create_net_graph_msg_handler(network_graph: &NetworkGraph) -> (
1388 Secp256k1<All>, NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
1390 let secp_ctx = Secp256k1::new();
1391 let logger = Arc::new(test_utils::TestLogger::new());
1392 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1393 (secp_ctx, net_graph_msg_handler)
1397 fn request_full_sync_finite_times() {
1398 let network_graph = create_network_graph();
1399 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1400 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1402 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1403 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1404 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1405 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1406 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1407 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1410 fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
1411 let node_id = PublicKey::from_secret_key(&secp_ctx, node_key);
1412 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1413 features: NodeFeatures::known(),
1418 addresses: Vec::new(),
1419 excess_address_data: Vec::new(),
1420 excess_data: Vec::new(),
1422 f(&mut unsigned_announcement);
1423 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1425 signature: secp_ctx.sign(&msghash, node_key),
1426 contents: unsigned_announcement
1430 fn get_signed_channel_announcement<F: Fn(&mut UnsignedChannelAnnouncement)>(f: F, node_1_key: &SecretKey, node_2_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelAnnouncement {
1431 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
1432 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
1433 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1434 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1436 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1437 features: ChannelFeatures::known(),
1438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1439 short_channel_id: 0,
1442 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1443 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1444 excess_data: Vec::new(),
1446 f(&mut unsigned_announcement);
1447 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1448 ChannelAnnouncement {
1449 node_signature_1: secp_ctx.sign(&msghash, node_1_key),
1450 node_signature_2: secp_ctx.sign(&msghash, node_2_key),
1451 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1452 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1453 contents: unsigned_announcement,
1457 fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> Script {
1458 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1459 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1460 Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1461 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1462 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1463 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1464 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
1468 fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
1469 let mut unsigned_channel_update = UnsignedChannelUpdate {
1470 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1471 short_channel_id: 0,
1474 cltv_expiry_delta: 144,
1475 htlc_minimum_msat: 1_000_000,
1476 htlc_maximum_msat: OptionalField::Absent,
1477 fee_base_msat: 10_000,
1478 fee_proportional_millionths: 20,
1479 excess_data: Vec::new()
1481 f(&mut unsigned_channel_update);
1482 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1484 signature: secp_ctx.sign(&msghash, node_key),
1485 contents: unsigned_channel_update
1490 fn handling_node_announcements() {
1491 let network_graph = create_network_graph();
1492 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1494 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1495 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1496 let zero_hash = Sha256dHash::hash(&[0; 32]);
1498 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
1499 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1501 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1505 // Announce a channel to add a corresponding node.
1506 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1507 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1508 Ok(res) => assert!(res),
1513 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1514 Ok(res) => assert!(res),
1518 let fake_msghash = hash_to_message!(&zero_hash);
1519 match net_graph_msg_handler.handle_node_announcement(
1521 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1522 contents: valid_announcement.contents.clone()
1525 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1528 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
1529 unsigned_announcement.timestamp += 1000;
1530 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1531 }, node_1_privkey, &secp_ctx);
1532 // Return false because contains excess data.
1533 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1534 Ok(res) => assert!(!res),
1538 // Even though previous announcement was not relayed further, we still accepted it,
1539 // so we now won't accept announcements before the previous one.
1540 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
1541 unsigned_announcement.timestamp += 1000 - 10;
1542 }, node_1_privkey, &secp_ctx);
1543 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1545 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1550 fn handling_channel_announcements() {
1551 let secp_ctx = Secp256k1::new();
1552 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1554 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1555 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1557 let good_script = get_channel_script(&secp_ctx);
1558 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1560 // Test if the UTXO lookups were not supported
1561 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1562 let mut net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, None, Arc::clone(&logger));
1563 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1564 Ok(res) => assert!(res),
1569 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1575 // If we receive announcement for the same channel (with UTXO lookups disabled),
1576 // drop new one on the floor, since we can't see any changes.
1577 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1579 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1582 // Test if an associated transaction were not on-chain (or not confirmed).
1583 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1584 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1585 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1586 net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1588 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1589 unsigned_announcement.short_channel_id += 1;
1590 }, node_1_privkey, node_2_privkey, &secp_ctx);
1591 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1593 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1596 // Now test if the transaction is found in the UTXO set and the script is correct.
1597 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1598 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1599 unsigned_announcement.short_channel_id += 2;
1600 }, node_1_privkey, node_2_privkey, &secp_ctx);
1601 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1602 Ok(res) => assert!(res),
1607 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1613 // If we receive announcement for the same channel (but TX is not confirmed),
1614 // drop new one on the floor, since we can't see any changes.
1615 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1616 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1618 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1621 // But if it is confirmed, replace the channel
1622 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1623 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1624 unsigned_announcement.features = ChannelFeatures::empty();
1625 unsigned_announcement.short_channel_id += 2;
1626 }, node_1_privkey, node_2_privkey, &secp_ctx);
1627 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1628 Ok(res) => assert!(res),
1632 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1633 Some(channel_entry) => {
1634 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1640 // Don't relay valid channels with excess data
1641 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1642 unsigned_announcement.short_channel_id += 3;
1643 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1644 }, node_1_privkey, node_2_privkey, &secp_ctx);
1645 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1646 Ok(res) => assert!(!res),
1650 let mut invalid_sig_announcement = valid_announcement.clone();
1651 invalid_sig_announcement.contents.excess_data = Vec::new();
1652 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1654 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1657 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
1658 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1660 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1665 fn handling_channel_update() {
1666 let secp_ctx = Secp256k1::new();
1667 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1668 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1669 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1670 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1672 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1673 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1675 let amount_sats = 1000_000;
1676 let short_channel_id;
1679 // Announce a channel we will update
1680 let good_script = get_channel_script(&secp_ctx);
1681 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1683 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1684 short_channel_id = valid_channel_announcement.contents.short_channel_id;
1685 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1692 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1693 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1694 Ok(res) => assert!(res),
1699 match network_graph.read_only().channels().get(&short_channel_id) {
1701 Some(channel_info) => {
1702 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1703 assert!(channel_info.two_to_one.is_none());
1708 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1709 unsigned_channel_update.timestamp += 100;
1710 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1711 }, node_1_privkey, &secp_ctx);
1712 // Return false because contains excess data
1713 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1714 Ok(res) => assert!(!res),
1718 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1719 unsigned_channel_update.timestamp += 110;
1720 unsigned_channel_update.short_channel_id += 1;
1721 }, node_1_privkey, &secp_ctx);
1722 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1724 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1727 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1728 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1729 unsigned_channel_update.timestamp += 110;
1730 }, node_1_privkey, &secp_ctx);
1731 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1733 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1736 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1737 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1738 unsigned_channel_update.timestamp += 110;
1739 }, node_1_privkey, &secp_ctx);
1740 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1742 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1745 // Even though previous update was not relayed further, we still accepted it,
1746 // so we now won't accept update before the previous one.
1747 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1748 unsigned_channel_update.timestamp += 100;
1749 }, node_1_privkey, &secp_ctx);
1750 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1752 Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
1755 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1756 unsigned_channel_update.timestamp += 500;
1757 }, node_1_privkey, &secp_ctx);
1758 let zero_hash = Sha256dHash::hash(&[0; 32]);
1759 let fake_msghash = hash_to_message!(&zero_hash);
1760 invalid_sig_channel_update.signature = secp_ctx.sign(&fake_msghash, node_1_privkey);
1761 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1763 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1768 fn handling_network_update() {
1769 let logger = test_utils::TestLogger::new();
1770 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1771 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1772 let network_graph = NetworkGraph::new(genesis_hash);
1773 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
1774 let secp_ctx = Secp256k1::new();
1776 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1777 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1780 // There is no nodes in the table at the beginning.
1781 assert_eq!(network_graph.read_only().nodes().len(), 0);
1784 let short_channel_id;
1786 // Announce a channel we will update
1787 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1788 short_channel_id = valid_channel_announcement.contents.short_channel_id;
1789 let chain_source: Option<&test_utils::TestChainSource> = None;
1790 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
1791 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
1793 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1794 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
1796 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1798 payment_hash: PaymentHash([0; 32]),
1799 rejected_by_dest: false,
1800 all_paths_failed: true,
1802 network_update: Some(NetworkUpdate::ChannelUpdateMessage {
1803 msg: valid_channel_update,
1805 short_channel_id: None,
1811 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
1814 // Non-permanent closing just disables a channel
1816 match network_graph.read_only().channels().get(&short_channel_id) {
1818 Some(channel_info) => {
1819 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
1823 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1825 payment_hash: PaymentHash([0; 32]),
1826 rejected_by_dest: false,
1827 all_paths_failed: true,
1829 network_update: Some(NetworkUpdate::ChannelClosed {
1831 is_permanent: false,
1833 short_channel_id: None,
1839 match network_graph.read_only().channels().get(&short_channel_id) {
1841 Some(channel_info) => {
1842 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1847 // Permanent closing deletes a channel
1848 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1850 payment_hash: PaymentHash([0; 32]),
1851 rejected_by_dest: false,
1852 all_paths_failed: true,
1854 network_update: Some(NetworkUpdate::ChannelClosed {
1858 short_channel_id: None,
1864 assert_eq!(network_graph.read_only().channels().len(), 0);
1865 // Nodes are also deleted because there are no associated channels anymore
1866 assert_eq!(network_graph.read_only().nodes().len(), 0);
1867 // TODO: Test NetworkUpdate::NodeFailure, which is not implemented yet.
1871 fn test_channel_timeouts() {
1872 // Test the removal of channels with `remove_stale_channels`.
1873 let logger = test_utils::TestLogger::new();
1874 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1875 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1876 let network_graph = NetworkGraph::new(genesis_hash);
1877 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
1878 let secp_ctx = Secp256k1::new();
1880 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1881 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1883 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1884 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
1885 let chain_source: Option<&test_utils::TestChainSource> = None;
1886 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
1887 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
1889 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1890 assert!(net_graph_msg_handler.handle_channel_update(&valid_channel_update).is_ok());
1891 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
1893 network_graph.remove_stale_channels_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
1894 assert_eq!(network_graph.read_only().channels().len(), 1);
1895 assert_eq!(network_graph.read_only().nodes().len(), 2);
1897 network_graph.remove_stale_channels_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
1898 #[cfg(feature = "std")]
1900 // In std mode, a further check is performed before fully removing the channel -
1901 // the channel_announcement must have been received at least two weeks ago. We
1902 // fudge that here by indicating the time has jumped two weeks. Note that the
1903 // directional channel information will have been removed already..
1904 assert_eq!(network_graph.read_only().channels().len(), 1);
1905 assert_eq!(network_graph.read_only().nodes().len(), 2);
1906 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
1908 use std::time::{SystemTime, UNIX_EPOCH};
1909 let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1910 network_graph.remove_stale_channels_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
1913 assert_eq!(network_graph.read_only().channels().len(), 0);
1914 assert_eq!(network_graph.read_only().nodes().len(), 0);
1918 fn getting_next_channel_announcements() {
1919 let network_graph = create_network_graph();
1920 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1921 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1922 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1924 // Channels were not announced yet.
1925 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1926 assert_eq!(channels_with_announcements.len(), 0);
1928 let short_channel_id;
1930 // Announce a channel we will update
1931 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1932 short_channel_id = valid_channel_announcement.contents.short_channel_id;
1933 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1939 // Contains initial channel announcement now.
1940 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1941 assert_eq!(channels_with_announcements.len(), 1);
1942 if let Some(channel_announcements) = channels_with_announcements.first() {
1943 let &(_, ref update_1, ref update_2) = channel_announcements;
1944 assert_eq!(update_1, &None);
1945 assert_eq!(update_2, &None);
1952 // Valid channel update
1953 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1954 unsigned_channel_update.timestamp = 101;
1955 }, node_1_privkey, &secp_ctx);
1956 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1962 // Now contains an initial announcement and an update.
1963 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1964 assert_eq!(channels_with_announcements.len(), 1);
1965 if let Some(channel_announcements) = channels_with_announcements.first() {
1966 let &(_, ref update_1, ref update_2) = channel_announcements;
1967 assert_ne!(update_1, &None);
1968 assert_eq!(update_2, &None);
1974 // Channel update with excess data.
1975 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1976 unsigned_channel_update.timestamp = 102;
1977 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
1978 }, node_1_privkey, &secp_ctx);
1979 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1985 // Test that announcements with excess data won't be returned
1986 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1987 assert_eq!(channels_with_announcements.len(), 1);
1988 if let Some(channel_announcements) = channels_with_announcements.first() {
1989 let &(_, ref update_1, ref update_2) = channel_announcements;
1990 assert_eq!(update_1, &None);
1991 assert_eq!(update_2, &None);
1996 // Further starting point have no channels after it
1997 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1998 assert_eq!(channels_with_announcements.len(), 0);
2002 fn getting_next_node_announcements() {
2003 let network_graph = create_network_graph();
2004 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2005 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2006 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2007 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2010 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
2011 assert_eq!(next_announcements.len(), 0);
2014 // Announce a channel to add 2 nodes
2015 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2016 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2023 // Nodes were never announced
2024 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2025 assert_eq!(next_announcements.len(), 0);
2028 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2029 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2034 let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
2035 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2041 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2042 assert_eq!(next_announcements.len(), 2);
2044 // Skip the first node.
2045 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2046 assert_eq!(next_announcements.len(), 1);
2049 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2050 let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
2051 unsigned_announcement.timestamp += 10;
2052 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2053 }, node_2_privkey, &secp_ctx);
2054 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2055 Ok(res) => assert!(!res),
2060 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2061 assert_eq!(next_announcements.len(), 0);
2065 fn network_graph_serialization() {
2066 let network_graph = create_network_graph();
2067 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2069 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2070 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2072 // Announce a channel to add a corresponding node.
2073 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2074 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2075 Ok(res) => assert!(res),
2079 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2080 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2085 let mut w = test_utils::TestVecWriter(Vec::new());
2086 assert!(!network_graph.read_only().nodes().is_empty());
2087 assert!(!network_graph.read_only().channels().is_empty());
2088 network_graph.write(&mut w).unwrap();
2089 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == network_graph);
2093 fn calling_sync_routing_table() {
2094 let network_graph = create_network_graph();
2095 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2096 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2097 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2099 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2100 let first_blocknum = 0;
2101 let number_of_blocks = 0xffff_ffff;
2103 // It should ignore if gossip_queries feature is not enabled
2105 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2106 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2107 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2108 assert_eq!(events.len(), 0);
2111 // It should send a query_channel_message with the correct information
2113 let init_msg = Init { features: InitFeatures::known() };
2114 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2115 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2116 assert_eq!(events.len(), 1);
2118 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2119 assert_eq!(node_id, &node_id_1);
2120 assert_eq!(msg.chain_hash, chain_hash);
2121 assert_eq!(msg.first_blocknum, first_blocknum);
2122 assert_eq!(msg.number_of_blocks, number_of_blocks);
2124 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2128 // It should not enqueue a query when should_request_full_sync return false.
2129 // The initial implementation allows syncing with the first 5 peers after
2130 // which should_request_full_sync will return false
2132 let network_graph = create_network_graph();
2133 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2134 let init_msg = Init { features: InitFeatures::known() };
2136 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2137 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2138 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2139 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2141 assert_eq!(events.len(), 1);
2143 assert_eq!(events.len(), 0);
2151 fn handling_reply_channel_range() {
2152 let network_graph = create_network_graph();
2153 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2154 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2155 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2157 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2159 // Test receipt of a single reply that should enqueue an SCID query
2160 // matching the SCIDs in the reply
2162 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2164 sync_complete: true,
2166 number_of_blocks: 2000,
2167 short_channel_ids: vec![
2168 0x0003e0_000000_0000, // 992x0x0
2169 0x0003e8_000000_0000, // 1000x0x0
2170 0x0003e9_000000_0000, // 1001x0x0
2171 0x0003f0_000000_0000, // 1008x0x0
2172 0x00044c_000000_0000, // 1100x0x0
2173 0x0006e0_000000_0000, // 1760x0x0
2176 assert!(result.is_ok());
2178 // We expect to emit a query_short_channel_ids message with the received scids
2179 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2180 assert_eq!(events.len(), 1);
2182 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2183 assert_eq!(node_id, &node_id_1);
2184 assert_eq!(msg.chain_hash, chain_hash);
2185 assert_eq!(msg.short_channel_ids, vec![
2186 0x0003e0_000000_0000, // 992x0x0
2187 0x0003e8_000000_0000, // 1000x0x0
2188 0x0003e9_000000_0000, // 1001x0x0
2189 0x0003f0_000000_0000, // 1008x0x0
2190 0x00044c_000000_0000, // 1100x0x0
2191 0x0006e0_000000_0000, // 1760x0x0
2194 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2200 fn handling_reply_short_channel_ids() {
2201 let network_graph = create_network_graph();
2202 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2203 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2204 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2206 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2208 // Test receipt of a successful reply
2210 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2212 full_information: true,
2214 assert!(result.is_ok());
2217 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2218 // for the chain_hash requested in the query.
2220 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2222 full_information: false,
2224 assert!(result.is_err());
2225 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2230 fn handling_query_channel_range() {
2231 let network_graph = create_network_graph();
2232 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2234 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2235 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2236 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2237 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2239 let mut scids: Vec<u64> = vec![
2240 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2241 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2244 // used for testing multipart reply across blocks
2245 for block in 100000..=108001 {
2246 scids.push(scid_from_parts(block, 0, 0).unwrap());
2249 // used for testing resumption on same block
2250 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2253 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2254 unsigned_announcement.short_channel_id = scid;
2255 }, node_1_privkey, node_2_privkey, &secp_ctx);
2256 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2262 // Error when number_of_blocks=0
2263 do_handling_query_channel_range(
2264 &net_graph_msg_handler,
2267 chain_hash: chain_hash.clone(),
2269 number_of_blocks: 0,
2272 vec![ReplyChannelRange {
2273 chain_hash: chain_hash.clone(),
2275 number_of_blocks: 0,
2276 sync_complete: true,
2277 short_channel_ids: vec![]
2281 // Error when wrong chain
2282 do_handling_query_channel_range(
2283 &net_graph_msg_handler,
2286 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2288 number_of_blocks: 0xffff_ffff,
2291 vec![ReplyChannelRange {
2292 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2294 number_of_blocks: 0xffff_ffff,
2295 sync_complete: true,
2296 short_channel_ids: vec![],
2300 // Error when first_blocknum > 0xffffff
2301 do_handling_query_channel_range(
2302 &net_graph_msg_handler,
2305 chain_hash: chain_hash.clone(),
2306 first_blocknum: 0x01000000,
2307 number_of_blocks: 0xffff_ffff,
2310 vec![ReplyChannelRange {
2311 chain_hash: chain_hash.clone(),
2312 first_blocknum: 0x01000000,
2313 number_of_blocks: 0xffff_ffff,
2314 sync_complete: true,
2315 short_channel_ids: vec![]
2319 // Empty reply when max valid SCID block num
2320 do_handling_query_channel_range(
2321 &net_graph_msg_handler,
2324 chain_hash: chain_hash.clone(),
2325 first_blocknum: 0xffffff,
2326 number_of_blocks: 1,
2331 chain_hash: chain_hash.clone(),
2332 first_blocknum: 0xffffff,
2333 number_of_blocks: 1,
2334 sync_complete: true,
2335 short_channel_ids: vec![]
2340 // No results in valid query range
2341 do_handling_query_channel_range(
2342 &net_graph_msg_handler,
2345 chain_hash: chain_hash.clone(),
2346 first_blocknum: 1000,
2347 number_of_blocks: 1000,
2352 chain_hash: chain_hash.clone(),
2353 first_blocknum: 1000,
2354 number_of_blocks: 1000,
2355 sync_complete: true,
2356 short_channel_ids: vec![],
2361 // Overflow first_blocknum + number_of_blocks
2362 do_handling_query_channel_range(
2363 &net_graph_msg_handler,
2366 chain_hash: chain_hash.clone(),
2367 first_blocknum: 0xfe0000,
2368 number_of_blocks: 0xffffffff,
2373 chain_hash: chain_hash.clone(),
2374 first_blocknum: 0xfe0000,
2375 number_of_blocks: 0xffffffff - 0xfe0000,
2376 sync_complete: true,
2377 short_channel_ids: vec![
2378 0xfffffe_ffffff_ffff, // max
2384 // Single block exactly full
2385 do_handling_query_channel_range(
2386 &net_graph_msg_handler,
2389 chain_hash: chain_hash.clone(),
2390 first_blocknum: 100000,
2391 number_of_blocks: 8000,
2396 chain_hash: chain_hash.clone(),
2397 first_blocknum: 100000,
2398 number_of_blocks: 8000,
2399 sync_complete: true,
2400 short_channel_ids: (100000..=107999)
2401 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2407 // Multiple split on new block
2408 do_handling_query_channel_range(
2409 &net_graph_msg_handler,
2412 chain_hash: chain_hash.clone(),
2413 first_blocknum: 100000,
2414 number_of_blocks: 8001,
2419 chain_hash: chain_hash.clone(),
2420 first_blocknum: 100000,
2421 number_of_blocks: 7999,
2422 sync_complete: false,
2423 short_channel_ids: (100000..=107999)
2424 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2428 chain_hash: chain_hash.clone(),
2429 first_blocknum: 107999,
2430 number_of_blocks: 2,
2431 sync_complete: true,
2432 short_channel_ids: vec![
2433 scid_from_parts(108000, 0, 0).unwrap(),
2439 // Multiple split on same block
2440 do_handling_query_channel_range(
2441 &net_graph_msg_handler,
2444 chain_hash: chain_hash.clone(),
2445 first_blocknum: 100002,
2446 number_of_blocks: 8000,
2451 chain_hash: chain_hash.clone(),
2452 first_blocknum: 100002,
2453 number_of_blocks: 7999,
2454 sync_complete: false,
2455 short_channel_ids: (100002..=108001)
2456 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2460 chain_hash: chain_hash.clone(),
2461 first_blocknum: 108001,
2462 number_of_blocks: 1,
2463 sync_complete: true,
2464 short_channel_ids: vec![
2465 scid_from_parts(108001, 1, 0).unwrap(),
2472 fn do_handling_query_channel_range(
2473 net_graph_msg_handler: &NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2474 test_node_id: &PublicKey,
2475 msg: QueryChannelRange,
2477 expected_replies: Vec<ReplyChannelRange>
2479 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2480 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2481 let query_end_blocknum = msg.end_blocknum();
2482 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2485 assert!(result.is_ok());
2487 assert!(result.is_err());
2490 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2491 assert_eq!(events.len(), expected_replies.len());
2493 for i in 0..events.len() {
2494 let expected_reply = &expected_replies[i];
2496 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2497 assert_eq!(node_id, test_node_id);
2498 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2499 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2500 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2501 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2502 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2504 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2505 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2506 assert!(msg.first_blocknum >= max_firstblocknum);
2507 max_firstblocknum = msg.first_blocknum;
2508 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2510 // Check that the last block count is >= the query's end_blocknum
2511 if i == events.len() - 1 {
2512 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2515 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2521 fn handling_query_short_channel_ids() {
2522 let network_graph = create_network_graph();
2523 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2524 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2525 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2527 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2529 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2531 short_channel_ids: vec![0x0003e8_000000_0000],
2533 assert!(result.is_err());
2537 #[cfg(all(test, feature = "unstable"))]
2545 fn read_network_graph(bench: &mut Bencher) {
2546 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2547 let mut v = Vec::new();
2548 d.read_to_end(&mut v).unwrap();
2550 let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2555 fn write_network_graph(bench: &mut Bencher) {
2556 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2557 let net_graph = NetworkGraph::read(&mut d).unwrap();
2559 let _ = net_graph.encode();