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, $msg_type: expr ) => {
298 match $secp_ctx.verify($msg, $sig, $pubkey) {
301 return Err(LightningError {
302 err: format!("Invalid signature on {} message", $msg_type),
303 action: ErrorAction::SendWarningMessage {
304 msg: msgs::WarningMessage {
306 data: format!("Invalid signature on {} message", $msg_type),
308 log_level: Level::Trace,
316 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> RoutingMessageHandler for NetGraphMsgHandler<G, C, L>
317 where C::Target: chain::Access, L::Target: Logger
319 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
320 self.network_graph.update_node_from_announcement(msg, &self.secp_ctx)?;
321 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
322 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
323 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
326 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
327 self.network_graph.update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
328 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 { "" });
329 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
332 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
333 self.network_graph.update_channel(msg, &self.secp_ctx)?;
334 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
337 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
338 let mut result = Vec::with_capacity(batch_amount as usize);
339 let channels = self.network_graph.channels.read().unwrap();
340 let mut iter = channels.range(starting_point..);
341 while result.len() < batch_amount as usize {
342 if let Some((_, ref chan)) = iter.next() {
343 if chan.announcement_message.is_some() {
344 let chan_announcement = chan.announcement_message.clone().unwrap();
345 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
346 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
347 if let Some(one_to_two) = chan.one_to_two.as_ref() {
348 one_to_two_announcement = one_to_two.last_update_message.clone();
350 if let Some(two_to_one) = chan.two_to_one.as_ref() {
351 two_to_one_announcement = two_to_one.last_update_message.clone();
353 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
355 // TODO: We may end up sending un-announced channel_updates if we are sending
356 // initial sync data while receiving announce/updates for this channel.
365 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
366 let mut result = Vec::with_capacity(batch_amount as usize);
367 let nodes = self.network_graph.nodes.read().unwrap();
368 let mut iter = if let Some(pubkey) = starting_point {
369 let mut iter = nodes.range(NodeId::from_pubkey(pubkey)..);
373 nodes.range::<NodeId, _>(..)
375 while result.len() < batch_amount as usize {
376 if let Some((_, ref node)) = iter.next() {
377 if let Some(node_info) = node.announcement_info.as_ref() {
378 if node_info.announcement_message.is_some() {
379 result.push(node_info.announcement_message.clone().unwrap());
389 /// Initiates a stateless sync of routing gossip information with a peer
390 /// using gossip_queries. The default strategy used by this implementation
391 /// is to sync the full block range with several peers.
393 /// We should expect one or more reply_channel_range messages in response
394 /// to our query_channel_range. Each reply will enqueue a query_scid message
395 /// to request gossip messages for each channel. The sync is considered complete
396 /// when the final reply_scids_end message is received, though we are not
397 /// tracking this directly.
398 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
400 // We will only perform a sync with peers that support gossip_queries.
401 if !init_msg.features.supports_gossip_queries() {
405 // Check if we need to perform a full synchronization with this peer
406 if !self.should_request_full_sync(&their_node_id) {
410 let first_blocknum = 0;
411 let number_of_blocks = 0xffffffff;
412 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
413 let mut pending_events = self.pending_events.lock().unwrap();
414 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
415 node_id: their_node_id.clone(),
416 msg: QueryChannelRange {
417 chain_hash: self.network_graph.genesis_hash,
424 /// Statelessly processes a reply to a channel range query by immediately
425 /// sending an SCID query with SCIDs in the reply. To keep this handler
426 /// stateless, it does not validate the sequencing of replies for multi-
427 /// reply ranges. It does not validate whether the reply(ies) cover the
428 /// queried range. It also does not filter SCIDs to only those in the
429 /// original query range. We also do not validate that the chain_hash
430 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
431 /// does not match our chain_hash will be rejected when the announcement is
433 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
434 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(),);
436 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
437 let mut pending_events = self.pending_events.lock().unwrap();
438 pending_events.push(MessageSendEvent::SendShortIdsQuery {
439 node_id: their_node_id.clone(),
440 msg: QueryShortChannelIds {
441 chain_hash: msg.chain_hash,
442 short_channel_ids: msg.short_channel_ids,
449 /// When an SCID query is initiated the remote peer will begin streaming
450 /// gossip messages. In the event of a failure, we may have received
451 /// some channel information. Before trying with another peer, the
452 /// caller should update its set of SCIDs that need to be queried.
453 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
454 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
456 // If the remote node does not have up-to-date information for the
457 // chain_hash they will set full_information=false. We can fail
458 // the result and try again with a different peer.
459 if !msg.full_information {
460 return Err(LightningError {
461 err: String::from("Received reply_short_channel_ids_end with no information"),
462 action: ErrorAction::IgnoreError
469 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
470 /// are in the specified block range. Due to message size limits, large range
471 /// queries may result in several reply messages. This implementation enqueues
472 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
473 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
474 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
475 /// memory constrained systems.
476 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
477 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);
479 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
481 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
482 // If so, we manually cap the ending block to avoid this overflow.
483 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
485 // Per spec, we must reply to a query. Send an empty message when things are invalid.
486 if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
487 let mut pending_events = self.pending_events.lock().unwrap();
488 pending_events.push(MessageSendEvent::SendReplyChannelRange {
489 node_id: their_node_id.clone(),
490 msg: ReplyChannelRange {
491 chain_hash: msg.chain_hash.clone(),
492 first_blocknum: msg.first_blocknum,
493 number_of_blocks: msg.number_of_blocks,
495 short_channel_ids: vec![],
498 return Err(LightningError {
499 err: String::from("query_channel_range could not be processed"),
500 action: ErrorAction::IgnoreError,
504 // Creates channel batches. We are not checking if the channel is routable
505 // (has at least one update). A peer may still want to know the channel
506 // exists even if its not yet routable.
507 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
508 let channels = self.network_graph.channels.read().unwrap();
509 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
510 if let Some(chan_announcement) = &chan.announcement_message {
511 // Construct a new batch if last one is full
512 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
513 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
516 let batch = batches.last_mut().unwrap();
517 batch.push(chan_announcement.contents.short_channel_id);
522 let mut pending_events = self.pending_events.lock().unwrap();
523 let batch_count = batches.len();
524 let mut prev_batch_endblock = msg.first_blocknum;
525 for (batch_index, batch) in batches.into_iter().enumerate() {
526 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
527 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
529 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
530 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
531 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
532 // significant diversion from the requirements set by the spec, and, in case of blocks
533 // with no channel opens (e.g. empty blocks), requires that we use the previous value
534 // and *not* derive the first_blocknum from the actual first block of the reply.
535 let first_blocknum = prev_batch_endblock;
537 // Each message carries the number of blocks (from the `first_blocknum`) its contents
538 // fit in. Though there is no requirement that we use exactly the number of blocks its
539 // contents are from, except for the bogus requirements c-lightning enforces, above.
541 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
542 // >= the query's end block. Thus, for the last reply, we calculate the difference
543 // between the query's end block and the start of the reply.
545 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
546 // first_blocknum will be either msg.first_blocknum or a higher block height.
547 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
548 (true, msg.end_blocknum() - first_blocknum)
550 // Prior replies should use the number of blocks that fit into the reply. Overflow
551 // safe since first_blocknum is always <= last SCID's block.
553 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
556 prev_batch_endblock = first_blocknum + number_of_blocks;
558 pending_events.push(MessageSendEvent::SendReplyChannelRange {
559 node_id: their_node_id.clone(),
560 msg: ReplyChannelRange {
561 chain_hash: msg.chain_hash.clone(),
565 short_channel_ids: batch,
573 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
576 err: String::from("Not implemented"),
577 action: ErrorAction::IgnoreError,
582 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<G, C, L>
584 C::Target: chain::Access,
587 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
588 let mut ret = Vec::new();
589 let mut pending_events = self.pending_events.lock().unwrap();
590 core::mem::swap(&mut ret, &mut pending_events);
595 #[derive(Clone, Debug, PartialEq)]
596 /// Details about one direction of a channel as received within a [`ChannelUpdate`].
597 pub struct ChannelUpdateInfo {
598 /// When the last update to the channel direction was issued.
599 /// Value is opaque, as set in the announcement.
600 pub last_update: u32,
601 /// Whether the channel can be currently used for payments (in this one direction).
603 /// The difference in CLTV values that you must have when routing through this channel.
604 pub cltv_expiry_delta: u16,
605 /// The minimum value, which must be relayed to the next hop via the channel
606 pub htlc_minimum_msat: u64,
607 /// The maximum value which may be relayed to the next hop via the channel.
608 pub htlc_maximum_msat: Option<u64>,
609 /// Fees charged when the channel is used for routing
610 pub fees: RoutingFees,
611 /// Most recent update for the channel received from the network
612 /// Mostly redundant with the data we store in fields explicitly.
613 /// Everything else is useful only for sending out for initial routing sync.
614 /// Not stored if contains excess data to prevent DoS.
615 pub last_update_message: Option<ChannelUpdate>,
618 impl fmt::Display for ChannelUpdateInfo {
619 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
620 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)?;
625 impl_writeable_tlv_based!(ChannelUpdateInfo, {
626 (0, last_update, required),
627 (2, enabled, required),
628 (4, cltv_expiry_delta, required),
629 (6, htlc_minimum_msat, required),
630 (8, htlc_maximum_msat, required),
631 (10, fees, required),
632 (12, last_update_message, required),
635 #[derive(Clone, Debug, PartialEq)]
636 /// Details about a channel (both directions).
637 /// Received within a channel announcement.
638 pub struct ChannelInfo {
639 /// Protocol features of a channel communicated during its announcement
640 pub features: ChannelFeatures,
641 /// Source node of the first direction of a channel
642 pub node_one: NodeId,
643 /// Details about the first direction of a channel
644 pub one_to_two: Option<ChannelUpdateInfo>,
645 /// Source node of the second direction of a channel
646 pub node_two: NodeId,
647 /// Details about the second direction of a channel
648 pub two_to_one: Option<ChannelUpdateInfo>,
649 /// The channel capacity as seen on-chain, if chain lookup is available.
650 pub capacity_sats: Option<u64>,
651 /// An initial announcement of the channel
652 /// Mostly redundant with the data we store in fields explicitly.
653 /// Everything else is useful only for sending out for initial routing sync.
654 /// Not stored if contains excess data to prevent DoS.
655 pub announcement_message: Option<ChannelAnnouncement>,
656 /// The timestamp when we received the announcement, if we are running with feature = "std"
657 /// (which we can probably assume we are - no-std environments probably won't have a full
658 /// network graph in memory!).
659 announcement_received_time: u64,
663 /// Returns a [`DirectedChannelInfo`] for the channel directed to the given `target`, or `None`
664 /// if `target` is not one of the channel's counterparties.
665 pub fn as_directed_to(&self, target: &NodeId) -> Option<DirectedChannelInfo> {
666 let (direction, source, target) = {
667 if target == &self.node_one {
668 (self.two_to_one.as_ref(), &self.node_two, &self.node_one)
669 } else if target == &self.node_two {
670 (self.one_to_two.as_ref(), &self.node_one, &self.node_two)
675 Some(DirectedChannelInfo { channel: self, direction, source, target })
679 impl fmt::Display for ChannelInfo {
680 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
681 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
682 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)?;
687 impl_writeable_tlv_based!(ChannelInfo, {
688 (0, features, required),
689 (1, announcement_received_time, (default_value, 0)),
690 (2, node_one, required),
691 (4, one_to_two, required),
692 (6, node_two, required),
693 (8, two_to_one, required),
694 (10, capacity_sats, required),
695 (12, announcement_message, required),
698 /// A wrapper around [`ChannelInfo`] representing information about the channel as directed from a
699 /// source node to a target node.
700 #[derive(Clone, Debug)]
701 pub struct DirectedChannelInfo<'a: 'b, 'b> {
702 channel: &'a ChannelInfo,
703 direction: Option<&'b ChannelUpdateInfo>,
708 impl<'a: 'b, 'b> DirectedChannelInfo<'a, 'b> {
709 /// Returns information for the channel.
710 pub fn channel(&self) -> &'a ChannelInfo { self.channel }
712 /// Returns information for the direction.
713 pub fn direction(&self) -> Option<&'b ChannelUpdateInfo> { self.direction }
715 /// Returns the node id for the source.
716 pub fn source(&self) -> &'b NodeId { self.source }
718 /// Returns the node id for the target.
719 pub fn target(&self) -> &'b NodeId { self.target }
721 /// Returns the [`EffectiveCapacity`] of the channel in a specific direction.
723 /// This is either the total capacity from the funding transaction, if known, or the
724 /// `htlc_maximum_msat` for the direction as advertised by the gossip network, if known,
725 /// whichever is smaller.
726 pub fn effective_capacity(&self) -> EffectiveCapacity {
727 let capacity_msat = self.channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000);
729 .and_then(|direction| direction.htlc_maximum_msat)
730 .map(|max_htlc_msat| {
731 let capacity_msat = capacity_msat.unwrap_or(u64::max_value());
732 if max_htlc_msat < capacity_msat {
733 EffectiveCapacity::MaximumHTLC { amount_msat: max_htlc_msat }
735 EffectiveCapacity::Total { capacity_msat }
738 .or_else(|| capacity_msat.map(|capacity_msat|
739 EffectiveCapacity::Total { capacity_msat }))
740 .unwrap_or(EffectiveCapacity::Unknown)
744 /// The effective capacity of a channel for routing purposes.
746 /// While this may be smaller than the actual channel capacity, amounts greater than
747 /// [`Self::as_msat`] should not be routed through the channel.
748 pub enum EffectiveCapacity {
749 /// The available liquidity in the channel known from being a channel counterparty, and thus a
752 /// Either the inbound or outbound liquidity depending on the direction, denominated in
756 /// The maximum HTLC amount in one direction as advertised on the gossip network.
758 /// The maximum HTLC amount denominated in millisatoshi.
761 /// The total capacity of the channel as determined by the funding transaction.
763 /// The funding amount denominated in millisatoshi.
766 /// A capacity sufficient to route any payment, typically used for private channels provided by
767 /// an invoice, though may not be the case for zero-amount invoices.
769 /// A capacity that is unknown possibly because either the chain state is unavailable to know
770 /// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
774 /// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
775 /// use when making routing decisions.
776 pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
778 impl EffectiveCapacity {
779 /// Returns the effective capacity denominated in millisatoshi.
780 pub fn as_msat(&self) -> u64 {
782 EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
783 EffectiveCapacity::MaximumHTLC { amount_msat } => *amount_msat,
784 EffectiveCapacity::Total { capacity_msat } => *capacity_msat,
785 EffectiveCapacity::Infinite => u64::max_value(),
786 EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
791 /// Fees for routing via a given channel or a node
792 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
793 pub struct RoutingFees {
794 /// Flat routing fee in satoshis
796 /// Liquidity-based routing fee in millionths of a routed amount.
797 /// In other words, 10000 is 1%.
798 pub proportional_millionths: u32,
801 impl_writeable_tlv_based!(RoutingFees, {
802 (0, base_msat, required),
803 (2, proportional_millionths, required)
806 #[derive(Clone, Debug, PartialEq)]
807 /// Information received in the latest node_announcement from this node.
808 pub struct NodeAnnouncementInfo {
809 /// Protocol features the node announced support for
810 pub features: NodeFeatures,
811 /// When the last known update to the node state was issued.
812 /// Value is opaque, as set in the announcement.
813 pub last_update: u32,
814 /// Color assigned to the node
816 /// Moniker assigned to the node.
817 /// May be invalid or malicious (eg control chars),
818 /// should not be exposed to the user.
820 /// Internet-level addresses via which one can connect to the node
821 pub addresses: Vec<NetAddress>,
822 /// An initial announcement of the node
823 /// Mostly redundant with the data we store in fields explicitly.
824 /// Everything else is useful only for sending out for initial routing sync.
825 /// Not stored if contains excess data to prevent DoS.
826 pub announcement_message: Option<NodeAnnouncement>
829 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
830 (0, features, required),
831 (2, last_update, required),
833 (6, alias, required),
834 (8, announcement_message, option),
835 (10, addresses, vec_type),
838 #[derive(Clone, Debug, PartialEq)]
839 /// Details about a node in the network, known from the network announcement.
840 pub struct NodeInfo {
841 /// All valid channels a node has announced
842 pub channels: Vec<u64>,
843 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
844 /// The two fields (flat and proportional fee) are independent,
845 /// meaning they don't have to refer to the same channel.
846 pub lowest_inbound_channel_fees: Option<RoutingFees>,
847 /// More information about a node from node_announcement.
848 /// Optional because we store a Node entry after learning about it from
849 /// a channel announcement, but before receiving a node announcement.
850 pub announcement_info: Option<NodeAnnouncementInfo>
853 impl fmt::Display for NodeInfo {
854 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
855 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
856 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
861 impl_writeable_tlv_based!(NodeInfo, {
862 (0, lowest_inbound_channel_fees, option),
863 (2, announcement_info, option),
864 (4, channels, vec_type),
867 const SERIALIZATION_VERSION: u8 = 1;
868 const MIN_SERIALIZATION_VERSION: u8 = 1;
870 impl Writeable for NetworkGraph {
871 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
872 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
874 self.genesis_hash.write(writer)?;
875 let channels = self.channels.read().unwrap();
876 (channels.len() as u64).write(writer)?;
877 for (ref chan_id, ref chan_info) in channels.iter() {
878 (*chan_id).write(writer)?;
879 chan_info.write(writer)?;
881 let nodes = self.nodes.read().unwrap();
882 (nodes.len() as u64).write(writer)?;
883 for (ref node_id, ref node_info) in nodes.iter() {
884 node_id.write(writer)?;
885 node_info.write(writer)?;
888 write_tlv_fields!(writer, {});
893 impl Readable for NetworkGraph {
894 fn read<R: io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
895 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
897 let genesis_hash: BlockHash = Readable::read(reader)?;
898 let channels_count: u64 = Readable::read(reader)?;
899 let mut channels = BTreeMap::new();
900 for _ in 0..channels_count {
901 let chan_id: u64 = Readable::read(reader)?;
902 let chan_info = Readable::read(reader)?;
903 channels.insert(chan_id, chan_info);
905 let nodes_count: u64 = Readable::read(reader)?;
906 let mut nodes = BTreeMap::new();
907 for _ in 0..nodes_count {
908 let node_id = Readable::read(reader)?;
909 let node_info = Readable::read(reader)?;
910 nodes.insert(node_id, node_info);
912 read_tlv_fields!(reader, {});
916 channels: RwLock::new(channels),
917 nodes: RwLock::new(nodes),
922 impl fmt::Display for NetworkGraph {
923 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
924 writeln!(f, "Network map\n[Channels]")?;
925 for (key, val) in self.channels.read().unwrap().iter() {
926 writeln!(f, " {}: {}", key, val)?;
928 writeln!(f, "[Nodes]")?;
929 for (&node_id, val) in self.nodes.read().unwrap().iter() {
930 writeln!(f, " {}: {}", log_bytes!(node_id.as_slice()), val)?;
936 impl PartialEq for NetworkGraph {
937 fn eq(&self, other: &Self) -> bool {
938 self.genesis_hash == other.genesis_hash &&
939 *self.channels.read().unwrap() == *other.channels.read().unwrap() &&
940 *self.nodes.read().unwrap() == *other.nodes.read().unwrap()
945 /// Creates a new, empty, network graph.
946 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
949 channels: RwLock::new(BTreeMap::new()),
950 nodes: RwLock::new(BTreeMap::new()),
954 /// Returns a read-only view of the network graph.
955 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
956 let channels = self.channels.read().unwrap();
957 let nodes = self.nodes.read().unwrap();
958 ReadOnlyNetworkGraph {
964 /// For an already known node (from channel announcements), update its stored properties from a
965 /// given node announcement.
967 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
968 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
969 /// routing messages from a source using a protocol other than the lightning P2P protocol.
970 pub fn update_node_from_announcement<T: secp256k1::Verification>(&self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
971 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
972 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id, "node_announcement");
973 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
976 /// For an already known node (from channel announcements), update its stored properties from a
977 /// given node announcement without verifying the associated signatures. Because we aren't
978 /// given the associated signatures here we cannot relay the node announcement to any of our
980 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
981 self.update_node_from_announcement_intern(msg, None)
984 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
985 match self.nodes.write().unwrap().get_mut(&NodeId::from_pubkey(&msg.node_id)) {
986 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
988 if let Some(node_info) = node.announcement_info.as_ref() {
989 // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
990 // updates to ensure you always have the latest one, only vaguely suggesting
991 // that it be at least the current time.
992 if node_info.last_update > msg.timestamp {
993 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
994 } else if node_info.last_update == msg.timestamp {
995 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1000 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1001 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1002 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1003 node.announcement_info = Some(NodeAnnouncementInfo {
1004 features: msg.features.clone(),
1005 last_update: msg.timestamp,
1008 addresses: msg.addresses.clone(),
1009 announcement_message: if should_relay { full_msg.cloned() } else { None },
1017 /// Store or update channel info from a channel announcement.
1019 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1020 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1021 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1023 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1024 /// the corresponding UTXO exists on chain and is correctly-formatted.
1025 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>(
1026 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>
1027 ) -> Result<(), LightningError>
1029 C::Target: chain::Access,
1031 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
1032 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1, "channel_announcement");
1033 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2, "channel_announcement");
1034 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1, "channel_announcement");
1035 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2, "channel_announcement");
1036 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
1039 /// Store or update channel info from a channel announcement without verifying the associated
1040 /// signatures. Because we aren't given the associated signatures here we cannot relay the
1041 /// channel announcement to any of our peers.
1043 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1044 /// the corresponding UTXO exists on chain and is correctly-formatted.
1045 pub fn update_channel_from_unsigned_announcement<C: Deref>(
1046 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
1047 ) -> Result<(), LightningError>
1049 C::Target: chain::Access,
1051 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
1054 fn update_channel_from_unsigned_announcement_intern<C: Deref>(
1055 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
1056 ) -> Result<(), LightningError>
1058 C::Target: chain::Access,
1060 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1061 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1064 let utxo_value = match &chain_access {
1066 // Tentatively accept, potentially exposing us to DoS attacks
1069 &Some(ref chain_access) => {
1070 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
1071 Ok(TxOut { value, script_pubkey }) => {
1072 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1073 .push_slice(&msg.bitcoin_key_1.serialize())
1074 .push_slice(&msg.bitcoin_key_2.serialize())
1075 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1076 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1077 if script_pubkey != expected_script {
1078 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});
1080 //TODO: Check if value is worth storing, use it to inform routing, and compare it
1081 //to the new HTLC max field in channel_update
1084 Err(chain::AccessError::UnknownChain) => {
1085 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
1087 Err(chain::AccessError::UnknownTx) => {
1088 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
1094 #[allow(unused_mut, unused_assignments)]
1095 let mut announcement_received_time = 0;
1096 #[cfg(feature = "std")]
1098 announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1101 let chan_info = ChannelInfo {
1102 features: msg.features.clone(),
1103 node_one: NodeId::from_pubkey(&msg.node_id_1),
1105 node_two: NodeId::from_pubkey(&msg.node_id_2),
1107 capacity_sats: utxo_value,
1108 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1109 { full_msg.cloned() } else { None },
1110 announcement_received_time,
1113 let mut channels = self.channels.write().unwrap();
1114 let mut nodes = self.nodes.write().unwrap();
1115 match channels.entry(msg.short_channel_id) {
1116 BtreeEntry::Occupied(mut entry) => {
1117 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1118 //in the blockchain API, we need to handle it smartly here, though it's unclear
1120 if utxo_value.is_some() {
1121 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1122 // only sometimes returns results. In any case remove the previous entry. Note
1123 // that the spec expects us to "blacklist" the node_ids involved, but we can't
1125 // a) we don't *require* a UTXO provider that always returns results.
1126 // b) we don't track UTXOs of channels we know about and remove them if they
1128 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1129 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), msg.short_channel_id);
1130 *entry.get_mut() = chan_info;
1132 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1135 BtreeEntry::Vacant(entry) => {
1136 entry.insert(chan_info);
1140 macro_rules! add_channel_to_node {
1141 ( $node_id: expr ) => {
1142 match nodes.entry($node_id) {
1143 BtreeEntry::Occupied(node_entry) => {
1144 node_entry.into_mut().channels.push(msg.short_channel_id);
1146 BtreeEntry::Vacant(node_entry) => {
1147 node_entry.insert(NodeInfo {
1148 channels: vec!(msg.short_channel_id),
1149 lowest_inbound_channel_fees: None,
1150 announcement_info: None,
1157 add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_1));
1158 add_channel_to_node!(NodeId::from_pubkey(&msg.node_id_2));
1163 /// Close a channel if a corresponding HTLC fail was sent.
1164 /// If permanent, removes a channel from the local storage.
1165 /// May cause the removal of nodes too, if this was their last channel.
1166 /// If not permanent, makes channels unavailable for routing.
1167 pub fn close_channel_from_update(&self, short_channel_id: u64, is_permanent: bool) {
1168 let mut channels = self.channels.write().unwrap();
1170 if let Some(chan) = channels.remove(&short_channel_id) {
1171 let mut nodes = self.nodes.write().unwrap();
1172 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1175 if let Some(chan) = channels.get_mut(&short_channel_id) {
1176 if let Some(one_to_two) = chan.one_to_two.as_mut() {
1177 one_to_two.enabled = false;
1179 if let Some(two_to_one) = chan.two_to_one.as_mut() {
1180 two_to_one.enabled = false;
1186 /// Marks a node in the graph as failed.
1187 pub fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
1189 // TODO: Wholly remove the node
1191 // TODO: downgrade the node
1195 #[cfg(feature = "std")]
1196 /// Removes information about channels that we haven't heard any updates about in some time.
1197 /// This can be used regularly to prune the network graph of channels that likely no longer
1200 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1201 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1202 /// pruning occur for updates which are at least two weeks old, which we implement here.
1204 /// Note that for users of the `lightning-background-processor` crate this method may be
1205 /// automatically called regularly for you.
1207 /// This method is only available with the `std` feature. See
1208 /// [`NetworkGraph::remove_stale_channels_with_time`] for `no-std` use.
1209 pub fn remove_stale_channels(&self) {
1210 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1211 self.remove_stale_channels_with_time(time);
1214 /// Removes information about channels that we haven't heard any updates about in some time.
1215 /// This can be used regularly to prune the network graph of channels that likely no longer
1218 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1219 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1220 /// pruning occur for updates which are at least two weeks old, which we implement here.
1222 /// This function takes the current unix time as an argument. For users with the `std` feature
1223 /// enabled, [`NetworkGraph::remove_stale_channels`] may be preferable.
1224 pub fn remove_stale_channels_with_time(&self, current_time_unix: u64) {
1225 let mut channels = self.channels.write().unwrap();
1226 // Time out if we haven't received an update in at least 14 days.
1227 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1228 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1229 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1230 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1232 let mut scids_to_remove = Vec::new();
1233 for (scid, info) in channels.iter_mut() {
1234 if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1235 info.one_to_two = None;
1237 if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1238 info.two_to_one = None;
1240 if info.one_to_two.is_none() && info.two_to_one.is_none() {
1241 // We check the announcement_received_time here to ensure we don't drop
1242 // announcements that we just received and are just waiting for our peer to send a
1243 // channel_update for.
1244 if info.announcement_received_time < min_time_unix as u64 {
1245 scids_to_remove.push(*scid);
1249 if !scids_to_remove.is_empty() {
1250 let mut nodes = self.nodes.write().unwrap();
1251 for scid in scids_to_remove {
1252 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1253 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
1258 /// For an already known (from announcement) channel, update info about one of the directions
1261 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1262 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1263 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1265 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1266 /// materially in the future will be rejected.
1267 pub fn update_channel<T: secp256k1::Verification>(&self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
1268 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
1271 /// For an already known (from announcement) channel, update info about one of the directions
1272 /// of the channel without verifying the associated signatures. Because we aren't given the
1273 /// associated signatures here we cannot relay the channel update to any of our peers.
1275 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1276 /// materially in the future will be rejected.
1277 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1278 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
1281 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> {
1283 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
1284 let chan_was_enabled;
1286 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
1288 // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
1289 // disable this check during tests!
1290 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1291 if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
1292 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1294 if msg.timestamp as u64 > time + 60 * 60 * 24 {
1295 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1299 let mut channels = self.channels.write().unwrap();
1300 match channels.get_mut(&msg.short_channel_id) {
1301 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
1303 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
1304 if htlc_maximum_msat > MAX_VALUE_MSAT {
1305 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
1308 if let Some(capacity_sats) = channel.capacity_sats {
1309 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1310 // Don't query UTXO set here to reduce DoS risks.
1311 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1312 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1316 macro_rules! maybe_update_channel_info {
1317 ( $target: expr, $src_node: expr) => {
1318 if let Some(existing_chan_info) = $target.as_ref() {
1319 // The timestamp field is somewhat of a misnomer - the BOLTs use it to
1320 // order updates to ensure you always have the latest one, only
1321 // suggesting that it be at least the current time. For
1322 // channel_updates specifically, the BOLTs discuss the possibility of
1323 // pruning based on the timestamp field being more than two weeks old,
1324 // but only in the non-normative section.
1325 if existing_chan_info.last_update > msg.timestamp {
1326 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1327 } else if existing_chan_info.last_update == msg.timestamp {
1328 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1330 chan_was_enabled = existing_chan_info.enabled;
1332 chan_was_enabled = false;
1335 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1336 { full_msg.cloned() } else { None };
1338 let updated_channel_update_info = ChannelUpdateInfo {
1339 enabled: chan_enabled,
1340 last_update: msg.timestamp,
1341 cltv_expiry_delta: msg.cltv_expiry_delta,
1342 htlc_minimum_msat: msg.htlc_minimum_msat,
1343 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1345 base_msat: msg.fee_base_msat,
1346 proportional_millionths: msg.fee_proportional_millionths,
1350 $target = Some(updated_channel_update_info);
1354 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1355 if msg.flags & 1 == 1 {
1356 dest_node_id = channel.node_one.clone();
1357 if let Some((sig, ctx)) = sig_info {
1358 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
1359 err: "Couldn't parse source node pubkey".to_owned(),
1360 action: ErrorAction::IgnoreAndLog(Level::Debug)
1361 })?, "channel_update");
1363 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1365 dest_node_id = channel.node_two.clone();
1366 if let Some((sig, ctx)) = sig_info {
1367 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
1368 err: "Couldn't parse destination node pubkey".to_owned(),
1369 action: ErrorAction::IgnoreAndLog(Level::Debug)
1370 })?, "channel_update");
1372 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1377 let mut nodes = self.nodes.write().unwrap();
1379 let node = nodes.get_mut(&dest_node_id).unwrap();
1380 let mut base_msat = msg.fee_base_msat;
1381 let mut proportional_millionths = msg.fee_proportional_millionths;
1382 if let Some(fees) = node.lowest_inbound_channel_fees {
1383 base_msat = cmp::min(base_msat, fees.base_msat);
1384 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1386 node.lowest_inbound_channel_fees = Some(RoutingFees {
1388 proportional_millionths
1390 } else if chan_was_enabled {
1391 let node = nodes.get_mut(&dest_node_id).unwrap();
1392 let mut lowest_inbound_channel_fees = None;
1394 for chan_id in node.channels.iter() {
1395 let chan = channels.get(chan_id).unwrap();
1397 if chan.node_one == dest_node_id {
1398 chan_info_opt = chan.two_to_one.as_ref();
1400 chan_info_opt = chan.one_to_two.as_ref();
1402 if let Some(chan_info) = chan_info_opt {
1403 if chan_info.enabled {
1404 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1405 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1406 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1407 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1412 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1418 fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1419 macro_rules! remove_from_node {
1420 ($node_id: expr) => {
1421 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1422 entry.get_mut().channels.retain(|chan_id| {
1423 short_channel_id != *chan_id
1425 if entry.get().channels.is_empty() {
1426 entry.remove_entry();
1429 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1434 remove_from_node!(chan.node_one);
1435 remove_from_node!(chan.node_two);
1439 impl ReadOnlyNetworkGraph<'_> {
1440 /// Returns all known valid channels' short ids along with announced channel info.
1442 /// (C-not exported) because we have no mapping for `BTreeMap`s
1443 pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1447 /// Returns all known nodes' public keys along with announced node info.
1449 /// (C-not exported) because we have no mapping for `BTreeMap`s
1450 pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
1454 /// Get network addresses by node id.
1455 /// Returns None if the requested node is completely unknown,
1456 /// or if node announcement for the node was never received.
1457 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
1458 if let Some(node) = self.nodes.get(&NodeId::from_pubkey(&pubkey)) {
1459 if let Some(node_info) = node.announcement_info.as_ref() {
1460 return Some(node_info.addresses.clone())
1470 use ln::PaymentHash;
1471 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1472 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, NetworkUpdate, MAX_EXCESS_BYTES_FOR_RELAY};
1473 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1474 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
1475 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1476 use util::test_utils;
1477 use util::logger::Logger;
1478 use util::ser::{Readable, Writeable};
1479 use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
1480 use util::scid_utils::scid_from_parts;
1482 use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
1484 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1485 use bitcoin::hashes::Hash;
1486 use bitcoin::network::constants::Network;
1487 use bitcoin::blockdata::constants::genesis_block;
1488 use bitcoin::blockdata::script::{Builder, Script};
1489 use bitcoin::blockdata::transaction::TxOut;
1490 use bitcoin::blockdata::opcodes;
1494 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1495 use bitcoin::secp256k1::{All, Secp256k1};
1501 fn create_network_graph() -> NetworkGraph {
1502 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1503 NetworkGraph::new(genesis_hash)
1506 fn create_net_graph_msg_handler(network_graph: &NetworkGraph) -> (
1507 Secp256k1<All>, NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
1509 let secp_ctx = Secp256k1::new();
1510 let logger = Arc::new(test_utils::TestLogger::new());
1511 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1512 (secp_ctx, net_graph_msg_handler)
1516 fn request_full_sync_finite_times() {
1517 let network_graph = create_network_graph();
1518 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1519 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1521 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1522 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1523 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1524 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1525 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1526 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1529 fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
1530 let node_id = PublicKey::from_secret_key(&secp_ctx, node_key);
1531 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1532 features: NodeFeatures::known(),
1537 addresses: Vec::new(),
1538 excess_address_data: Vec::new(),
1539 excess_data: Vec::new(),
1541 f(&mut unsigned_announcement);
1542 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1544 signature: secp_ctx.sign(&msghash, node_key),
1545 contents: unsigned_announcement
1549 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 {
1550 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
1551 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
1552 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1553 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1555 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1556 features: ChannelFeatures::known(),
1557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1558 short_channel_id: 0,
1561 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1562 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1563 excess_data: Vec::new(),
1565 f(&mut unsigned_announcement);
1566 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1567 ChannelAnnouncement {
1568 node_signature_1: secp_ctx.sign(&msghash, node_1_key),
1569 node_signature_2: secp_ctx.sign(&msghash, node_2_key),
1570 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1571 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1572 contents: unsigned_announcement,
1576 fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> Script {
1577 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1578 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1579 Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1580 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1581 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1582 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1583 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
1587 fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
1588 let mut unsigned_channel_update = UnsignedChannelUpdate {
1589 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1590 short_channel_id: 0,
1593 cltv_expiry_delta: 144,
1594 htlc_minimum_msat: 1_000_000,
1595 htlc_maximum_msat: OptionalField::Absent,
1596 fee_base_msat: 10_000,
1597 fee_proportional_millionths: 20,
1598 excess_data: Vec::new()
1600 f(&mut unsigned_channel_update);
1601 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1603 signature: secp_ctx.sign(&msghash, node_key),
1604 contents: unsigned_channel_update
1609 fn handling_node_announcements() {
1610 let network_graph = create_network_graph();
1611 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1613 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1614 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1615 let zero_hash = Sha256dHash::hash(&[0; 32]);
1617 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
1618 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1620 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1624 // Announce a channel to add a corresponding node.
1625 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1626 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1627 Ok(res) => assert!(res),
1632 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1633 Ok(res) => assert!(res),
1637 let fake_msghash = hash_to_message!(&zero_hash);
1638 match net_graph_msg_handler.handle_node_announcement(
1640 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1641 contents: valid_announcement.contents.clone()
1644 Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
1647 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
1648 unsigned_announcement.timestamp += 1000;
1649 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1650 }, node_1_privkey, &secp_ctx);
1651 // Return false because contains excess data.
1652 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1653 Ok(res) => assert!(!res),
1657 // Even though previous announcement was not relayed further, we still accepted it,
1658 // so we now won't accept announcements before the previous one.
1659 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
1660 unsigned_announcement.timestamp += 1000 - 10;
1661 }, node_1_privkey, &secp_ctx);
1662 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1664 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1669 fn handling_channel_announcements() {
1670 let secp_ctx = Secp256k1::new();
1671 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1673 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1674 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1676 let good_script = get_channel_script(&secp_ctx);
1677 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1679 // Test if the UTXO lookups were not supported
1680 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1681 let mut net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, None, Arc::clone(&logger));
1682 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1683 Ok(res) => assert!(res),
1688 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1694 // If we receive announcement for the same channel (with UTXO lookups disabled),
1695 // drop new one on the floor, since we can't see any changes.
1696 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1698 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1701 // Test if an associated transaction were not on-chain (or not confirmed).
1702 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1703 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1704 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1705 net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1707 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1708 unsigned_announcement.short_channel_id += 1;
1709 }, node_1_privkey, node_2_privkey, &secp_ctx);
1710 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1712 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1715 // Now test if the transaction is found in the UTXO set and the script is correct.
1716 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1717 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1718 unsigned_announcement.short_channel_id += 2;
1719 }, node_1_privkey, node_2_privkey, &secp_ctx);
1720 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1721 Ok(res) => assert!(res),
1726 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1732 // If we receive announcement for the same channel (but TX is not confirmed),
1733 // drop new one on the floor, since we can't see any changes.
1734 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1735 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1737 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1740 // But if it is confirmed, replace the channel
1741 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1742 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1743 unsigned_announcement.features = ChannelFeatures::empty();
1744 unsigned_announcement.short_channel_id += 2;
1745 }, node_1_privkey, node_2_privkey, &secp_ctx);
1746 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1747 Ok(res) => assert!(res),
1751 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1752 Some(channel_entry) => {
1753 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1759 // Don't relay valid channels with excess data
1760 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1761 unsigned_announcement.short_channel_id += 3;
1762 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1763 }, node_1_privkey, node_2_privkey, &secp_ctx);
1764 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1765 Ok(res) => assert!(!res),
1769 let mut invalid_sig_announcement = valid_announcement.clone();
1770 invalid_sig_announcement.contents.excess_data = Vec::new();
1771 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1773 Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
1776 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
1777 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1779 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1784 fn handling_channel_update() {
1785 let secp_ctx = Secp256k1::new();
1786 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1787 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1788 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1789 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1791 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1792 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1794 let amount_sats = 1000_000;
1795 let short_channel_id;
1798 // Announce a channel we will update
1799 let good_script = get_channel_script(&secp_ctx);
1800 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1802 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1803 short_channel_id = valid_channel_announcement.contents.short_channel_id;
1804 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1811 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1812 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1813 Ok(res) => assert!(res),
1818 match network_graph.read_only().channels().get(&short_channel_id) {
1820 Some(channel_info) => {
1821 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1822 assert!(channel_info.two_to_one.is_none());
1827 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1828 unsigned_channel_update.timestamp += 100;
1829 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1830 }, node_1_privkey, &secp_ctx);
1831 // Return false because contains excess data
1832 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1833 Ok(res) => assert!(!res),
1837 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1838 unsigned_channel_update.timestamp += 110;
1839 unsigned_channel_update.short_channel_id += 1;
1840 }, node_1_privkey, &secp_ctx);
1841 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1843 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1846 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1847 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1848 unsigned_channel_update.timestamp += 110;
1849 }, node_1_privkey, &secp_ctx);
1850 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1852 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1855 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1856 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1857 unsigned_channel_update.timestamp += 110;
1858 }, node_1_privkey, &secp_ctx);
1859 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1861 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1864 // Even though previous update was not relayed further, we still accepted it,
1865 // so we now won't accept update before the previous one.
1866 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1867 unsigned_channel_update.timestamp += 100;
1868 }, node_1_privkey, &secp_ctx);
1869 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1871 Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
1874 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1875 unsigned_channel_update.timestamp += 500;
1876 }, node_1_privkey, &secp_ctx);
1877 let zero_hash = Sha256dHash::hash(&[0; 32]);
1878 let fake_msghash = hash_to_message!(&zero_hash);
1879 invalid_sig_channel_update.signature = secp_ctx.sign(&fake_msghash, node_1_privkey);
1880 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1882 Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
1887 fn handling_network_update() {
1888 let logger = test_utils::TestLogger::new();
1889 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1890 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1891 let network_graph = NetworkGraph::new(genesis_hash);
1892 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
1893 let secp_ctx = Secp256k1::new();
1895 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1896 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1899 // There is no nodes in the table at the beginning.
1900 assert_eq!(network_graph.read_only().nodes().len(), 0);
1903 let short_channel_id;
1905 // Announce a channel we will update
1906 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1907 short_channel_id = valid_channel_announcement.contents.short_channel_id;
1908 let chain_source: Option<&test_utils::TestChainSource> = None;
1909 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
1910 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
1912 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1913 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
1915 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1917 payment_hash: PaymentHash([0; 32]),
1918 rejected_by_dest: false,
1919 all_paths_failed: true,
1921 network_update: Some(NetworkUpdate::ChannelUpdateMessage {
1922 msg: valid_channel_update,
1924 short_channel_id: None,
1930 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
1933 // Non-permanent closing just disables a channel
1935 match network_graph.read_only().channels().get(&short_channel_id) {
1937 Some(channel_info) => {
1938 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
1942 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1944 payment_hash: PaymentHash([0; 32]),
1945 rejected_by_dest: false,
1946 all_paths_failed: true,
1948 network_update: Some(NetworkUpdate::ChannelClosed {
1950 is_permanent: false,
1952 short_channel_id: None,
1958 match network_graph.read_only().channels().get(&short_channel_id) {
1960 Some(channel_info) => {
1961 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1966 // Permanent closing deletes a channel
1967 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
1969 payment_hash: PaymentHash([0; 32]),
1970 rejected_by_dest: false,
1971 all_paths_failed: true,
1973 network_update: Some(NetworkUpdate::ChannelClosed {
1977 short_channel_id: None,
1983 assert_eq!(network_graph.read_only().channels().len(), 0);
1984 // Nodes are also deleted because there are no associated channels anymore
1985 assert_eq!(network_graph.read_only().nodes().len(), 0);
1986 // TODO: Test NetworkUpdate::NodeFailure, which is not implemented yet.
1990 fn test_channel_timeouts() {
1991 // Test the removal of channels with `remove_stale_channels`.
1992 let logger = test_utils::TestLogger::new();
1993 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1994 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1995 let network_graph = NetworkGraph::new(genesis_hash);
1996 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
1997 let secp_ctx = Secp256k1::new();
1999 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2000 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2002 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2003 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2004 let chain_source: Option<&test_utils::TestChainSource> = None;
2005 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
2006 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2008 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2009 assert!(net_graph_msg_handler.handle_channel_update(&valid_channel_update).is_ok());
2010 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2012 network_graph.remove_stale_channels_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2013 assert_eq!(network_graph.read_only().channels().len(), 1);
2014 assert_eq!(network_graph.read_only().nodes().len(), 2);
2016 network_graph.remove_stale_channels_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2017 #[cfg(feature = "std")]
2019 // In std mode, a further check is performed before fully removing the channel -
2020 // the channel_announcement must have been received at least two weeks ago. We
2021 // fudge that here by indicating the time has jumped two weeks. Note that the
2022 // directional channel information will have been removed already..
2023 assert_eq!(network_graph.read_only().channels().len(), 1);
2024 assert_eq!(network_graph.read_only().nodes().len(), 2);
2025 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2027 use std::time::{SystemTime, UNIX_EPOCH};
2028 let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2029 network_graph.remove_stale_channels_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2032 assert_eq!(network_graph.read_only().channels().len(), 0);
2033 assert_eq!(network_graph.read_only().nodes().len(), 0);
2037 fn getting_next_channel_announcements() {
2038 let network_graph = create_network_graph();
2039 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2040 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2041 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2043 // Channels were not announced yet.
2044 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
2045 assert_eq!(channels_with_announcements.len(), 0);
2047 let short_channel_id;
2049 // Announce a channel we will update
2050 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2051 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2052 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2058 // Contains initial channel announcement now.
2059 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2060 assert_eq!(channels_with_announcements.len(), 1);
2061 if let Some(channel_announcements) = channels_with_announcements.first() {
2062 let &(_, ref update_1, ref update_2) = channel_announcements;
2063 assert_eq!(update_1, &None);
2064 assert_eq!(update_2, &None);
2071 // Valid channel update
2072 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2073 unsigned_channel_update.timestamp = 101;
2074 }, node_1_privkey, &secp_ctx);
2075 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2081 // Now contains an initial announcement and an update.
2082 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2083 assert_eq!(channels_with_announcements.len(), 1);
2084 if let Some(channel_announcements) = channels_with_announcements.first() {
2085 let &(_, ref update_1, ref update_2) = channel_announcements;
2086 assert_ne!(update_1, &None);
2087 assert_eq!(update_2, &None);
2093 // Channel update with excess data.
2094 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2095 unsigned_channel_update.timestamp = 102;
2096 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2097 }, node_1_privkey, &secp_ctx);
2098 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2104 // Test that announcements with excess data won't be returned
2105 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2106 assert_eq!(channels_with_announcements.len(), 1);
2107 if let Some(channel_announcements) = channels_with_announcements.first() {
2108 let &(_, ref update_1, ref update_2) = channel_announcements;
2109 assert_eq!(update_1, &None);
2110 assert_eq!(update_2, &None);
2115 // Further starting point have no channels after it
2116 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
2117 assert_eq!(channels_with_announcements.len(), 0);
2121 fn getting_next_node_announcements() {
2122 let network_graph = create_network_graph();
2123 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2124 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2125 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2126 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2129 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
2130 assert_eq!(next_announcements.len(), 0);
2133 // Announce a channel to add 2 nodes
2134 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2135 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2142 // Nodes were never announced
2143 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2144 assert_eq!(next_announcements.len(), 0);
2147 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2148 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2153 let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
2154 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2160 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2161 assert_eq!(next_announcements.len(), 2);
2163 // Skip the first node.
2164 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2165 assert_eq!(next_announcements.len(), 1);
2168 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2169 let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
2170 unsigned_announcement.timestamp += 10;
2171 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2172 }, node_2_privkey, &secp_ctx);
2173 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2174 Ok(res) => assert!(!res),
2179 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2180 assert_eq!(next_announcements.len(), 0);
2184 fn network_graph_serialization() {
2185 let network_graph = create_network_graph();
2186 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2188 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2189 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2191 // Announce a channel to add a corresponding node.
2192 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2193 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2194 Ok(res) => assert!(res),
2198 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2199 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2204 let mut w = test_utils::TestVecWriter(Vec::new());
2205 assert!(!network_graph.read_only().nodes().is_empty());
2206 assert!(!network_graph.read_only().channels().is_empty());
2207 network_graph.write(&mut w).unwrap();
2208 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == network_graph);
2212 fn calling_sync_routing_table() {
2213 let network_graph = create_network_graph();
2214 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2215 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2216 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2218 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2219 let first_blocknum = 0;
2220 let number_of_blocks = 0xffff_ffff;
2222 // It should ignore if gossip_queries feature is not enabled
2224 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2225 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2226 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2227 assert_eq!(events.len(), 0);
2230 // It should send a query_channel_message with the correct information
2232 let init_msg = Init { features: InitFeatures::known() };
2233 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2234 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2235 assert_eq!(events.len(), 1);
2237 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2238 assert_eq!(node_id, &node_id_1);
2239 assert_eq!(msg.chain_hash, chain_hash);
2240 assert_eq!(msg.first_blocknum, first_blocknum);
2241 assert_eq!(msg.number_of_blocks, number_of_blocks);
2243 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2247 // It should not enqueue a query when should_request_full_sync return false.
2248 // The initial implementation allows syncing with the first 5 peers after
2249 // which should_request_full_sync will return false
2251 let network_graph = create_network_graph();
2252 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2253 let init_msg = Init { features: InitFeatures::known() };
2255 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2256 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2257 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2258 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2260 assert_eq!(events.len(), 1);
2262 assert_eq!(events.len(), 0);
2270 fn handling_reply_channel_range() {
2271 let network_graph = create_network_graph();
2272 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2273 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2274 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2276 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2278 // Test receipt of a single reply that should enqueue an SCID query
2279 // matching the SCIDs in the reply
2281 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2283 sync_complete: true,
2285 number_of_blocks: 2000,
2286 short_channel_ids: vec![
2287 0x0003e0_000000_0000, // 992x0x0
2288 0x0003e8_000000_0000, // 1000x0x0
2289 0x0003e9_000000_0000, // 1001x0x0
2290 0x0003f0_000000_0000, // 1008x0x0
2291 0x00044c_000000_0000, // 1100x0x0
2292 0x0006e0_000000_0000, // 1760x0x0
2295 assert!(result.is_ok());
2297 // We expect to emit a query_short_channel_ids message with the received scids
2298 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2299 assert_eq!(events.len(), 1);
2301 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2302 assert_eq!(node_id, &node_id_1);
2303 assert_eq!(msg.chain_hash, chain_hash);
2304 assert_eq!(msg.short_channel_ids, vec![
2305 0x0003e0_000000_0000, // 992x0x0
2306 0x0003e8_000000_0000, // 1000x0x0
2307 0x0003e9_000000_0000, // 1001x0x0
2308 0x0003f0_000000_0000, // 1008x0x0
2309 0x00044c_000000_0000, // 1100x0x0
2310 0x0006e0_000000_0000, // 1760x0x0
2313 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2319 fn handling_reply_short_channel_ids() {
2320 let network_graph = create_network_graph();
2321 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2322 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2323 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2325 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2327 // Test receipt of a successful reply
2329 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2331 full_information: true,
2333 assert!(result.is_ok());
2336 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2337 // for the chain_hash requested in the query.
2339 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2341 full_information: false,
2343 assert!(result.is_err());
2344 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2349 fn handling_query_channel_range() {
2350 let network_graph = create_network_graph();
2351 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2353 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2354 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2355 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2356 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2358 let mut scids: Vec<u64> = vec![
2359 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2360 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2363 // used for testing multipart reply across blocks
2364 for block in 100000..=108001 {
2365 scids.push(scid_from_parts(block, 0, 0).unwrap());
2368 // used for testing resumption on same block
2369 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2372 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2373 unsigned_announcement.short_channel_id = scid;
2374 }, node_1_privkey, node_2_privkey, &secp_ctx);
2375 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2381 // Error when number_of_blocks=0
2382 do_handling_query_channel_range(
2383 &net_graph_msg_handler,
2386 chain_hash: chain_hash.clone(),
2388 number_of_blocks: 0,
2391 vec![ReplyChannelRange {
2392 chain_hash: chain_hash.clone(),
2394 number_of_blocks: 0,
2395 sync_complete: true,
2396 short_channel_ids: vec![]
2400 // Error when wrong chain
2401 do_handling_query_channel_range(
2402 &net_graph_msg_handler,
2405 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2407 number_of_blocks: 0xffff_ffff,
2410 vec![ReplyChannelRange {
2411 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2413 number_of_blocks: 0xffff_ffff,
2414 sync_complete: true,
2415 short_channel_ids: vec![],
2419 // Error when first_blocknum > 0xffffff
2420 do_handling_query_channel_range(
2421 &net_graph_msg_handler,
2424 chain_hash: chain_hash.clone(),
2425 first_blocknum: 0x01000000,
2426 number_of_blocks: 0xffff_ffff,
2429 vec![ReplyChannelRange {
2430 chain_hash: chain_hash.clone(),
2431 first_blocknum: 0x01000000,
2432 number_of_blocks: 0xffff_ffff,
2433 sync_complete: true,
2434 short_channel_ids: vec![]
2438 // Empty reply when max valid SCID block num
2439 do_handling_query_channel_range(
2440 &net_graph_msg_handler,
2443 chain_hash: chain_hash.clone(),
2444 first_blocknum: 0xffffff,
2445 number_of_blocks: 1,
2450 chain_hash: chain_hash.clone(),
2451 first_blocknum: 0xffffff,
2452 number_of_blocks: 1,
2453 sync_complete: true,
2454 short_channel_ids: vec![]
2459 // No results in valid query range
2460 do_handling_query_channel_range(
2461 &net_graph_msg_handler,
2464 chain_hash: chain_hash.clone(),
2465 first_blocknum: 1000,
2466 number_of_blocks: 1000,
2471 chain_hash: chain_hash.clone(),
2472 first_blocknum: 1000,
2473 number_of_blocks: 1000,
2474 sync_complete: true,
2475 short_channel_ids: vec![],
2480 // Overflow first_blocknum + number_of_blocks
2481 do_handling_query_channel_range(
2482 &net_graph_msg_handler,
2485 chain_hash: chain_hash.clone(),
2486 first_blocknum: 0xfe0000,
2487 number_of_blocks: 0xffffffff,
2492 chain_hash: chain_hash.clone(),
2493 first_blocknum: 0xfe0000,
2494 number_of_blocks: 0xffffffff - 0xfe0000,
2495 sync_complete: true,
2496 short_channel_ids: vec![
2497 0xfffffe_ffffff_ffff, // max
2503 // Single block exactly full
2504 do_handling_query_channel_range(
2505 &net_graph_msg_handler,
2508 chain_hash: chain_hash.clone(),
2509 first_blocknum: 100000,
2510 number_of_blocks: 8000,
2515 chain_hash: chain_hash.clone(),
2516 first_blocknum: 100000,
2517 number_of_blocks: 8000,
2518 sync_complete: true,
2519 short_channel_ids: (100000..=107999)
2520 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2526 // Multiple split on new block
2527 do_handling_query_channel_range(
2528 &net_graph_msg_handler,
2531 chain_hash: chain_hash.clone(),
2532 first_blocknum: 100000,
2533 number_of_blocks: 8001,
2538 chain_hash: chain_hash.clone(),
2539 first_blocknum: 100000,
2540 number_of_blocks: 7999,
2541 sync_complete: false,
2542 short_channel_ids: (100000..=107999)
2543 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2547 chain_hash: chain_hash.clone(),
2548 first_blocknum: 107999,
2549 number_of_blocks: 2,
2550 sync_complete: true,
2551 short_channel_ids: vec![
2552 scid_from_parts(108000, 0, 0).unwrap(),
2558 // Multiple split on same block
2559 do_handling_query_channel_range(
2560 &net_graph_msg_handler,
2563 chain_hash: chain_hash.clone(),
2564 first_blocknum: 100002,
2565 number_of_blocks: 8000,
2570 chain_hash: chain_hash.clone(),
2571 first_blocknum: 100002,
2572 number_of_blocks: 7999,
2573 sync_complete: false,
2574 short_channel_ids: (100002..=108001)
2575 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2579 chain_hash: chain_hash.clone(),
2580 first_blocknum: 108001,
2581 number_of_blocks: 1,
2582 sync_complete: true,
2583 short_channel_ids: vec![
2584 scid_from_parts(108001, 1, 0).unwrap(),
2591 fn do_handling_query_channel_range(
2592 net_graph_msg_handler: &NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2593 test_node_id: &PublicKey,
2594 msg: QueryChannelRange,
2596 expected_replies: Vec<ReplyChannelRange>
2598 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2599 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2600 let query_end_blocknum = msg.end_blocknum();
2601 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2604 assert!(result.is_ok());
2606 assert!(result.is_err());
2609 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2610 assert_eq!(events.len(), expected_replies.len());
2612 for i in 0..events.len() {
2613 let expected_reply = &expected_replies[i];
2615 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2616 assert_eq!(node_id, test_node_id);
2617 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2618 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2619 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2620 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2621 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2623 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2624 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2625 assert!(msg.first_blocknum >= max_firstblocknum);
2626 max_firstblocknum = msg.first_blocknum;
2627 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2629 // Check that the last block count is >= the query's end_blocknum
2630 if i == events.len() - 1 {
2631 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2634 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2640 fn handling_query_short_channel_ids() {
2641 let network_graph = create_network_graph();
2642 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2643 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2644 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2646 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2648 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2650 short_channel_ids: vec![0x0003e8_000000_0000],
2652 assert!(result.is_err());
2656 #[cfg(all(test, feature = "unstable"))]
2664 fn read_network_graph(bench: &mut Bencher) {
2665 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2666 let mut v = Vec::new();
2667 d.read_to_end(&mut v).unwrap();
2669 let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2674 fn write_network_graph(bench: &mut Bencher) {
2675 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2676 let net_graph = NetworkGraph::read(&mut d).unwrap();
2678 let _ = net_graph.encode();