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 [`NetworkGraph`] stores the network gossip and [`P2PGossipSync`] fetches it from peers
12 use bitcoin::blockdata::constants::ChainHash;
14 use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
15 use bitcoin::secp256k1::{PublicKey, Verification};
16 use bitcoin::secp256k1::Secp256k1;
17 use bitcoin::secp256k1;
19 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
20 use bitcoin::hashes::Hash;
21 use bitcoin::network::constants::Network;
23 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
24 use crate::ln::types::ChannelId;
25 use crate::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
26 use crate::ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, SocketAddress, MAX_VALUE_MSAT};
27 use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, GossipTimestampFilter};
28 use crate::ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use crate::routing::utxo::{self, UtxoLookup, UtxoResolver};
31 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, MaybeReadable};
32 use crate::util::logger::{Logger, Level};
33 use crate::util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
34 use crate::util::string::PrintableString;
35 use crate::util::indexed_map::{IndexedMap, Entry as IndexedMapEntry};
38 use crate::io_extras::{copy, sink};
39 use crate::prelude::*;
41 use crate::sync::{RwLock, RwLockReadGuard, LockTestExt};
42 #[cfg(feature = "std")]
43 use core::sync::atomic::{AtomicUsize, Ordering};
44 use crate::sync::Mutex;
45 use core::ops::{Bound, Deref};
46 use core::str::FromStr;
48 #[cfg(feature = "std")]
49 use std::time::{SystemTime, UNIX_EPOCH};
51 /// We remove stale channel directional info two weeks after the last update, per BOLT 7's
53 const STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14;
55 /// We stop tracking the removal of permanently failed nodes and channels one week after removal
56 const REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 7;
58 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
59 /// refuse to relay the message.
60 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
62 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
63 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
64 const MAX_SCIDS_PER_REPLY: usize = 8000;
66 /// Represents the compressed public key of a node
67 #[derive(Clone, Copy)]
68 pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
71 /// Create a new NodeId from a public key
72 pub fn from_pubkey(pubkey: &PublicKey) -> Self {
73 NodeId(pubkey.serialize())
76 /// Create a new NodeId from a slice of bytes
77 pub fn from_slice(bytes: &[u8]) -> Result<Self, DecodeError> {
78 if bytes.len() != PUBLIC_KEY_SIZE {
79 return Err(DecodeError::InvalidValue);
81 let mut data = [0; PUBLIC_KEY_SIZE];
82 data.copy_from_slice(bytes);
86 /// Get the public key slice from this NodeId
87 pub fn as_slice(&self) -> &[u8] {
91 /// Get the public key as an array from this NodeId
92 pub fn as_array(&self) -> &[u8; PUBLIC_KEY_SIZE] {
96 /// Get the public key from this NodeId
97 pub fn as_pubkey(&self) -> Result<PublicKey, secp256k1::Error> {
98 PublicKey::from_slice(&self.0)
102 impl fmt::Debug for NodeId {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104 write!(f, "NodeId({})", crate::util::logger::DebugBytes(&self.0))
107 impl fmt::Display for NodeId {
108 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109 crate::util::logger::DebugBytes(&self.0).fmt(f)
113 impl core::hash::Hash for NodeId {
114 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
119 impl Eq for NodeId {}
121 impl PartialEq for NodeId {
122 fn eq(&self, other: &Self) -> bool {
123 self.0[..] == other.0[..]
127 impl cmp::PartialOrd for NodeId {
128 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
129 Some(self.cmp(other))
133 impl Ord for NodeId {
134 fn cmp(&self, other: &Self) -> cmp::Ordering {
135 self.0[..].cmp(&other.0[..])
139 impl Writeable for NodeId {
140 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
141 writer.write_all(&self.0)?;
146 impl Readable for NodeId {
147 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
148 let mut buf = [0; PUBLIC_KEY_SIZE];
149 reader.read_exact(&mut buf)?;
154 impl From<PublicKey> for NodeId {
155 fn from(pubkey: PublicKey) -> Self {
156 Self::from_pubkey(&pubkey)
160 impl TryFrom<NodeId> for PublicKey {
161 type Error = secp256k1::Error;
163 fn try_from(node_id: NodeId) -> Result<Self, Self::Error> {
168 impl FromStr for NodeId {
169 type Err = hex::parse::HexToArrayError;
171 fn from_str(s: &str) -> Result<Self, Self::Err> {
172 let data: [u8; PUBLIC_KEY_SIZE] = hex::FromHex::from_hex(s)?;
177 /// Represents the network as nodes and channels between them
178 pub struct NetworkGraph<L: Deref> where L::Target: Logger {
179 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
180 last_rapid_gossip_sync_timestamp: Mutex<Option<u32>>,
181 chain_hash: ChainHash,
183 // Lock order: channels -> nodes
184 channels: RwLock<IndexedMap<u64, ChannelInfo>>,
185 nodes: RwLock<IndexedMap<NodeId, NodeInfo>>,
186 // Lock order: removed_channels -> removed_nodes
188 // NOTE: In the following `removed_*` maps, we use seconds since UNIX epoch to track time instead
189 // of `std::time::Instant`s for a few reasons:
190 // * We want it to be possible to do tracking in no-std environments where we can compare
191 // a provided current UNIX timestamp with the time at which we started tracking.
192 // * In the future, if we decide to persist these maps, they will already be serializable.
193 // * Although we lose out on the platform's monotonic clock, the system clock in a std
194 // environment should be practical over the time period we are considering (on the order of a
197 /// Keeps track of short channel IDs for channels we have explicitly removed due to permanent
198 /// failure so that we don't resync them from gossip. Each SCID is mapped to the time (in seconds)
199 /// it was removed so that once some time passes, we can potentially resync it from gossip again.
200 removed_channels: Mutex<HashMap<u64, Option<u64>>>,
201 /// Keeps track of `NodeId`s we have explicitly removed due to permanent failure so that we don't
202 /// resync them from gossip. Each `NodeId` is mapped to the time (in seconds) it was removed so
203 /// that once some time passes, we can potentially resync it from gossip again.
204 removed_nodes: Mutex<HashMap<NodeId, Option<u64>>>,
205 /// Announcement messages which are awaiting an on-chain lookup to be processed.
206 pub(super) pending_checks: utxo::PendingChecks,
209 /// A read-only view of [`NetworkGraph`].
210 pub struct ReadOnlyNetworkGraph<'a> {
211 channels: RwLockReadGuard<'a, IndexedMap<u64, ChannelInfo>>,
212 nodes: RwLockReadGuard<'a, IndexedMap<NodeId, NodeInfo>>,
215 /// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
216 /// return packet by a node along the route. See [BOLT #4] for details.
218 /// [BOLT #4]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md
219 #[derive(Clone, Debug, PartialEq, Eq)]
220 pub enum NetworkUpdate {
221 /// An error indicating a `channel_update` messages should be applied via
222 /// [`NetworkGraph::update_channel`].
223 ChannelUpdateMessage {
224 /// The update to apply via [`NetworkGraph::update_channel`].
227 /// An error indicating that a channel failed to route a payment, which should be applied via
228 /// [`NetworkGraph::channel_failed_permanent`] if permanent.
230 /// The short channel id of the closed channel.
231 short_channel_id: u64,
232 /// Whether the channel should be permanently removed or temporarily disabled until a new
233 /// `channel_update` message is received.
236 /// An error indicating that a node failed to route a payment, which should be applied via
237 /// [`NetworkGraph::node_failed_permanent`] if permanent.
239 /// The node id of the failed node.
241 /// Whether the node should be permanently removed from consideration or can be restored
242 /// when a new `channel_update` message is received.
247 impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
248 (0, ChannelUpdateMessage) => {
251 (2, ChannelFailure) => {
252 (0, short_channel_id, required),
253 (2, is_permanent, required),
255 (4, NodeFailure) => {
256 (0, node_id, required),
257 (2, is_permanent, required),
261 /// Receives and validates network updates from peers,
262 /// stores authentic and relevant data as a network graph.
263 /// This network graph is then used for routing payments.
264 /// Provides interface to help with initial routing sync by
265 /// serving historical announcements.
266 pub struct P2PGossipSync<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref>
267 where U::Target: UtxoLookup, L::Target: Logger
270 utxo_lookup: RwLock<Option<U>>,
271 #[cfg(feature = "std")]
272 full_syncs_requested: AtomicUsize,
273 pending_events: Mutex<Vec<MessageSendEvent>>,
277 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> P2PGossipSync<G, U, L>
278 where U::Target: UtxoLookup, L::Target: Logger
280 /// Creates a new tracker of the actual state of the network of channels and nodes,
281 /// assuming an existing [`NetworkGraph`].
282 /// UTXO lookup is used to make sure announced channels exist on-chain, channel data is
283 /// correct, and the announcement is signed with channel owners' keys.
284 pub fn new(network_graph: G, utxo_lookup: Option<U>, logger: L) -> Self {
287 #[cfg(feature = "std")]
288 full_syncs_requested: AtomicUsize::new(0),
289 utxo_lookup: RwLock::new(utxo_lookup),
290 pending_events: Mutex::new(vec![]),
295 /// Adds a provider used to check new announcements. Does not affect
296 /// existing announcements unless they are updated.
297 /// Add, update or remove the provider would replace the current one.
298 pub fn add_utxo_lookup(&self, utxo_lookup: Option<U>) {
299 *self.utxo_lookup.write().unwrap() = utxo_lookup;
302 /// Gets a reference to the underlying [`NetworkGraph`] which was provided in
303 /// [`P2PGossipSync::new`].
305 /// This is not exported to bindings users as bindings don't support a reference-to-a-reference yet
306 pub fn network_graph(&self) -> &G {
310 #[cfg(feature = "std")]
311 /// Returns true when a full routing table sync should be performed with a peer.
312 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
313 //TODO: Determine whether to request a full sync based on the network map.
314 const FULL_SYNCS_TO_REQUEST: usize = 5;
315 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
316 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
323 /// Used to broadcast forward gossip messages which were validated async.
325 /// Note that this will ignore events other than `Broadcast*` or messages with too much excess
327 pub(super) fn forward_gossip_msg(&self, mut ev: MessageSendEvent) {
329 MessageSendEvent::BroadcastChannelAnnouncement { msg, ref mut update_msg } => {
330 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
331 if update_msg.as_ref()
332 .map(|msg| msg.contents.excess_data.len()).unwrap_or(0) > MAX_EXCESS_BYTES_FOR_RELAY
337 MessageSendEvent::BroadcastChannelUpdate { msg } => {
338 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
340 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
341 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY ||
342 msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY ||
343 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY
350 self.pending_events.lock().unwrap().push(ev);
354 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
355 /// Handles any network updates originating from [`Event`]s.
357 /// Note that this will skip applying any [`NetworkUpdate::ChannelUpdateMessage`] to avoid
358 /// leaking possibly identifying information of the sender to the public network.
360 /// [`Event`]: crate::events::Event
361 pub fn handle_network_update(&self, network_update: &NetworkUpdate) {
362 match *network_update {
363 NetworkUpdate::ChannelUpdateMessage { ref msg } => {
364 let short_channel_id = msg.contents.short_channel_id;
365 let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
366 let status = if is_enabled { "enabled" } else { "disabled" };
367 log_debug!(self.logger, "Skipping application of a channel update from a payment failure. Channel {} is {}.", short_channel_id, status);
369 NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } => {
371 log_debug!(self.logger, "Removing channel graph entry for {} due to a payment failure.", short_channel_id);
372 self.channel_failed_permanent(short_channel_id);
375 NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
377 log_debug!(self.logger,
378 "Removed node graph entry for {} due to a payment failure.", log_pubkey!(node_id));
379 self.node_failed_permanent(node_id);
385 /// Gets the chain hash for this network graph.
386 pub fn get_chain_hash(&self) -> ChainHash {
391 macro_rules! secp_verify_sig {
392 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr, $msg_type: expr ) => {
393 match $secp_ctx.verify_ecdsa($msg, $sig, $pubkey) {
396 return Err(LightningError {
397 err: format!("Invalid signature on {} message", $msg_type),
398 action: ErrorAction::SendWarningMessage {
399 msg: msgs::WarningMessage {
400 channel_id: ChannelId::new_zero(),
401 data: format!("Invalid signature on {} message", $msg_type),
403 log_level: Level::Trace,
411 macro_rules! get_pubkey_from_node_id {
412 ( $node_id: expr, $msg_type: expr ) => {
413 PublicKey::from_slice($node_id.as_slice())
414 .map_err(|_| LightningError {
415 err: format!("Invalid public key on {} message", $msg_type),
416 action: ErrorAction::SendWarningMessage {
417 msg: msgs::WarningMessage {
418 channel_id: ChannelId::new_zero(),
419 data: format!("Invalid public key on {} message", $msg_type),
421 log_level: Level::Trace
427 fn message_sha256d_hash<M: Writeable>(msg: &M) -> Sha256dHash {
428 let mut engine = Sha256dHash::engine();
429 msg.write(&mut engine).expect("In-memory structs should not fail to serialize");
430 Sha256dHash::from_engine(engine)
433 /// Verifies the signature of a [`NodeAnnouncement`].
435 /// Returns an error if it is invalid.
436 pub fn verify_node_announcement<C: Verification>(msg: &NodeAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
437 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg.contents)[..]);
438 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &get_pubkey_from_node_id!(msg.contents.node_id, "node_announcement"), "node_announcement");
443 /// Verifies all signatures included in a [`ChannelAnnouncement`].
445 /// Returns an error if one of the signatures is invalid.
446 pub fn verify_channel_announcement<C: Verification>(msg: &ChannelAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
447 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg.contents)[..]);
448 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &get_pubkey_from_node_id!(msg.contents.node_id_1, "channel_announcement"), "channel_announcement");
449 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &get_pubkey_from_node_id!(msg.contents.node_id_2, "channel_announcement"), "channel_announcement");
450 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &get_pubkey_from_node_id!(msg.contents.bitcoin_key_1, "channel_announcement"), "channel_announcement");
451 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &get_pubkey_from_node_id!(msg.contents.bitcoin_key_2, "channel_announcement"), "channel_announcement");
456 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> RoutingMessageHandler for P2PGossipSync<G, U, L>
457 where U::Target: UtxoLookup, L::Target: Logger
459 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
460 self.network_graph.update_node_from_announcement(msg)?;
461 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
462 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
463 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
466 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
467 self.network_graph.update_channel_from_announcement(msg, &*self.utxo_lookup.read().unwrap())?;
468 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
471 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
472 self.network_graph.update_channel(msg)?;
473 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
476 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
477 let mut channels = self.network_graph.channels.write().unwrap();
478 for (_, ref chan) in channels.range(starting_point..) {
479 if chan.announcement_message.is_some() {
480 let chan_announcement = chan.announcement_message.clone().unwrap();
481 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
482 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
483 if let Some(one_to_two) = chan.one_to_two.as_ref() {
484 one_to_two_announcement = one_to_two.last_update_message.clone();
486 if let Some(two_to_one) = chan.two_to_one.as_ref() {
487 two_to_one_announcement = two_to_one.last_update_message.clone();
489 return Some((chan_announcement, one_to_two_announcement, two_to_one_announcement));
491 // TODO: We may end up sending un-announced channel_updates if we are sending
492 // initial sync data while receiving announce/updates for this channel.
498 fn get_next_node_announcement(&self, starting_point: Option<&NodeId>) -> Option<NodeAnnouncement> {
499 let mut nodes = self.network_graph.nodes.write().unwrap();
500 let iter = if let Some(node_id) = starting_point {
501 nodes.range((Bound::Excluded(node_id), Bound::Unbounded))
505 for (_, ref node) in iter {
506 if let Some(node_info) = node.announcement_info.as_ref() {
507 if let NodeAnnouncementInfo::Relayed(announcement) = node_info {
508 return Some(announcement.clone());
515 /// Initiates a stateless sync of routing gossip information with a peer
516 /// using [`gossip_queries`]. The default strategy used by this implementation
517 /// is to sync the full block range with several peers.
519 /// We should expect one or more [`reply_channel_range`] messages in response
520 /// to our [`query_channel_range`]. Each reply will enqueue a [`query_scid`] message
521 /// to request gossip messages for each channel. The sync is considered complete
522 /// when the final [`reply_scids_end`] message is received, though we are not
523 /// tracking this directly.
525 /// [`gossip_queries`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#query-messages
526 /// [`reply_channel_range`]: msgs::ReplyChannelRange
527 /// [`query_channel_range`]: msgs::QueryChannelRange
528 /// [`query_scid`]: msgs::QueryShortChannelIds
529 /// [`reply_scids_end`]: msgs::ReplyShortChannelIdsEnd
530 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &Init, _inbound: bool) -> Result<(), ()> {
531 // We will only perform a sync with peers that support gossip_queries.
532 if !init_msg.features.supports_gossip_queries() {
533 // Don't disconnect peers for not supporting gossip queries. We may wish to have
534 // channels with peers even without being able to exchange gossip.
538 // The lightning network's gossip sync system is completely broken in numerous ways.
540 // Given no broadly-available set-reconciliation protocol, the only reasonable approach is
541 // to do a full sync from the first few peers we connect to, and then receive gossip
542 // updates from all our peers normally.
544 // Originally, we could simply tell a peer to dump us the entire gossip table on startup,
545 // wasting lots of bandwidth but ensuring we have the full network graph. After the initial
546 // dump peers would always send gossip and we'd stay up-to-date with whatever our peer has
549 // In order to reduce the bandwidth waste, "gossip queries" were introduced, allowing you
550 // to ask for the SCIDs of all channels in your peer's routing graph, and then only request
551 // channel data which you are missing. Except there was no way at all to identify which
552 // `channel_update`s you were missing, so you still had to request everything, just in a
553 // very complicated way with some queries instead of just getting the dump.
555 // Later, an option was added to fetch the latest timestamps of the `channel_update`s to
556 // make efficient sync possible, however it has yet to be implemented in lnd, which makes
557 // relying on it useless.
559 // After gossip queries were introduced, support for receiving a full gossip table dump on
560 // connection was removed from several nodes, making it impossible to get a full sync
561 // without using the "gossip queries" messages.
563 // Once you opt into "gossip queries" the only way to receive any gossip updates that a
564 // peer receives after you connect, you must send a `gossip_timestamp_filter` message. This
565 // message, as the name implies, tells the peer to not forward any gossip messages with a
566 // timestamp older than a given value (not the time the peer received the filter, but the
567 // timestamp in the update message, which is often hours behind when the peer received the
570 // Obnoxiously, `gossip_timestamp_filter` isn't *just* a filter, but its also a request for
571 // your peer to send you the full routing graph (subject to the filter). Thus, in order to
572 // tell a peer to send you any updates as it sees them, you have to also ask for the full
573 // routing graph to be synced. If you set a timestamp filter near the current time, peers
574 // will simply not forward any new updates they see to you which were generated some time
575 // ago (which is not uncommon). If you instead set a timestamp filter near 0 (or two weeks
576 // ago), you will always get the full routing graph from all your peers.
578 // Most lightning nodes today opt to simply turn off receiving gossip data which only
579 // propagated some time after it was generated, and, worse, often disable gossiping with
580 // several peers after their first connection. The second behavior can cause gossip to not
581 // propagate fully if there are cuts in the gossiping subgraph.
583 // In an attempt to cut a middle ground between always fetching the full graph from all of
584 // our peers and never receiving gossip from peers at all, we send all of our peers a
585 // `gossip_timestamp_filter`, with the filter time set either two weeks ago or an hour ago.
587 // For no-std builds, we bury our head in the sand and do a full sync on each connection.
588 #[allow(unused_mut, unused_assignments)]
589 let mut gossip_start_time = 0;
590 #[cfg(feature = "std")]
592 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
593 if self.should_request_full_sync(&their_node_id) {
594 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
596 gossip_start_time -= 60 * 60; // an hour ago
600 let mut pending_events = self.pending_events.lock().unwrap();
601 pending_events.push(MessageSendEvent::SendGossipTimestampFilter {
602 node_id: their_node_id.clone(),
603 msg: GossipTimestampFilter {
604 chain_hash: self.network_graph.chain_hash,
605 first_timestamp: gossip_start_time as u32, // 2106 issue!
606 timestamp_range: u32::max_value(),
612 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: ReplyChannelRange) -> Result<(), LightningError> {
613 // We don't make queries, so should never receive replies. If, in the future, the set
614 // reconciliation extensions to gossip queries become broadly supported, we should revert
615 // this code to its state pre-0.0.106.
619 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
620 // We don't make queries, so should never receive replies. If, in the future, the set
621 // reconciliation extensions to gossip queries become broadly supported, we should revert
622 // this code to its state pre-0.0.106.
626 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
627 /// are in the specified block range. Due to message size limits, large range
628 /// queries may result in several reply messages. This implementation enqueues
629 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
630 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
631 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
632 /// memory constrained systems.
633 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
634 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);
636 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
638 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
639 // If so, we manually cap the ending block to avoid this overflow.
640 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
642 // Per spec, we must reply to a query. Send an empty message when things are invalid.
643 if msg.chain_hash != self.network_graph.chain_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
644 let mut pending_events = self.pending_events.lock().unwrap();
645 pending_events.push(MessageSendEvent::SendReplyChannelRange {
646 node_id: their_node_id.clone(),
647 msg: ReplyChannelRange {
648 chain_hash: msg.chain_hash.clone(),
649 first_blocknum: msg.first_blocknum,
650 number_of_blocks: msg.number_of_blocks,
652 short_channel_ids: vec![],
655 return Err(LightningError {
656 err: String::from("query_channel_range could not be processed"),
657 action: ErrorAction::IgnoreError,
661 // Creates channel batches. We are not checking if the channel is routable
662 // (has at least one update). A peer may still want to know the channel
663 // exists even if its not yet routable.
664 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
665 let mut channels = self.network_graph.channels.write().unwrap();
666 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
667 if let Some(chan_announcement) = &chan.announcement_message {
668 // Construct a new batch if last one is full
669 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
670 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
673 let batch = batches.last_mut().unwrap();
674 batch.push(chan_announcement.contents.short_channel_id);
679 let mut pending_events = self.pending_events.lock().unwrap();
680 let batch_count = batches.len();
681 let mut prev_batch_endblock = msg.first_blocknum;
682 for (batch_index, batch) in batches.into_iter().enumerate() {
683 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
684 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
686 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
687 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
688 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
689 // significant diversion from the requirements set by the spec, and, in case of blocks
690 // with no channel opens (e.g. empty blocks), requires that we use the previous value
691 // and *not* derive the first_blocknum from the actual first block of the reply.
692 let first_blocknum = prev_batch_endblock;
694 // Each message carries the number of blocks (from the `first_blocknum`) its contents
695 // fit in. Though there is no requirement that we use exactly the number of blocks its
696 // contents are from, except for the bogus requirements c-lightning enforces, above.
698 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
699 // >= the query's end block. Thus, for the last reply, we calculate the difference
700 // between the query's end block and the start of the reply.
702 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
703 // first_blocknum will be either msg.first_blocknum or a higher block height.
704 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
705 (true, msg.end_blocknum() - first_blocknum)
707 // Prior replies should use the number of blocks that fit into the reply. Overflow
708 // safe since first_blocknum is always <= last SCID's block.
710 (false, block_from_scid(*batch.last().unwrap()) - first_blocknum)
713 prev_batch_endblock = first_blocknum + number_of_blocks;
715 pending_events.push(MessageSendEvent::SendReplyChannelRange {
716 node_id: their_node_id.clone(),
717 msg: ReplyChannelRange {
718 chain_hash: msg.chain_hash.clone(),
722 short_channel_ids: batch,
730 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
733 err: String::from("Not implemented"),
734 action: ErrorAction::IgnoreError,
738 fn provided_node_features(&self) -> NodeFeatures {
739 let mut features = NodeFeatures::empty();
740 features.set_gossip_queries_optional();
744 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
745 let mut features = InitFeatures::empty();
746 features.set_gossip_queries_optional();
750 fn processing_queue_high(&self) -> bool {
751 self.network_graph.pending_checks.too_many_checks_pending()
755 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> MessageSendEventsProvider for P2PGossipSync<G, U, L>
757 U::Target: UtxoLookup,
760 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
761 let mut ret = Vec::new();
762 let mut pending_events = self.pending_events.lock().unwrap();
763 core::mem::swap(&mut ret, &mut pending_events);
768 #[derive(Clone, Debug, PartialEq, Eq)]
769 /// Details about one direction of a channel as received within a [`ChannelUpdate`].
770 pub struct ChannelUpdateInfo {
771 /// When the last update to the channel direction was issued.
772 /// Value is opaque, as set in the announcement.
773 pub last_update: u32,
774 /// Whether the channel can be currently used for payments (in this one direction).
776 /// The difference in CLTV values that you must have when routing through this channel.
777 pub cltv_expiry_delta: u16,
778 /// The minimum value, which must be relayed to the next hop via the channel
779 pub htlc_minimum_msat: u64,
780 /// The maximum value which may be relayed to the next hop via the channel.
781 pub htlc_maximum_msat: u64,
782 /// Fees charged when the channel is used for routing
783 pub fees: RoutingFees,
784 /// Most recent update for the channel received from the network
785 /// Mostly redundant with the data we store in fields explicitly.
786 /// Everything else is useful only for sending out for initial routing sync.
787 /// Not stored if contains excess data to prevent DoS.
788 pub last_update_message: Option<ChannelUpdate>,
791 impl fmt::Display for ChannelUpdateInfo {
792 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
793 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)?;
798 impl Writeable for ChannelUpdateInfo {
799 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
800 write_tlv_fields!(writer, {
801 (0, self.last_update, required),
802 (2, self.enabled, required),
803 (4, self.cltv_expiry_delta, required),
804 (6, self.htlc_minimum_msat, required),
805 // Writing htlc_maximum_msat as an Option<u64> is required to maintain backwards
806 // compatibility with LDK versions prior to v0.0.110.
807 (8, Some(self.htlc_maximum_msat), required),
808 (10, self.fees, required),
809 (12, self.last_update_message, required),
815 impl Readable for ChannelUpdateInfo {
816 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
817 _init_tlv_field_var!(last_update, required);
818 _init_tlv_field_var!(enabled, required);
819 _init_tlv_field_var!(cltv_expiry_delta, required);
820 _init_tlv_field_var!(htlc_minimum_msat, required);
821 _init_tlv_field_var!(htlc_maximum_msat, option);
822 _init_tlv_field_var!(fees, required);
823 _init_tlv_field_var!(last_update_message, required);
825 read_tlv_fields!(reader, {
826 (0, last_update, required),
827 (2, enabled, required),
828 (4, cltv_expiry_delta, required),
829 (6, htlc_minimum_msat, required),
830 (8, htlc_maximum_msat, required),
831 (10, fees, required),
832 (12, last_update_message, required)
835 if let Some(htlc_maximum_msat) = htlc_maximum_msat {
836 Ok(ChannelUpdateInfo {
837 last_update: _init_tlv_based_struct_field!(last_update, required),
838 enabled: _init_tlv_based_struct_field!(enabled, required),
839 cltv_expiry_delta: _init_tlv_based_struct_field!(cltv_expiry_delta, required),
840 htlc_minimum_msat: _init_tlv_based_struct_field!(htlc_minimum_msat, required),
842 fees: _init_tlv_based_struct_field!(fees, required),
843 last_update_message: _init_tlv_based_struct_field!(last_update_message, required),
846 Err(DecodeError::InvalidValue)
851 #[derive(Clone, Debug, PartialEq, Eq)]
852 /// Details about a channel (both directions).
853 /// Received within a channel announcement.
854 pub struct ChannelInfo {
855 /// Protocol features of a channel communicated during its announcement
856 pub features: ChannelFeatures,
857 /// Source node of the first direction of a channel
858 pub node_one: NodeId,
859 /// Details about the first direction of a channel
860 pub one_to_two: Option<ChannelUpdateInfo>,
861 /// Source node of the second direction of a channel
862 pub node_two: NodeId,
863 /// Details about the second direction of a channel
864 pub two_to_one: Option<ChannelUpdateInfo>,
865 /// The channel capacity as seen on-chain, if chain lookup is available.
866 pub capacity_sats: Option<u64>,
867 /// An initial announcement of the channel
868 /// Mostly redundant with the data we store in fields explicitly.
869 /// Everything else is useful only for sending out for initial routing sync.
870 /// Not stored if contains excess data to prevent DoS.
871 pub announcement_message: Option<ChannelAnnouncement>,
872 /// The timestamp when we received the announcement, if we are running with feature = "std"
873 /// (which we can probably assume we are - no-std environments probably won't have a full
874 /// network graph in memory!).
875 announcement_received_time: u64,
879 /// Returns a [`DirectedChannelInfo`] for the channel directed to the given `target` from a
880 /// returned `source`, or `None` if `target` is not one of the channel's counterparties.
881 pub fn as_directed_to(&self, target: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
882 let (direction, source, outbound) = {
883 if target == &self.node_one {
884 (self.two_to_one.as_ref(), &self.node_two, false)
885 } else if target == &self.node_two {
886 (self.one_to_two.as_ref(), &self.node_one, true)
891 direction.map(|dir| (DirectedChannelInfo::new(self, dir, outbound), source))
894 /// Returns a [`DirectedChannelInfo`] for the channel directed from the given `source` to a
895 /// returned `target`, or `None` if `source` is not one of the channel's counterparties.
896 pub fn as_directed_from(&self, source: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
897 let (direction, target, outbound) = {
898 if source == &self.node_one {
899 (self.one_to_two.as_ref(), &self.node_two, true)
900 } else if source == &self.node_two {
901 (self.two_to_one.as_ref(), &self.node_one, false)
906 direction.map(|dir| (DirectedChannelInfo::new(self, dir, outbound), target))
909 /// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag.
910 pub fn get_directional_info(&self, channel_flags: u8) -> Option<&ChannelUpdateInfo> {
911 let direction = channel_flags & 1u8;
913 self.one_to_two.as_ref()
915 self.two_to_one.as_ref()
920 impl fmt::Display for ChannelInfo {
921 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
922 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
923 log_bytes!(self.features.encode()), &self.node_one, self.one_to_two, &self.node_two, self.two_to_one)?;
928 impl Writeable for ChannelInfo {
929 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
930 write_tlv_fields!(writer, {
931 (0, self.features, required),
932 (1, self.announcement_received_time, (default_value, 0)),
933 (2, self.node_one, required),
934 (4, self.one_to_two, required),
935 (6, self.node_two, required),
936 (8, self.two_to_one, required),
937 (10, self.capacity_sats, required),
938 (12, self.announcement_message, required),
944 // A wrapper allowing for the optional deseralization of ChannelUpdateInfo. Utilizing this is
945 // necessary to maintain backwards compatibility with previous serializations of `ChannelUpdateInfo`
946 // that may have no `htlc_maximum_msat` field set. In case the field is absent, we simply ignore
947 // the error and continue reading the `ChannelInfo`. Hopefully, we'll then eventually receive newer
948 // channel updates via the gossip network.
949 struct ChannelUpdateInfoDeserWrapper(Option<ChannelUpdateInfo>);
951 impl MaybeReadable for ChannelUpdateInfoDeserWrapper {
952 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
953 match crate::util::ser::Readable::read(reader) {
954 Ok(channel_update_option) => Ok(Some(Self(channel_update_option))),
955 Err(DecodeError::ShortRead) => Ok(None),
956 Err(DecodeError::InvalidValue) => Ok(None),
957 Err(err) => Err(err),
962 impl Readable for ChannelInfo {
963 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
964 _init_tlv_field_var!(features, required);
965 _init_tlv_field_var!(announcement_received_time, (default_value, 0));
966 _init_tlv_field_var!(node_one, required);
967 let mut one_to_two_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
968 _init_tlv_field_var!(node_two, required);
969 let mut two_to_one_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
970 _init_tlv_field_var!(capacity_sats, required);
971 _init_tlv_field_var!(announcement_message, required);
972 read_tlv_fields!(reader, {
973 (0, features, required),
974 (1, announcement_received_time, (default_value, 0)),
975 (2, node_one, required),
976 (4, one_to_two_wrap, upgradable_option),
977 (6, node_two, required),
978 (8, two_to_one_wrap, upgradable_option),
979 (10, capacity_sats, required),
980 (12, announcement_message, required),
984 features: _init_tlv_based_struct_field!(features, required),
985 node_one: _init_tlv_based_struct_field!(node_one, required),
986 one_to_two: one_to_two_wrap.map(|w| w.0).unwrap_or(None),
987 node_two: _init_tlv_based_struct_field!(node_two, required),
988 two_to_one: two_to_one_wrap.map(|w| w.0).unwrap_or(None),
989 capacity_sats: _init_tlv_based_struct_field!(capacity_sats, required),
990 announcement_message: _init_tlv_based_struct_field!(announcement_message, required),
991 announcement_received_time: _init_tlv_based_struct_field!(announcement_received_time, (default_value, 0)),
996 /// A wrapper around [`ChannelInfo`] representing information about the channel as directed from a
997 /// source node to a target node.
999 pub struct DirectedChannelInfo<'a> {
1000 channel: &'a ChannelInfo,
1001 direction: &'a ChannelUpdateInfo,
1002 /// The direction this channel is in - if set, it indicates that we're traversing the channel
1003 /// from [`ChannelInfo::node_one`] to [`ChannelInfo::node_two`].
1004 from_node_one: bool,
1007 impl<'a> DirectedChannelInfo<'a> {
1009 fn new(channel: &'a ChannelInfo, direction: &'a ChannelUpdateInfo, from_node_one: bool) -> Self {
1010 Self { channel, direction, from_node_one }
1013 /// Returns information for the channel.
1015 pub fn channel(&self) -> &'a ChannelInfo { self.channel }
1017 /// Returns the [`EffectiveCapacity`] of the channel in the direction.
1019 /// This is either the total capacity from the funding transaction, if known, or the
1020 /// `htlc_maximum_msat` for the direction as advertised by the gossip network, if known,
1023 pub fn effective_capacity(&self) -> EffectiveCapacity {
1024 let mut htlc_maximum_msat = self.direction().htlc_maximum_msat;
1025 let capacity_msat = self.channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000);
1027 match capacity_msat {
1028 Some(capacity_msat) => {
1029 htlc_maximum_msat = cmp::min(htlc_maximum_msat, capacity_msat);
1030 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat }
1032 None => EffectiveCapacity::AdvertisedMaxHTLC { amount_msat: htlc_maximum_msat },
1036 /// Returns information for the direction.
1038 pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.direction }
1040 /// Returns the `node_id` of the source hop.
1042 /// Refers to the `node_id` forwarding the payment to the next hop.
1044 pub fn source(&self) -> &'a NodeId { if self.from_node_one { &self.channel.node_one } else { &self.channel.node_two } }
1046 /// Returns the `node_id` of the target hop.
1048 /// Refers to the `node_id` receiving the payment from the previous hop.
1050 pub fn target(&self) -> &'a NodeId { if self.from_node_one { &self.channel.node_two } else { &self.channel.node_one } }
1053 impl<'a> fmt::Debug for DirectedChannelInfo<'a> {
1054 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1055 f.debug_struct("DirectedChannelInfo")
1056 .field("channel", &self.channel)
1061 /// The effective capacity of a channel for routing purposes.
1063 /// While this may be smaller than the actual channel capacity, amounts greater than
1064 /// [`Self::as_msat`] should not be routed through the channel.
1065 #[derive(Clone, Copy, Debug, PartialEq)]
1066 pub enum EffectiveCapacity {
1067 /// The available liquidity in the channel known from being a channel counterparty, and thus a
1070 /// Either the inbound or outbound liquidity depending on the direction, denominated in
1072 liquidity_msat: u64,
1074 /// The maximum HTLC amount in one direction as advertised on the gossip network.
1076 /// The maximum HTLC amount denominated in millisatoshi.
1079 /// The total capacity of the channel as determined by the funding transaction.
1081 /// The funding amount denominated in millisatoshi.
1083 /// The maximum HTLC amount denominated in millisatoshi.
1084 htlc_maximum_msat: u64
1086 /// A capacity sufficient to route any payment, typically used for private channels provided by
1089 /// The maximum HTLC amount as provided by an invoice route hint.
1091 /// The maximum HTLC amount denominated in millisatoshi.
1094 /// A capacity that is unknown possibly because either the chain state is unavailable to know
1095 /// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
1099 /// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
1100 /// use when making routing decisions.
1101 pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
1103 impl EffectiveCapacity {
1104 /// Returns the effective capacity denominated in millisatoshi.
1105 pub fn as_msat(&self) -> u64 {
1107 EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
1108 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } => *amount_msat,
1109 EffectiveCapacity::Total { capacity_msat, .. } => *capacity_msat,
1110 EffectiveCapacity::HintMaxHTLC { amount_msat } => *amount_msat,
1111 EffectiveCapacity::Infinite => u64::max_value(),
1112 EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
1117 /// Fees for routing via a given channel or a node
1118 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash, Ord, PartialOrd)]
1119 pub struct RoutingFees {
1120 /// Flat routing fee in millisatoshis.
1122 /// Liquidity-based routing fee in millionths of a routed amount.
1123 /// In other words, 10000 is 1%.
1124 pub proportional_millionths: u32,
1127 impl_writeable_tlv_based!(RoutingFees, {
1128 (0, base_msat, required),
1129 (2, proportional_millionths, required)
1132 #[derive(Clone, Debug, PartialEq, Eq)]
1133 /// Non-relayable information received in the latest node_announcement from this node.
1134 pub struct NodeAnnouncementDetails {
1135 /// Protocol features the node announced support for
1136 pub features: NodeFeatures,
1138 /// When the last known update to the node state was issued.
1139 /// Value is opaque, as set in the announcement.
1140 pub last_update: u32,
1142 /// Color assigned to the node
1145 /// Moniker assigned to the node.
1146 /// May be invalid or malicious (eg control chars),
1147 /// should not be exposed to the user.
1148 pub alias: NodeAlias,
1150 /// Internet-level addresses via which one can connect to the node
1151 pub addresses: Vec<SocketAddress>,
1154 #[derive(Clone, Debug, PartialEq, Eq)]
1155 /// Information received in the latest node_announcement from this node.
1156 pub enum NodeAnnouncementInfo {
1157 /// An initial announcement of the node
1158 /// Everything else is useful only for sending out for initial routing sync.
1159 /// Not stored if contains excess data to prevent DoS.
1160 Relayed(NodeAnnouncement),
1162 /// Non-relayable information received in the latest node_announcement from this node.
1163 Local(NodeAnnouncementDetails),
1166 impl NodeAnnouncementInfo {
1168 /// Protocol features the node announced support for
1169 pub fn features(&self) -> &NodeFeatures {
1171 NodeAnnouncementInfo::Relayed(relayed) => {
1172 &relayed.contents.features
1174 NodeAnnouncementInfo::Local(local) => {
1180 /// When the last known update to the node state was issued.
1182 /// Value may or may not be a timestamp, depending on the policy of the origin node.
1183 pub fn last_update(&self) -> u32 {
1185 NodeAnnouncementInfo::Relayed(relayed) => {
1186 relayed.contents.timestamp
1188 NodeAnnouncementInfo::Local(local) => {
1194 /// Color assigned to the node
1195 pub fn rgb(&self) -> [u8; 3] {
1197 NodeAnnouncementInfo::Relayed(relayed) => {
1198 relayed.contents.rgb
1200 NodeAnnouncementInfo::Local(local) => {
1206 /// Moniker assigned to the node.
1208 /// May be invalid or malicious (eg control chars), should not be exposed to the user.
1209 pub fn alias(&self) -> &NodeAlias {
1211 NodeAnnouncementInfo::Relayed(relayed) => {
1212 &relayed.contents.alias
1214 NodeAnnouncementInfo::Local(local) => {
1220 /// Internet-level addresses via which one can connect to the node
1221 pub fn addresses(&self) -> &Vec<SocketAddress> {
1223 NodeAnnouncementInfo::Relayed(relayed) => {
1224 &relayed.contents.addresses
1226 NodeAnnouncementInfo::Local(local) => {
1232 /// An initial announcement of the node
1234 /// Not stored if contains excess data to prevent DoS.
1235 pub fn announcement_message(&self) -> Option<&NodeAnnouncement> {
1237 NodeAnnouncementInfo::Relayed(announcement) => {
1240 NodeAnnouncementInfo::Local(_) => {
1247 impl Writeable for NodeAnnouncementInfo {
1248 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1249 let features = self.features();
1250 let last_update = self.last_update();
1251 let rgb = self.rgb();
1252 let alias = self.alias();
1253 let addresses = self.addresses();
1254 let announcement_message = self.announcement_message();
1256 write_tlv_fields!(writer, {
1257 (0, features, required),
1258 (2, last_update, required),
1260 (6, alias, required),
1261 (8, announcement_message, option),
1262 (10, *addresses, required_vec), // Versions 0.0.115 through 0.0.123 only serialized an empty vec
1268 impl Readable for NodeAnnouncementInfo {
1269 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1270 _init_and_read_len_prefixed_tlv_fields!(reader, {
1271 (0, features, required),
1272 (2, last_update, required),
1274 (6, alias, required),
1275 (8, announcement_message, option),
1276 (10, addresses, required_vec),
1278 if let Some(announcement) = announcement_message {
1279 Ok(Self::Relayed(announcement))
1281 Ok(Self::Local(NodeAnnouncementDetails {
1282 features: features.0.unwrap(),
1283 last_update: last_update.0.unwrap(),
1284 rgb: rgb.0.unwrap(),
1285 alias: alias.0.unwrap(),
1292 /// A user-defined name for a node, which may be used when displaying the node in a graph.
1294 /// Since node aliases are provided by third parties, they are a potential avenue for injection
1295 /// attacks. Care must be taken when processing.
1296 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
1297 pub struct NodeAlias(pub [u8; 32]);
1299 impl fmt::Display for NodeAlias {
1300 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1301 let first_null = self.0.iter().position(|b| *b == 0).unwrap_or(self.0.len());
1302 let bytes = self.0.split_at(first_null).0;
1303 match core::str::from_utf8(bytes) {
1304 Ok(alias) => PrintableString(alias).fmt(f)?,
1306 use core::fmt::Write;
1307 for c in bytes.iter().map(|b| *b as char) {
1308 // Display printable ASCII characters
1309 let control_symbol = core::char::REPLACEMENT_CHARACTER;
1310 let c = if c >= '\x20' && c <= '\x7e' { c } else { control_symbol };
1319 impl Writeable for NodeAlias {
1320 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1325 impl Readable for NodeAlias {
1326 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
1327 Ok(NodeAlias(Readable::read(r)?))
1331 #[derive(Clone, Debug, PartialEq, Eq)]
1332 /// Details about a node in the network, known from the network announcement.
1333 pub struct NodeInfo {
1334 /// All valid channels a node has announced
1335 pub channels: Vec<u64>,
1336 /// More information about a node from node_announcement.
1337 /// Optional because we store a Node entry after learning about it from
1338 /// a channel announcement, but before receiving a node announcement.
1339 pub announcement_info: Option<NodeAnnouncementInfo>
1343 /// Returns whether the node has only announced Tor addresses.
1344 pub fn is_tor_only(&self) -> bool {
1345 self.announcement_info
1347 .map(|info| info.addresses())
1348 .and_then(|addresses| (!addresses.is_empty()).then(|| addresses))
1349 .map(|addresses| addresses.iter().all(|address| address.is_tor()))
1354 impl fmt::Display for NodeInfo {
1355 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1356 write!(f, " channels: {:?}, announcement_info: {:?}",
1357 &self.channels[..], self.announcement_info)?;
1362 impl Writeable for NodeInfo {
1363 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1364 write_tlv_fields!(writer, {
1365 // Note that older versions of LDK wrote the lowest inbound fees here at type 0
1366 (2, self.announcement_info, option),
1367 (4, self.channels, required_vec),
1373 // A wrapper allowing for the optional deserialization of `NodeAnnouncementInfo`. Utilizing this is
1374 // necessary to maintain compatibility with previous serializations of `SocketAddress` that have an
1375 // invalid hostname set. We ignore and eat all errors until we are either able to read a
1376 // `NodeAnnouncementInfo` or hit a `ShortRead`, i.e., read the TLV field to the end.
1377 struct NodeAnnouncementInfoDeserWrapper(NodeAnnouncementInfo);
1379 impl MaybeReadable for NodeAnnouncementInfoDeserWrapper {
1380 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
1381 match crate::util::ser::Readable::read(reader) {
1382 Ok(node_announcement_info) => return Ok(Some(Self(node_announcement_info))),
1384 copy(reader, &mut sink()).unwrap();
1391 impl Readable for NodeInfo {
1392 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1393 // Historically, we tracked the lowest inbound fees for any node in order to use it as an
1394 // A* heuristic when routing. Sadly, these days many, many nodes have at least one channel
1395 // with zero inbound fees, causing that heuristic to provide little gain. Worse, because it
1396 // requires additional complexity and lookups during routing, it ends up being a
1397 // performance loss. Thus, we simply ignore the old field here and no longer track it.
1398 _init_and_read_len_prefixed_tlv_fields!(reader, {
1399 (0, _lowest_inbound_channel_fees, option),
1400 (2, announcement_info_wrap, upgradable_option),
1401 (4, channels, required_vec),
1403 let _: Option<RoutingFees> = _lowest_inbound_channel_fees;
1404 let announcement_info_wrap: Option<NodeAnnouncementInfoDeserWrapper> = announcement_info_wrap;
1407 announcement_info: announcement_info_wrap.map(|w| w.0),
1413 const SERIALIZATION_VERSION: u8 = 1;
1414 const MIN_SERIALIZATION_VERSION: u8 = 1;
1416 impl<L: Deref> Writeable for NetworkGraph<L> where L::Target: Logger {
1417 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1418 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1420 self.chain_hash.write(writer)?;
1421 let channels = self.channels.read().unwrap();
1422 (channels.len() as u64).write(writer)?;
1423 for (ref chan_id, ref chan_info) in channels.unordered_iter() {
1424 (*chan_id).write(writer)?;
1425 chan_info.write(writer)?;
1427 let nodes = self.nodes.read().unwrap();
1428 (nodes.len() as u64).write(writer)?;
1429 for (ref node_id, ref node_info) in nodes.unordered_iter() {
1430 node_id.write(writer)?;
1431 node_info.write(writer)?;
1434 let last_rapid_gossip_sync_timestamp = self.get_last_rapid_gossip_sync_timestamp();
1435 write_tlv_fields!(writer, {
1436 (1, last_rapid_gossip_sync_timestamp, option),
1442 impl<L: Deref> ReadableArgs<L> for NetworkGraph<L> where L::Target: Logger {
1443 fn read<R: io::Read>(reader: &mut R, logger: L) -> Result<NetworkGraph<L>, DecodeError> {
1444 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1446 let chain_hash: ChainHash = Readable::read(reader)?;
1447 let channels_count: u64 = Readable::read(reader)?;
1448 // In Nov, 2023 there were about 15,000 nodes; we cap allocations to 1.5x that.
1449 let mut channels = IndexedMap::with_capacity(cmp::min(channels_count as usize, 22500));
1450 for _ in 0..channels_count {
1451 let chan_id: u64 = Readable::read(reader)?;
1452 let chan_info = Readable::read(reader)?;
1453 channels.insert(chan_id, chan_info);
1455 let nodes_count: u64 = Readable::read(reader)?;
1456 // In Nov, 2023 there were about 69K channels; we cap allocations to 1.5x that.
1457 let mut nodes = IndexedMap::with_capacity(cmp::min(nodes_count as usize, 103500));
1458 for _ in 0..nodes_count {
1459 let node_id = Readable::read(reader)?;
1460 let node_info = Readable::read(reader)?;
1461 nodes.insert(node_id, node_info);
1464 let mut last_rapid_gossip_sync_timestamp: Option<u32> = None;
1465 read_tlv_fields!(reader, {
1466 (1, last_rapid_gossip_sync_timestamp, option),
1470 secp_ctx: Secp256k1::verification_only(),
1473 channels: RwLock::new(channels),
1474 nodes: RwLock::new(nodes),
1475 last_rapid_gossip_sync_timestamp: Mutex::new(last_rapid_gossip_sync_timestamp),
1476 removed_nodes: Mutex::new(new_hash_map()),
1477 removed_channels: Mutex::new(new_hash_map()),
1478 pending_checks: utxo::PendingChecks::new(),
1483 impl<L: Deref> fmt::Display for NetworkGraph<L> where L::Target: Logger {
1484 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1485 writeln!(f, "Network map\n[Channels]")?;
1486 for (key, val) in self.channels.read().unwrap().unordered_iter() {
1487 writeln!(f, " {}: {}", key, val)?;
1489 writeln!(f, "[Nodes]")?;
1490 for (&node_id, val) in self.nodes.read().unwrap().unordered_iter() {
1491 writeln!(f, " {}: {}", &node_id, val)?;
1497 impl<L: Deref> Eq for NetworkGraph<L> where L::Target: Logger {}
1498 impl<L: Deref> PartialEq for NetworkGraph<L> where L::Target: Logger {
1499 fn eq(&self, other: &Self) -> bool {
1500 // For a total lockorder, sort by position in memory and take the inner locks in that order.
1501 // (Assumes that we can't move within memory while a lock is held).
1502 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1503 let a = if ord { (&self.channels, &self.nodes) } else { (&other.channels, &other.nodes) };
1504 let b = if ord { (&other.channels, &other.nodes) } else { (&self.channels, &self.nodes) };
1505 let (channels_a, channels_b) = (a.0.unsafe_well_ordered_double_lock_self(), b.0.unsafe_well_ordered_double_lock_self());
1506 let (nodes_a, nodes_b) = (a.1.unsafe_well_ordered_double_lock_self(), b.1.unsafe_well_ordered_double_lock_self());
1507 self.chain_hash.eq(&other.chain_hash) && channels_a.eq(&channels_b) && nodes_a.eq(&nodes_b)
1511 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
1512 /// Creates a new, empty, network graph.
1513 pub fn new(network: Network, logger: L) -> NetworkGraph<L> {
1515 secp_ctx: Secp256k1::verification_only(),
1516 chain_hash: ChainHash::using_genesis_block(network),
1518 channels: RwLock::new(IndexedMap::new()),
1519 nodes: RwLock::new(IndexedMap::new()),
1520 last_rapid_gossip_sync_timestamp: Mutex::new(None),
1521 removed_channels: Mutex::new(new_hash_map()),
1522 removed_nodes: Mutex::new(new_hash_map()),
1523 pending_checks: utxo::PendingChecks::new(),
1527 /// Returns a read-only view of the network graph.
1528 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
1529 let channels = self.channels.read().unwrap();
1530 let nodes = self.nodes.read().unwrap();
1531 ReadOnlyNetworkGraph {
1537 /// The unix timestamp provided by the most recent rapid gossip sync.
1538 /// It will be set by the rapid sync process after every sync completion.
1539 pub fn get_last_rapid_gossip_sync_timestamp(&self) -> Option<u32> {
1540 self.last_rapid_gossip_sync_timestamp.lock().unwrap().clone()
1543 /// Update the unix timestamp provided by the most recent rapid gossip sync.
1544 /// This should be done automatically by the rapid sync process after every sync completion.
1545 pub fn set_last_rapid_gossip_sync_timestamp(&self, last_rapid_gossip_sync_timestamp: u32) {
1546 self.last_rapid_gossip_sync_timestamp.lock().unwrap().replace(last_rapid_gossip_sync_timestamp);
1549 /// Clears the `NodeAnnouncementInfo` field for all nodes in the `NetworkGraph` for testing
1552 pub fn clear_nodes_announcement_info(&self) {
1553 for node in self.nodes.write().unwrap().unordered_iter_mut() {
1554 node.1.announcement_info = None;
1558 /// For an already known node (from channel announcements), update its stored properties from a
1559 /// given node announcement.
1561 /// You probably don't want to call this directly, instead relying on a P2PGossipSync's
1562 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1563 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1564 pub fn update_node_from_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), LightningError> {
1565 verify_node_announcement(msg, &self.secp_ctx)?;
1566 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1569 /// For an already known node (from channel announcements), update its stored properties from a
1570 /// given node announcement without verifying the associated signatures. Because we aren't
1571 /// given the associated signatures here we cannot relay the node announcement to any of our
1573 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1574 self.update_node_from_announcement_intern(msg, None)
1577 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1578 let mut nodes = self.nodes.write().unwrap();
1579 match nodes.get_mut(&msg.node_id) {
1581 core::mem::drop(nodes);
1582 self.pending_checks.check_hold_pending_node_announcement(msg, full_msg)?;
1583 Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError})
1586 if let Some(node_info) = node.announcement_info.as_ref() {
1587 // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
1588 // updates to ensure you always have the latest one, only vaguely suggesting
1589 // that it be at least the current time.
1590 if node_info.last_update() > msg.timestamp {
1591 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1592 } else if node_info.last_update() == msg.timestamp {
1593 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1598 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1599 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1600 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1602 node.announcement_info = if let (Some(signed_announcement), true) = (full_msg, should_relay) {
1603 Some(NodeAnnouncementInfo::Relayed(signed_announcement.clone()))
1605 Some(NodeAnnouncementInfo::Local(NodeAnnouncementDetails {
1606 features: msg.features.clone(),
1607 last_update: msg.timestamp,
1610 addresses: msg.addresses.clone(),
1619 /// Store or update channel info from a channel announcement.
1621 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1622 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1623 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1625 /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1626 /// the corresponding UTXO exists on chain and is correctly-formatted.
1627 pub fn update_channel_from_announcement<U: Deref>(
1628 &self, msg: &msgs::ChannelAnnouncement, utxo_lookup: &Option<U>,
1629 ) -> Result<(), LightningError>
1631 U::Target: UtxoLookup,
1633 verify_channel_announcement(msg, &self.secp_ctx)?;
1634 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), utxo_lookup)
1637 /// Store or update channel info from a channel announcement.
1639 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1640 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1641 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1643 /// This will skip verification of if the channel is actually on-chain.
1644 pub fn update_channel_from_announcement_no_lookup(
1645 &self, msg: &ChannelAnnouncement
1646 ) -> Result<(), LightningError> {
1647 self.update_channel_from_announcement::<&UtxoResolver>(msg, &None)
1650 /// Store or update channel info from a channel announcement without verifying the associated
1651 /// signatures. Because we aren't given the associated signatures here we cannot relay the
1652 /// channel announcement to any of our peers.
1654 /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1655 /// the corresponding UTXO exists on chain and is correctly-formatted.
1656 pub fn update_channel_from_unsigned_announcement<U: Deref>(
1657 &self, msg: &msgs::UnsignedChannelAnnouncement, utxo_lookup: &Option<U>
1658 ) -> Result<(), LightningError>
1660 U::Target: UtxoLookup,
1662 self.update_channel_from_unsigned_announcement_intern(msg, None, utxo_lookup)
1665 /// Update channel from partial announcement data received via rapid gossip sync
1667 /// `timestamp: u64`: Timestamp emulating the backdated original announcement receipt (by the
1668 /// rapid gossip sync server)
1670 /// All other parameters as used in [`msgs::UnsignedChannelAnnouncement`] fields.
1671 pub fn add_channel_from_partial_announcement(&self, short_channel_id: u64, timestamp: u64, features: ChannelFeatures, node_id_1: PublicKey, node_id_2: PublicKey) -> Result<(), LightningError> {
1672 if node_id_1 == node_id_2 {
1673 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1676 let node_1 = NodeId::from_pubkey(&node_id_1);
1677 let node_2 = NodeId::from_pubkey(&node_id_2);
1678 let channel_info = ChannelInfo {
1680 node_one: node_1.clone(),
1682 node_two: node_2.clone(),
1684 capacity_sats: None,
1685 announcement_message: None,
1686 announcement_received_time: timestamp,
1689 self.add_channel_between_nodes(short_channel_id, channel_info, None)
1692 fn add_channel_between_nodes(&self, short_channel_id: u64, channel_info: ChannelInfo, utxo_value: Option<u64>) -> Result<(), LightningError> {
1693 let mut channels = self.channels.write().unwrap();
1694 let mut nodes = self.nodes.write().unwrap();
1696 let node_id_a = channel_info.node_one.clone();
1697 let node_id_b = channel_info.node_two.clone();
1699 log_gossip!(self.logger, "Adding channel {} between nodes {} and {}", short_channel_id, node_id_a, node_id_b);
1701 match channels.entry(short_channel_id) {
1702 IndexedMapEntry::Occupied(mut entry) => {
1703 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1704 //in the blockchain API, we need to handle it smartly here, though it's unclear
1706 if utxo_value.is_some() {
1707 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1708 // only sometimes returns results. In any case remove the previous entry. Note
1709 // that the spec expects us to "blacklist" the node_ids involved, but we can't
1711 // a) we don't *require* a UTXO provider that always returns results.
1712 // b) we don't track UTXOs of channels we know about and remove them if they
1714 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1715 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), short_channel_id);
1716 *entry.get_mut() = channel_info;
1718 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1721 IndexedMapEntry::Vacant(entry) => {
1722 entry.insert(channel_info);
1726 for current_node_id in [node_id_a, node_id_b].iter() {
1727 match nodes.entry(current_node_id.clone()) {
1728 IndexedMapEntry::Occupied(node_entry) => {
1729 node_entry.into_mut().channels.push(short_channel_id);
1731 IndexedMapEntry::Vacant(node_entry) => {
1732 node_entry.insert(NodeInfo {
1733 channels: vec!(short_channel_id),
1734 announcement_info: None,
1743 fn update_channel_from_unsigned_announcement_intern<U: Deref>(
1744 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, utxo_lookup: &Option<U>
1745 ) -> Result<(), LightningError>
1747 U::Target: UtxoLookup,
1749 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1750 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1753 if msg.chain_hash != self.chain_hash {
1754 return Err(LightningError {
1755 err: "Channel announcement chain hash does not match genesis hash".to_owned(),
1756 action: ErrorAction::IgnoreAndLog(Level::Debug),
1761 let channels = self.channels.read().unwrap();
1763 if let Some(chan) = channels.get(&msg.short_channel_id) {
1764 if chan.capacity_sats.is_some() {
1765 // If we'd previously looked up the channel on-chain and checked the script
1766 // against what appears on-chain, ignore the duplicate announcement.
1768 // Because a reorg could replace one channel with another at the same SCID, if
1769 // the channel appears to be different, we re-validate. This doesn't expose us
1770 // to any more DoS risk than not, as a peer can always flood us with
1771 // randomly-generated SCID values anyway.
1773 // We use the Node IDs rather than the bitcoin_keys to check for "equivalence"
1774 // as we didn't (necessarily) store the bitcoin keys, and we only really care
1775 // if the peers on the channel changed anyway.
1776 if msg.node_id_1 == chan.node_one && msg.node_id_2 == chan.node_two {
1777 return Err(LightningError {
1778 err: "Already have chain-validated channel".to_owned(),
1779 action: ErrorAction::IgnoreDuplicateGossip
1782 } else if utxo_lookup.is_none() {
1783 // Similarly, if we can't check the chain right now anyway, ignore the
1784 // duplicate announcement without bothering to take the channels write lock.
1785 return Err(LightningError {
1786 err: "Already have non-chain-validated channel".to_owned(),
1787 action: ErrorAction::IgnoreDuplicateGossip
1794 let removed_channels = self.removed_channels.lock().unwrap();
1795 let removed_nodes = self.removed_nodes.lock().unwrap();
1796 if removed_channels.contains_key(&msg.short_channel_id) ||
1797 removed_nodes.contains_key(&msg.node_id_1) ||
1798 removed_nodes.contains_key(&msg.node_id_2) {
1799 return Err(LightningError{
1800 err: format!("Channel with SCID {} or one of its nodes was removed from our network graph recently", &msg.short_channel_id),
1801 action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1805 let utxo_value = self.pending_checks.check_channel_announcement(
1806 utxo_lookup, msg, full_msg)?;
1808 #[allow(unused_mut, unused_assignments)]
1809 let mut announcement_received_time = 0;
1810 #[cfg(feature = "std")]
1812 announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1815 let chan_info = ChannelInfo {
1816 features: msg.features.clone(),
1817 node_one: msg.node_id_1,
1819 node_two: msg.node_id_2,
1821 capacity_sats: utxo_value,
1822 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1823 { full_msg.cloned() } else { None },
1824 announcement_received_time,
1827 self.add_channel_between_nodes(msg.short_channel_id, chan_info, utxo_value)?;
1829 log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.short_channel_id, if !msg.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
1833 /// Marks a channel in the graph as failed permanently.
1835 /// The channel and any node for which this was their last channel are removed from the graph.
1836 pub fn channel_failed_permanent(&self, short_channel_id: u64) {
1837 #[cfg(feature = "std")]
1838 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1839 #[cfg(not(feature = "std"))]
1840 let current_time_unix = None;
1842 self.channel_failed_permanent_with_time(short_channel_id, current_time_unix)
1845 /// Marks a channel in the graph as failed permanently.
1847 /// The channel and any node for which this was their last channel are removed from the graph.
1848 fn channel_failed_permanent_with_time(&self, short_channel_id: u64, current_time_unix: Option<u64>) {
1849 let mut channels = self.channels.write().unwrap();
1850 if let Some(chan) = channels.remove(&short_channel_id) {
1851 let mut nodes = self.nodes.write().unwrap();
1852 self.removed_channels.lock().unwrap().insert(short_channel_id, current_time_unix);
1853 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1857 /// Marks a node in the graph as permanently failed, effectively removing it and its channels
1858 /// from local storage.
1859 pub fn node_failed_permanent(&self, node_id: &PublicKey) {
1860 #[cfg(feature = "std")]
1861 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1862 #[cfg(not(feature = "std"))]
1863 let current_time_unix = None;
1865 let node_id = NodeId::from_pubkey(node_id);
1866 let mut channels = self.channels.write().unwrap();
1867 let mut nodes = self.nodes.write().unwrap();
1868 let mut removed_channels = self.removed_channels.lock().unwrap();
1869 let mut removed_nodes = self.removed_nodes.lock().unwrap();
1871 if let Some(node) = nodes.remove(&node_id) {
1872 for scid in node.channels.iter() {
1873 if let Some(chan_info) = channels.remove(scid) {
1874 let other_node_id = if node_id == chan_info.node_one { chan_info.node_two } else { chan_info.node_one };
1875 if let IndexedMapEntry::Occupied(mut other_node_entry) = nodes.entry(other_node_id) {
1876 other_node_entry.get_mut().channels.retain(|chan_id| {
1879 if other_node_entry.get().channels.is_empty() {
1880 other_node_entry.remove_entry();
1883 removed_channels.insert(*scid, current_time_unix);
1886 removed_nodes.insert(node_id, current_time_unix);
1890 #[cfg(feature = "std")]
1891 /// Removes information about channels that we haven't heard any updates about in some time.
1892 /// This can be used regularly to prune the network graph of channels that likely no longer
1895 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1896 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1897 /// pruning occur for updates which are at least two weeks old, which we implement here.
1899 /// Note that for users of the `lightning-background-processor` crate this method may be
1900 /// automatically called regularly for you.
1902 /// This method will also cause us to stop tracking removed nodes and channels if they have been
1903 /// in the map for a while so that these can be resynced from gossip in the future.
1905 /// This method is only available with the `std` feature. See
1906 /// [`NetworkGraph::remove_stale_channels_and_tracking_with_time`] for `no-std` use.
1907 pub fn remove_stale_channels_and_tracking(&self) {
1908 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1909 self.remove_stale_channels_and_tracking_with_time(time);
1912 /// Removes information about channels that we haven't heard any updates about in some time.
1913 /// This can be used regularly to prune the network graph of channels that likely no longer
1916 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1917 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1918 /// pruning occur for updates which are at least two weeks old, which we implement here.
1920 /// This method will also cause us to stop tracking removed nodes and channels if they have been
1921 /// in the map for a while so that these can be resynced from gossip in the future.
1923 /// This function takes the current unix time as an argument. For users with the `std` feature
1924 /// enabled, [`NetworkGraph::remove_stale_channels_and_tracking`] may be preferable.
1925 pub fn remove_stale_channels_and_tracking_with_time(&self, current_time_unix: u64) {
1926 let mut channels = self.channels.write().unwrap();
1927 // Time out if we haven't received an update in at least 14 days.
1928 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1929 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1930 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1931 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1933 let mut scids_to_remove = Vec::new();
1934 for (scid, info) in channels.unordered_iter_mut() {
1935 if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1936 log_gossip!(self.logger, "Removing directional update one_to_two (0) for channel {} due to its timestamp {} being below {}",
1937 scid, info.one_to_two.as_ref().unwrap().last_update, min_time_unix);
1938 info.one_to_two = None;
1940 if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1941 log_gossip!(self.logger, "Removing directional update two_to_one (1) for channel {} due to its timestamp {} being below {}",
1942 scid, info.two_to_one.as_ref().unwrap().last_update, min_time_unix);
1943 info.two_to_one = None;
1945 if info.one_to_two.is_none() || info.two_to_one.is_none() {
1946 // We check the announcement_received_time here to ensure we don't drop
1947 // announcements that we just received and are just waiting for our peer to send a
1948 // channel_update for.
1949 let announcement_received_timestamp = info.announcement_received_time;
1950 if announcement_received_timestamp < min_time_unix as u64 {
1951 log_gossip!(self.logger, "Removing channel {} because both directional updates are missing and its announcement timestamp {} being below {}",
1952 scid, announcement_received_timestamp, min_time_unix);
1953 scids_to_remove.push(*scid);
1957 if !scids_to_remove.is_empty() {
1958 let mut nodes = self.nodes.write().unwrap();
1959 for scid in scids_to_remove {
1960 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1961 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
1962 self.removed_channels.lock().unwrap().insert(scid, Some(current_time_unix));
1966 let should_keep_tracking = |time: &mut Option<u64>| {
1967 if let Some(time) = time {
1968 current_time_unix.saturating_sub(*time) < REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS
1970 // NOTE: In the case of no-std, we won't have access to the current UNIX time at the time of removal,
1971 // so we'll just set the removal time here to the current UNIX time on the very next invocation
1972 // of this function.
1973 #[cfg(not(feature = "std"))]
1975 let mut tracked_time = Some(current_time_unix);
1976 core::mem::swap(time, &mut tracked_time);
1979 #[allow(unreachable_code)]
1983 self.removed_channels.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1984 self.removed_nodes.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1987 /// For an already known (from announcement) channel, update info about one of the directions
1990 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1991 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1992 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1994 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1995 /// materially in the future will be rejected.
1996 pub fn update_channel(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
1997 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), false)
2000 /// For an already known (from announcement) channel, update info about one of the directions
2001 /// of the channel without verifying the associated signatures. Because we aren't given the
2002 /// associated signatures here we cannot relay the channel update to any of our peers.
2004 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
2005 /// materially in the future will be rejected.
2006 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
2007 self.update_channel_internal(msg, None, None, false)
2010 /// For an already known (from announcement) channel, verify the given [`ChannelUpdate`].
2012 /// This checks whether the update currently is applicable by [`Self::update_channel`].
2014 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
2015 /// materially in the future will be rejected.
2016 pub fn verify_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
2017 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), true)
2020 fn update_channel_internal(&self, msg: &msgs::UnsignedChannelUpdate,
2021 full_msg: Option<&msgs::ChannelUpdate>, sig: Option<&secp256k1::ecdsa::Signature>,
2022 only_verify: bool) -> Result<(), LightningError>
2024 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
2026 if msg.chain_hash != self.chain_hash {
2027 return Err(LightningError {
2028 err: "Channel update chain hash does not match genesis hash".to_owned(),
2029 action: ErrorAction::IgnoreAndLog(Level::Debug),
2033 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
2035 // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
2036 // disable this check during tests!
2037 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2038 if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
2039 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
2041 if msg.timestamp as u64 > time + 60 * 60 * 24 {
2042 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
2046 log_gossip!(self.logger, "Updating channel {} in direction {} with timestamp {}", msg.short_channel_id, msg.flags & 1, msg.timestamp);
2048 let mut channels = self.channels.write().unwrap();
2049 match channels.get_mut(&msg.short_channel_id) {
2051 core::mem::drop(channels);
2052 self.pending_checks.check_hold_pending_channel_update(msg, full_msg)?;
2053 return Err(LightningError {
2054 err: "Couldn't find channel for update".to_owned(),
2055 action: ErrorAction::IgnoreAndLog(Level::Gossip),
2059 if msg.htlc_maximum_msat > MAX_VALUE_MSAT {
2060 return Err(LightningError{err:
2061 "htlc_maximum_msat is larger than maximum possible msats".to_owned(),
2062 action: ErrorAction::IgnoreError});
2065 if let Some(capacity_sats) = channel.capacity_sats {
2066 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
2067 // Don't query UTXO set here to reduce DoS risks.
2068 if capacity_sats > MAX_VALUE_MSAT / 1000 || msg.htlc_maximum_msat > capacity_sats * 1000 {
2069 return Err(LightningError{err:
2070 "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(),
2071 action: ErrorAction::IgnoreError});
2074 macro_rules! check_update_latest {
2075 ($target: expr) => {
2076 if let Some(existing_chan_info) = $target.as_ref() {
2077 // The timestamp field is somewhat of a misnomer - the BOLTs use it to
2078 // order updates to ensure you always have the latest one, only
2079 // suggesting that it be at least the current time. For
2080 // channel_updates specifically, the BOLTs discuss the possibility of
2081 // pruning based on the timestamp field being more than two weeks old,
2082 // but only in the non-normative section.
2083 if existing_chan_info.last_update > msg.timestamp {
2084 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2085 } else if existing_chan_info.last_update == msg.timestamp {
2086 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2092 macro_rules! get_new_channel_info {
2094 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
2095 { full_msg.cloned() } else { None };
2097 let updated_channel_update_info = ChannelUpdateInfo {
2098 enabled: chan_enabled,
2099 last_update: msg.timestamp,
2100 cltv_expiry_delta: msg.cltv_expiry_delta,
2101 htlc_minimum_msat: msg.htlc_minimum_msat,
2102 htlc_maximum_msat: msg.htlc_maximum_msat,
2104 base_msat: msg.fee_base_msat,
2105 proportional_millionths: msg.fee_proportional_millionths,
2109 Some(updated_channel_update_info)
2113 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg)[..]);
2114 if msg.flags & 1 == 1 {
2115 check_update_latest!(channel.two_to_one);
2116 if let Some(sig) = sig {
2117 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
2118 err: "Couldn't parse source node pubkey".to_owned(),
2119 action: ErrorAction::IgnoreAndLog(Level::Debug)
2120 })?, "channel_update");
2123 channel.two_to_one = get_new_channel_info!();
2126 check_update_latest!(channel.one_to_two);
2127 if let Some(sig) = sig {
2128 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
2129 err: "Couldn't parse destination node pubkey".to_owned(),
2130 action: ErrorAction::IgnoreAndLog(Level::Debug)
2131 })?, "channel_update");
2134 channel.one_to_two = get_new_channel_info!();
2143 fn remove_channel_in_nodes(nodes: &mut IndexedMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
2144 macro_rules! remove_from_node {
2145 ($node_id: expr) => {
2146 if let IndexedMapEntry::Occupied(mut entry) = nodes.entry($node_id) {
2147 entry.get_mut().channels.retain(|chan_id| {
2148 short_channel_id != *chan_id
2150 if entry.get().channels.is_empty() {
2151 entry.remove_entry();
2154 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
2159 remove_from_node!(chan.node_one);
2160 remove_from_node!(chan.node_two);
2164 impl ReadOnlyNetworkGraph<'_> {
2165 /// Returns all known valid channels' short ids along with announced channel info.
2167 /// This is not exported to bindings users because we don't want to return lifetime'd references
2168 pub fn channels(&self) -> &IndexedMap<u64, ChannelInfo> {
2172 /// Returns information on a channel with the given id.
2173 pub fn channel(&self, short_channel_id: u64) -> Option<&ChannelInfo> {
2174 self.channels.get(&short_channel_id)
2177 #[cfg(c_bindings)] // Non-bindings users should use `channels`
2178 /// Returns the list of channels in the graph
2179 pub fn list_channels(&self) -> Vec<u64> {
2180 self.channels.unordered_keys().map(|c| *c).collect()
2183 /// Returns all known nodes' public keys along with announced node info.
2185 /// This is not exported to bindings users because we don't want to return lifetime'd references
2186 pub fn nodes(&self) -> &IndexedMap<NodeId, NodeInfo> {
2190 /// Returns information on a node with the given id.
2191 pub fn node(&self, node_id: &NodeId) -> Option<&NodeInfo> {
2192 self.nodes.get(node_id)
2195 #[cfg(c_bindings)] // Non-bindings users should use `nodes`
2196 /// Returns the list of nodes in the graph
2197 pub fn list_nodes(&self) -> Vec<NodeId> {
2198 self.nodes.unordered_keys().map(|n| *n).collect()
2201 /// Get network addresses by node id.
2202 /// Returns None if the requested node is completely unknown,
2203 /// or if node announcement for the node was never received.
2204 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<SocketAddress>> {
2205 self.nodes.get(&NodeId::from_pubkey(&pubkey))
2206 .and_then(|node| node.announcement_info.as_ref().map(|ann| ann.addresses().to_vec()))
2211 pub(crate) mod tests {
2212 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
2213 use crate::ln::channelmanager;
2214 use crate::ln::chan_utils::make_funding_redeemscript;
2215 #[cfg(feature = "std")]
2216 use crate::ln::features::InitFeatures;
2217 use crate::ln::msgs::SocketAddress;
2218 use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, NodeAlias, MAX_EXCESS_BYTES_FOR_RELAY, NodeId, RoutingFees, ChannelUpdateInfo, ChannelInfo, NodeAnnouncementInfo, NodeInfo};
2219 use crate::routing::utxo::{UtxoLookupError, UtxoResult};
2220 use crate::ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
2221 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
2222 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
2223 use crate::util::config::UserConfig;
2224 use crate::util::test_utils;
2225 use crate::util::ser::{Hostname, ReadableArgs, Readable, Writeable};
2226 use crate::util::scid_utils::scid_from_parts;
2228 use crate::routing::gossip::REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS;
2229 use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
2231 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
2232 use bitcoin::hashes::Hash;
2233 use bitcoin::hashes::hex::FromHex;
2234 use bitcoin::network::constants::Network;
2235 use bitcoin::blockdata::constants::ChainHash;
2236 use bitcoin::blockdata::script::ScriptBuf;
2237 use bitcoin::blockdata::transaction::TxOut;
2238 use bitcoin::secp256k1::{PublicKey, SecretKey};
2239 use bitcoin::secp256k1::{All, Secp256k1};
2242 use bitcoin::secp256k1;
2243 use crate::prelude::*;
2244 use crate::sync::Arc;
2246 fn create_network_graph() -> NetworkGraph<Arc<test_utils::TestLogger>> {
2247 let logger = Arc::new(test_utils::TestLogger::new());
2248 NetworkGraph::new(Network::Testnet, logger)
2251 fn create_gossip_sync(network_graph: &NetworkGraph<Arc<test_utils::TestLogger>>) -> (
2252 Secp256k1<All>, P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>,
2253 Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
2255 let secp_ctx = Secp256k1::new();
2256 let logger = Arc::new(test_utils::TestLogger::new());
2257 let gossip_sync = P2PGossipSync::new(network_graph, None, Arc::clone(&logger));
2258 (secp_ctx, gossip_sync)
2262 #[cfg(feature = "std")]
2263 fn request_full_sync_finite_times() {
2264 let network_graph = create_network_graph();
2265 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2266 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
2268 assert!(gossip_sync.should_request_full_sync(&node_id));
2269 assert!(gossip_sync.should_request_full_sync(&node_id));
2270 assert!(gossip_sync.should_request_full_sync(&node_id));
2271 assert!(gossip_sync.should_request_full_sync(&node_id));
2272 assert!(gossip_sync.should_request_full_sync(&node_id));
2273 assert!(!gossip_sync.should_request_full_sync(&node_id));
2276 pub(crate) fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
2277 let node_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_key));
2278 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2279 features: channelmanager::provided_node_features(&UserConfig::default()),
2283 alias: NodeAlias([0; 32]),
2284 addresses: Vec::new(),
2285 excess_address_data: Vec::new(),
2286 excess_data: Vec::new(),
2288 f(&mut unsigned_announcement);
2289 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2291 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2292 contents: unsigned_announcement
2296 pub(crate) 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 {
2297 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
2298 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
2299 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2300 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2302 let mut unsigned_announcement = UnsignedChannelAnnouncement {
2303 features: channelmanager::provided_channel_features(&UserConfig::default()),
2304 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2305 short_channel_id: 0,
2306 node_id_1: NodeId::from_pubkey(&node_id_1),
2307 node_id_2: NodeId::from_pubkey(&node_id_2),
2308 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey)),
2309 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey)),
2310 excess_data: Vec::new(),
2312 f(&mut unsigned_announcement);
2313 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2314 ChannelAnnouncement {
2315 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_key),
2316 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_key),
2317 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_btckey),
2318 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_btckey),
2319 contents: unsigned_announcement,
2323 pub(crate) fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> ScriptBuf {
2324 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
2325 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
2326 make_funding_redeemscript(&PublicKey::from_secret_key(secp_ctx, &node_1_btckey),
2327 &PublicKey::from_secret_key(secp_ctx, &node_2_btckey)).to_v0_p2wsh()
2330 pub(crate) fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
2331 let mut unsigned_channel_update = UnsignedChannelUpdate {
2332 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2333 short_channel_id: 0,
2336 cltv_expiry_delta: 144,
2337 htlc_minimum_msat: 1_000_000,
2338 htlc_maximum_msat: 1_000_000,
2339 fee_base_msat: 10_000,
2340 fee_proportional_millionths: 20,
2341 excess_data: Vec::new()
2343 f(&mut unsigned_channel_update);
2344 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2346 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2347 contents: unsigned_channel_update
2352 fn handling_node_announcements() {
2353 let network_graph = create_network_graph();
2354 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2356 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2357 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2358 let zero_hash = Sha256dHash::hash(&[0; 32]);
2360 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2361 match gossip_sync.handle_node_announcement(&valid_announcement) {
2363 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
2367 // Announce a channel to add a corresponding node.
2368 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2369 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2370 Ok(res) => assert!(res),
2375 match gossip_sync.handle_node_announcement(&valid_announcement) {
2376 Ok(res) => assert!(res),
2380 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2381 match gossip_sync.handle_node_announcement(
2383 signature: secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey),
2384 contents: valid_announcement.contents.clone()
2387 Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
2390 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
2391 unsigned_announcement.timestamp += 1000;
2392 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2393 }, node_1_privkey, &secp_ctx);
2394 // Return false because contains excess data.
2395 match gossip_sync.handle_node_announcement(&announcement_with_data) {
2396 Ok(res) => assert!(!res),
2400 // Even though previous announcement was not relayed further, we still accepted it,
2401 // so we now won't accept announcements before the previous one.
2402 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
2403 unsigned_announcement.timestamp += 1000 - 10;
2404 }, node_1_privkey, &secp_ctx);
2405 match gossip_sync.handle_node_announcement(&outdated_announcement) {
2407 Err(e) => assert_eq!(e.err, "Update older than last processed update")
2412 fn handling_channel_announcements() {
2413 let secp_ctx = Secp256k1::new();
2414 let logger = test_utils::TestLogger::new();
2416 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2417 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2419 let good_script = get_channel_script(&secp_ctx);
2420 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2422 // Test if the UTXO lookups were not supported
2423 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2424 let mut gossip_sync = P2PGossipSync::new(&network_graph, None, &logger);
2425 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2426 Ok(res) => assert!(res),
2431 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2437 // If we receive announcement for the same channel (with UTXO lookups disabled),
2438 // drop new one on the floor, since we can't see any changes.
2439 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2441 Err(e) => assert_eq!(e.err, "Already have non-chain-validated channel")
2444 // Test if an associated transaction were not on-chain (or not confirmed).
2445 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2446 *chain_source.utxo_ret.lock().unwrap() = UtxoResult::Sync(Err(UtxoLookupError::UnknownTx));
2447 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2448 gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2450 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2451 unsigned_announcement.short_channel_id += 1;
2452 }, node_1_privkey, node_2_privkey, &secp_ctx);
2453 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2455 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2458 // Now test if the transaction is found in the UTXO set and the script is correct.
2459 *chain_source.utxo_ret.lock().unwrap() =
2460 UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script.clone() }));
2461 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2462 unsigned_announcement.short_channel_id += 2;
2463 }, node_1_privkey, node_2_privkey, &secp_ctx);
2464 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2465 Ok(res) => assert!(res),
2470 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2476 // If we receive announcement for the same channel, once we've validated it against the
2477 // chain, we simply ignore all new (duplicate) announcements.
2478 *chain_source.utxo_ret.lock().unwrap() =
2479 UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script }));
2480 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2482 Err(e) => assert_eq!(e.err, "Already have chain-validated channel")
2485 #[cfg(feature = "std")]
2487 use std::time::{SystemTime, UNIX_EPOCH};
2489 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2490 // Mark a node as permanently failed so it's tracked as removed.
2491 gossip_sync.network_graph().node_failed_permanent(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2493 // Return error and ignore valid channel announcement if one of the nodes has been tracked as removed.
2494 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2495 unsigned_announcement.short_channel_id += 3;
2496 }, node_1_privkey, node_2_privkey, &secp_ctx);
2497 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2499 Err(e) => assert_eq!(e.err, "Channel with SCID 3 or one of its nodes was removed from our network graph recently")
2502 gossip_sync.network_graph().remove_stale_channels_and_tracking_with_time(tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2504 // The above channel announcement should be handled as per normal now.
2505 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2506 Ok(res) => assert!(res),
2511 // Don't relay valid channels with excess data
2512 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2513 unsigned_announcement.short_channel_id += 4;
2514 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2515 }, node_1_privkey, node_2_privkey, &secp_ctx);
2516 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2517 Ok(res) => assert!(!res),
2521 let mut invalid_sig_announcement = valid_announcement.clone();
2522 invalid_sig_announcement.contents.excess_data = Vec::new();
2523 match gossip_sync.handle_channel_announcement(&invalid_sig_announcement) {
2525 Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
2528 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
2529 match gossip_sync.handle_channel_announcement(&channel_to_itself_announcement) {
2531 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2534 // Test that channel announcements with the wrong chain hash are ignored (network graph is testnet,
2535 // announcement is mainnet).
2536 let incorrect_chain_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2537 unsigned_announcement.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2538 }, node_1_privkey, node_2_privkey, &secp_ctx);
2539 match gossip_sync.handle_channel_announcement(&incorrect_chain_announcement) {
2541 Err(e) => assert_eq!(e.err, "Channel announcement chain hash does not match genesis hash")
2546 fn handling_channel_update() {
2547 let secp_ctx = Secp256k1::new();
2548 let logger = test_utils::TestLogger::new();
2549 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2550 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2551 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2553 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2554 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2556 let amount_sats = 1000_000;
2557 let short_channel_id;
2560 // Announce a channel we will update
2561 let good_script = get_channel_script(&secp_ctx);
2562 *chain_source.utxo_ret.lock().unwrap() =
2563 UtxoResult::Sync(Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() }));
2565 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2566 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2567 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2574 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2575 network_graph.verify_channel_update(&valid_channel_update).unwrap();
2576 match gossip_sync.handle_channel_update(&valid_channel_update) {
2577 Ok(res) => assert!(res),
2582 match network_graph.read_only().channels().get(&short_channel_id) {
2584 Some(channel_info) => {
2585 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
2586 assert!(channel_info.two_to_one.is_none());
2591 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2592 unsigned_channel_update.timestamp += 100;
2593 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2594 }, node_1_privkey, &secp_ctx);
2595 // Return false because contains excess data
2596 match gossip_sync.handle_channel_update(&valid_channel_update) {
2597 Ok(res) => assert!(!res),
2601 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2602 unsigned_channel_update.timestamp += 110;
2603 unsigned_channel_update.short_channel_id += 1;
2604 }, node_1_privkey, &secp_ctx);
2605 match gossip_sync.handle_channel_update(&valid_channel_update) {
2607 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2610 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2611 unsigned_channel_update.htlc_maximum_msat = MAX_VALUE_MSAT + 1;
2612 unsigned_channel_update.timestamp += 110;
2613 }, node_1_privkey, &secp_ctx);
2614 match gossip_sync.handle_channel_update(&valid_channel_update) {
2616 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
2619 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2620 unsigned_channel_update.htlc_maximum_msat = amount_sats * 1000 + 1;
2621 unsigned_channel_update.timestamp += 110;
2622 }, node_1_privkey, &secp_ctx);
2623 match gossip_sync.handle_channel_update(&valid_channel_update) {
2625 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
2628 // Even though previous update was not relayed further, we still accepted it,
2629 // so we now won't accept update before the previous one.
2630 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2631 unsigned_channel_update.timestamp += 100;
2632 }, node_1_privkey, &secp_ctx);
2633 match gossip_sync.handle_channel_update(&valid_channel_update) {
2635 Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
2638 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2639 unsigned_channel_update.timestamp += 500;
2640 }, node_1_privkey, &secp_ctx);
2641 let zero_hash = Sha256dHash::hash(&[0; 32]);
2642 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2643 invalid_sig_channel_update.signature = secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey);
2644 match gossip_sync.handle_channel_update(&invalid_sig_channel_update) {
2646 Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
2649 // Test that channel updates with the wrong chain hash are ignored (network graph is testnet, channel
2650 // update is mainet).
2651 let incorrect_chain_update = get_signed_channel_update(|unsigned_channel_update| {
2652 unsigned_channel_update.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2653 }, node_1_privkey, &secp_ctx);
2655 match gossip_sync.handle_channel_update(&incorrect_chain_update) {
2657 Err(e) => assert_eq!(e.err, "Channel update chain hash does not match genesis hash")
2662 fn handling_network_update() {
2663 let logger = test_utils::TestLogger::new();
2664 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2665 let secp_ctx = Secp256k1::new();
2667 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2668 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2669 let node_2_id = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2672 // There is no nodes in the table at the beginning.
2673 assert_eq!(network_graph.read_only().nodes().len(), 0);
2676 let short_channel_id;
2678 // Check we won't apply an update via `handle_network_update` for privacy reasons, but
2679 // can continue fine if we manually apply it.
2680 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2681 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2682 let chain_source: Option<&test_utils::TestChainSource> = None;
2683 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2684 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2686 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2687 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2689 network_graph.handle_network_update(&NetworkUpdate::ChannelUpdateMessage {
2690 msg: valid_channel_update.clone(),
2693 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2694 network_graph.update_channel(&valid_channel_update).unwrap();
2697 // Non-permanent failure doesn't touch the channel at all
2699 match network_graph.read_only().channels().get(&short_channel_id) {
2701 Some(channel_info) => {
2702 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2706 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2708 is_permanent: false,
2711 match network_graph.read_only().channels().get(&short_channel_id) {
2713 Some(channel_info) => {
2714 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2719 // Permanent closing deletes a channel
2720 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2725 assert_eq!(network_graph.read_only().channels().len(), 0);
2726 // Nodes are also deleted because there are no associated channels anymore
2727 assert_eq!(network_graph.read_only().nodes().len(), 0);
2730 // Get a new network graph since we don't want to track removed nodes in this test with "std"
2731 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2733 // Announce a channel to test permanent node failure
2734 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2735 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2736 let chain_source: Option<&test_utils::TestChainSource> = None;
2737 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2738 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2740 // Non-permanent node failure does not delete any nodes or channels
2741 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2743 is_permanent: false,
2746 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2747 assert!(network_graph.read_only().nodes().get(&NodeId::from_pubkey(&node_2_id)).is_some());
2749 // Permanent node failure deletes node and its channels
2750 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2755 assert_eq!(network_graph.read_only().nodes().len(), 0);
2756 // Channels are also deleted because the associated node has been deleted
2757 assert_eq!(network_graph.read_only().channels().len(), 0);
2762 fn test_channel_timeouts() {
2763 // Test the removal of channels with `remove_stale_channels_and_tracking`.
2764 let logger = test_utils::TestLogger::new();
2765 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2766 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2767 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2768 let secp_ctx = Secp256k1::new();
2770 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2771 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2773 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2774 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2775 let chain_source: Option<&test_utils::TestChainSource> = None;
2776 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2777 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2779 // Submit two channel updates for each channel direction (update.flags bit).
2780 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2781 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2782 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2784 let valid_channel_update_2 = get_signed_channel_update(|update| {update.flags |=1;}, node_2_privkey, &secp_ctx);
2785 gossip_sync.handle_channel_update(&valid_channel_update_2).unwrap();
2786 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().two_to_one.is_some());
2788 network_graph.remove_stale_channels_and_tracking_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2789 assert_eq!(network_graph.read_only().channels().len(), 1);
2790 assert_eq!(network_graph.read_only().nodes().len(), 2);
2792 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2793 #[cfg(not(feature = "std"))] {
2794 // Make sure removed channels are tracked.
2795 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2797 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2798 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2800 #[cfg(feature = "std")]
2802 // In std mode, a further check is performed before fully removing the channel -
2803 // the channel_announcement must have been received at least two weeks ago. We
2804 // fudge that here by indicating the time has jumped two weeks.
2805 assert_eq!(network_graph.read_only().channels().len(), 1);
2806 assert_eq!(network_graph.read_only().nodes().len(), 2);
2808 // Note that the directional channel information will have been removed already..
2809 // We want to check that this will work even if *one* of the channel updates is recent,
2810 // so we should add it with a recent timestamp.
2811 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2812 use std::time::{SystemTime, UNIX_EPOCH};
2813 let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2814 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2815 unsigned_channel_update.timestamp = (announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
2816 }, node_1_privkey, &secp_ctx);
2817 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2818 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2819 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2820 // Make sure removed channels are tracked.
2821 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2822 // Provide a later time so that sufficient time has passed
2823 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2824 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2827 assert_eq!(network_graph.read_only().channels().len(), 0);
2828 assert_eq!(network_graph.read_only().nodes().len(), 0);
2829 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2831 #[cfg(feature = "std")]
2833 use std::time::{SystemTime, UNIX_EPOCH};
2835 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2837 // Clear tracked nodes and channels for clean slate
2838 network_graph.removed_channels.lock().unwrap().clear();
2839 network_graph.removed_nodes.lock().unwrap().clear();
2841 // Add a channel and nodes from channel announcement. So our network graph will
2842 // now only consist of two nodes and one channel between them.
2843 assert!(network_graph.update_channel_from_announcement(
2844 &valid_channel_announcement, &chain_source).is_ok());
2846 // Mark the channel as permanently failed. This will also remove the two nodes
2847 // and all of the entries will be tracked as removed.
2848 network_graph.channel_failed_permanent_with_time(short_channel_id, Some(tracking_time));
2850 // Should not remove from tracking if insufficient time has passed
2851 network_graph.remove_stale_channels_and_tracking_with_time(
2852 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS - 1);
2853 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1, "Removed channel count ≠1 with tracking_time {}", tracking_time);
2855 // Provide a later time so that sufficient time has passed
2856 network_graph.remove_stale_channels_and_tracking_with_time(
2857 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2858 assert!(network_graph.removed_channels.lock().unwrap().is_empty(), "Unexpectedly removed channels with tracking_time {}", tracking_time);
2859 assert!(network_graph.removed_nodes.lock().unwrap().is_empty(), "Unexpectedly removed nodes with tracking_time {}", tracking_time);
2862 #[cfg(not(feature = "std"))]
2864 // When we don't have access to the system clock, the time we started tracking removal will only
2865 // be that provided by the first call to `remove_stale_channels_and_tracking_with_time`. Hence,
2866 // only if sufficient time has passed after that first call, will the next call remove it from
2868 let removal_time = 1664619654;
2870 // Clear removed nodes and channels for clean slate
2871 network_graph.removed_channels.lock().unwrap().clear();
2872 network_graph.removed_nodes.lock().unwrap().clear();
2874 // Add a channel and nodes from channel announcement. So our network graph will
2875 // now only consist of two nodes and one channel between them.
2876 assert!(network_graph.update_channel_from_announcement(
2877 &valid_channel_announcement, &chain_source).is_ok());
2879 // Mark the channel as permanently failed. This will also remove the two nodes
2880 // and all of the entries will be tracked as removed.
2881 network_graph.channel_failed_permanent(short_channel_id);
2883 // The first time we call the following, the channel will have a removal time assigned.
2884 network_graph.remove_stale_channels_and_tracking_with_time(removal_time);
2885 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2887 // Provide a later time so that sufficient time has passed
2888 network_graph.remove_stale_channels_and_tracking_with_time(
2889 removal_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2890 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2891 assert!(network_graph.removed_nodes.lock().unwrap().is_empty());
2896 fn getting_next_channel_announcements() {
2897 let network_graph = create_network_graph();
2898 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2899 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2900 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2902 // Channels were not announced yet.
2903 let channels_with_announcements = gossip_sync.get_next_channel_announcement(0);
2904 assert!(channels_with_announcements.is_none());
2906 let short_channel_id;
2908 // Announce a channel we will update
2909 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2910 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2911 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2917 // Contains initial channel announcement now.
2918 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2919 if let Some(channel_announcements) = channels_with_announcements {
2920 let (_, ref update_1, ref update_2) = channel_announcements;
2921 assert_eq!(update_1, &None);
2922 assert_eq!(update_2, &None);
2928 // Valid channel update
2929 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2930 unsigned_channel_update.timestamp = 101;
2931 }, node_1_privkey, &secp_ctx);
2932 match gossip_sync.handle_channel_update(&valid_channel_update) {
2938 // Now contains an initial announcement and an update.
2939 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2940 if let Some(channel_announcements) = channels_with_announcements {
2941 let (_, ref update_1, ref update_2) = channel_announcements;
2942 assert_ne!(update_1, &None);
2943 assert_eq!(update_2, &None);
2949 // Channel update with excess data.
2950 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2951 unsigned_channel_update.timestamp = 102;
2952 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2953 }, node_1_privkey, &secp_ctx);
2954 match gossip_sync.handle_channel_update(&valid_channel_update) {
2960 // Test that announcements with excess data won't be returned
2961 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2962 if let Some(channel_announcements) = channels_with_announcements {
2963 let (_, ref update_1, ref update_2) = channel_announcements;
2964 assert_eq!(update_1, &None);
2965 assert_eq!(update_2, &None);
2970 // Further starting point have no channels after it
2971 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id + 1000);
2972 assert!(channels_with_announcements.is_none());
2976 fn getting_next_node_announcements() {
2977 let network_graph = create_network_graph();
2978 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2979 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2980 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2981 let node_id_1 = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2984 let next_announcements = gossip_sync.get_next_node_announcement(None);
2985 assert!(next_announcements.is_none());
2988 // Announce a channel to add 2 nodes
2989 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2990 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2996 // Nodes were never announced
2997 let next_announcements = gossip_sync.get_next_node_announcement(None);
2998 assert!(next_announcements.is_none());
3001 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3002 match gossip_sync.handle_node_announcement(&valid_announcement) {
3007 let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
3008 match gossip_sync.handle_node_announcement(&valid_announcement) {
3014 let next_announcements = gossip_sync.get_next_node_announcement(None);
3015 assert!(next_announcements.is_some());
3017 // Skip the first node.
3018 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3019 assert!(next_announcements.is_some());
3022 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
3023 let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
3024 unsigned_announcement.timestamp += 10;
3025 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
3026 }, node_2_privkey, &secp_ctx);
3027 match gossip_sync.handle_node_announcement(&valid_announcement) {
3028 Ok(res) => assert!(!res),
3033 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3034 assert!(next_announcements.is_none());
3038 fn network_graph_serialization() {
3039 let network_graph = create_network_graph();
3040 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3042 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3043 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3045 // Announce a channel to add a corresponding node.
3046 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3047 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3048 Ok(res) => assert!(res),
3052 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3053 match gossip_sync.handle_node_announcement(&valid_announcement) {
3058 let mut w = test_utils::TestVecWriter(Vec::new());
3059 assert!(!network_graph.read_only().nodes().is_empty());
3060 assert!(!network_graph.read_only().channels().is_empty());
3061 network_graph.write(&mut w).unwrap();
3063 let logger = Arc::new(test_utils::TestLogger::new());
3064 assert!(<NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), logger).unwrap() == network_graph);
3068 fn network_graph_tlv_serialization() {
3069 let network_graph = create_network_graph();
3070 network_graph.set_last_rapid_gossip_sync_timestamp(42);
3072 let mut w = test_utils::TestVecWriter(Vec::new());
3073 network_graph.write(&mut w).unwrap();
3075 let logger = Arc::new(test_utils::TestLogger::new());
3076 let reassembled_network_graph: NetworkGraph<_> = ReadableArgs::read(&mut io::Cursor::new(&w.0), logger).unwrap();
3077 assert!(reassembled_network_graph == network_graph);
3078 assert_eq!(reassembled_network_graph.get_last_rapid_gossip_sync_timestamp().unwrap(), 42);
3082 #[cfg(feature = "std")]
3083 fn calling_sync_routing_table() {
3084 use std::time::{SystemTime, UNIX_EPOCH};
3085 use crate::ln::msgs::Init;
3087 let network_graph = create_network_graph();
3088 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3089 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
3090 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
3092 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3094 // It should ignore if gossip_queries feature is not enabled
3096 let init_msg = Init { features: InitFeatures::empty(), networks: None, remote_network_address: None };
3097 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3098 let events = gossip_sync.get_and_clear_pending_msg_events();
3099 assert_eq!(events.len(), 0);
3102 // It should send a gossip_timestamp_filter with the correct information
3104 let mut features = InitFeatures::empty();
3105 features.set_gossip_queries_optional();
3106 let init_msg = Init { features, networks: None, remote_network_address: None };
3107 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3108 let events = gossip_sync.get_and_clear_pending_msg_events();
3109 assert_eq!(events.len(), 1);
3111 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
3112 assert_eq!(node_id, &node_id_1);
3113 assert_eq!(msg.chain_hash, chain_hash);
3114 let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
3115 assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
3116 assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
3117 assert_eq!(msg.timestamp_range, u32::max_value());
3119 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
3125 fn handling_query_channel_range() {
3126 let network_graph = create_network_graph();
3127 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3129 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3130 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3131 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3132 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
3134 let mut scids: Vec<u64> = vec![
3135 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
3136 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
3139 // used for testing multipart reply across blocks
3140 for block in 100000..=108001 {
3141 scids.push(scid_from_parts(block, 0, 0).unwrap());
3144 // used for testing resumption on same block
3145 scids.push(scid_from_parts(108001, 1, 0).unwrap());
3148 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
3149 unsigned_announcement.short_channel_id = scid;
3150 }, node_1_privkey, node_2_privkey, &secp_ctx);
3151 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3157 // Error when number_of_blocks=0
3158 do_handling_query_channel_range(
3162 chain_hash: chain_hash.clone(),
3164 number_of_blocks: 0,
3167 vec![ReplyChannelRange {
3168 chain_hash: chain_hash.clone(),
3170 number_of_blocks: 0,
3171 sync_complete: true,
3172 short_channel_ids: vec![]
3176 // Error when wrong chain
3177 do_handling_query_channel_range(
3181 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3183 number_of_blocks: 0xffff_ffff,
3186 vec![ReplyChannelRange {
3187 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3189 number_of_blocks: 0xffff_ffff,
3190 sync_complete: true,
3191 short_channel_ids: vec![],
3195 // Error when first_blocknum > 0xffffff
3196 do_handling_query_channel_range(
3200 chain_hash: chain_hash.clone(),
3201 first_blocknum: 0x01000000,
3202 number_of_blocks: 0xffff_ffff,
3205 vec![ReplyChannelRange {
3206 chain_hash: chain_hash.clone(),
3207 first_blocknum: 0x01000000,
3208 number_of_blocks: 0xffff_ffff,
3209 sync_complete: true,
3210 short_channel_ids: vec![]
3214 // Empty reply when max valid SCID block num
3215 do_handling_query_channel_range(
3219 chain_hash: chain_hash.clone(),
3220 first_blocknum: 0xffffff,
3221 number_of_blocks: 1,
3226 chain_hash: chain_hash.clone(),
3227 first_blocknum: 0xffffff,
3228 number_of_blocks: 1,
3229 sync_complete: true,
3230 short_channel_ids: vec![]
3235 // No results in valid query range
3236 do_handling_query_channel_range(
3240 chain_hash: chain_hash.clone(),
3241 first_blocknum: 1000,
3242 number_of_blocks: 1000,
3247 chain_hash: chain_hash.clone(),
3248 first_blocknum: 1000,
3249 number_of_blocks: 1000,
3250 sync_complete: true,
3251 short_channel_ids: vec![],
3256 // Overflow first_blocknum + number_of_blocks
3257 do_handling_query_channel_range(
3261 chain_hash: chain_hash.clone(),
3262 first_blocknum: 0xfe0000,
3263 number_of_blocks: 0xffffffff,
3268 chain_hash: chain_hash.clone(),
3269 first_blocknum: 0xfe0000,
3270 number_of_blocks: 0xffffffff - 0xfe0000,
3271 sync_complete: true,
3272 short_channel_ids: vec![
3273 0xfffffe_ffffff_ffff, // max
3279 // Single block exactly full
3280 do_handling_query_channel_range(
3284 chain_hash: chain_hash.clone(),
3285 first_blocknum: 100000,
3286 number_of_blocks: 8000,
3291 chain_hash: chain_hash.clone(),
3292 first_blocknum: 100000,
3293 number_of_blocks: 8000,
3294 sync_complete: true,
3295 short_channel_ids: (100000..=107999)
3296 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3302 // Multiple split on new block
3303 do_handling_query_channel_range(
3307 chain_hash: chain_hash.clone(),
3308 first_blocknum: 100000,
3309 number_of_blocks: 8001,
3314 chain_hash: chain_hash.clone(),
3315 first_blocknum: 100000,
3316 number_of_blocks: 7999,
3317 sync_complete: false,
3318 short_channel_ids: (100000..=107999)
3319 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3323 chain_hash: chain_hash.clone(),
3324 first_blocknum: 107999,
3325 number_of_blocks: 2,
3326 sync_complete: true,
3327 short_channel_ids: vec![
3328 scid_from_parts(108000, 0, 0).unwrap(),
3334 // Multiple split on same block
3335 do_handling_query_channel_range(
3339 chain_hash: chain_hash.clone(),
3340 first_blocknum: 100002,
3341 number_of_blocks: 8000,
3346 chain_hash: chain_hash.clone(),
3347 first_blocknum: 100002,
3348 number_of_blocks: 7999,
3349 sync_complete: false,
3350 short_channel_ids: (100002..=108001)
3351 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3355 chain_hash: chain_hash.clone(),
3356 first_blocknum: 108001,
3357 number_of_blocks: 1,
3358 sync_complete: true,
3359 short_channel_ids: vec![
3360 scid_from_parts(108001, 1, 0).unwrap(),
3367 fn do_handling_query_channel_range(
3368 gossip_sync: &P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
3369 test_node_id: &PublicKey,
3370 msg: QueryChannelRange,
3372 expected_replies: Vec<ReplyChannelRange>
3374 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
3375 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
3376 let query_end_blocknum = msg.end_blocknum();
3377 let result = gossip_sync.handle_query_channel_range(test_node_id, msg);
3380 assert!(result.is_ok());
3382 assert!(result.is_err());
3385 let events = gossip_sync.get_and_clear_pending_msg_events();
3386 assert_eq!(events.len(), expected_replies.len());
3388 for i in 0..events.len() {
3389 let expected_reply = &expected_replies[i];
3391 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
3392 assert_eq!(node_id, test_node_id);
3393 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
3394 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
3395 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
3396 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
3397 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
3399 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
3400 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
3401 assert!(msg.first_blocknum >= max_firstblocknum);
3402 max_firstblocknum = msg.first_blocknum;
3403 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
3405 // Check that the last block count is >= the query's end_blocknum
3406 if i == events.len() - 1 {
3407 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
3410 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
3416 fn handling_query_short_channel_ids() {
3417 let network_graph = create_network_graph();
3418 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3419 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3420 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
3422 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3424 let result = gossip_sync.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
3426 short_channel_ids: vec![0x0003e8_000000_0000],
3428 assert!(result.is_err());
3432 fn displays_node_alias() {
3433 let format_str_alias = |alias: &str| {
3434 let mut bytes = [0u8; 32];
3435 bytes[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
3436 format!("{}", NodeAlias(bytes))
3439 assert_eq!(format_str_alias("I\u{1F496}LDK! \u{26A1}"), "I\u{1F496}LDK! \u{26A1}");
3440 assert_eq!(format_str_alias("I\u{1F496}LDK!\0\u{26A1}"), "I\u{1F496}LDK!");
3441 assert_eq!(format_str_alias("I\u{1F496}LDK!\t\u{26A1}"), "I\u{1F496}LDK!\u{FFFD}\u{26A1}");
3443 let format_bytes_alias = |alias: &[u8]| {
3444 let mut bytes = [0u8; 32];
3445 bytes[..alias.len()].copy_from_slice(alias);
3446 format!("{}", NodeAlias(bytes))
3449 assert_eq!(format_bytes_alias(b"\xFFI <heart> LDK!"), "\u{FFFD}I <heart> LDK!");
3450 assert_eq!(format_bytes_alias(b"\xFFI <heart>\0LDK!"), "\u{FFFD}I <heart>");
3451 assert_eq!(format_bytes_alias(b"\xFFI <heart>\tLDK!"), "\u{FFFD}I <heart>\u{FFFD}LDK!");
3455 fn channel_info_is_readable() {
3456 let chanmon_cfgs = crate::ln::functional_test_utils::create_chanmon_cfgs(2);
3457 let node_cfgs = crate::ln::functional_test_utils::create_node_cfgs(2, &chanmon_cfgs);
3458 let node_chanmgrs = crate::ln::functional_test_utils::create_node_chanmgrs(2, &node_cfgs, &[None, None, None, None]);
3459 let nodes = crate::ln::functional_test_utils::create_network(2, &node_cfgs, &node_chanmgrs);
3460 let config = crate::ln::functional_test_utils::test_default_channel_config();
3462 // 1. Test encoding/decoding of ChannelUpdateInfo
3463 let chan_update_info = ChannelUpdateInfo {
3466 cltv_expiry_delta: 42,
3467 htlc_minimum_msat: 1234,
3468 htlc_maximum_msat: 5678,
3469 fees: RoutingFees { base_msat: 9, proportional_millionths: 10 },
3470 last_update_message: None,
3473 let mut encoded_chan_update_info: Vec<u8> = Vec::new();
3474 assert!(chan_update_info.write(&mut encoded_chan_update_info).is_ok());
3476 // First make sure we can read ChannelUpdateInfos we just wrote
3477 let read_chan_update_info: ChannelUpdateInfo = crate::util::ser::Readable::read(&mut encoded_chan_update_info.as_slice()).unwrap();
3478 assert_eq!(chan_update_info, read_chan_update_info);
3480 // Check the serialization hasn't changed.
3481 let legacy_chan_update_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c0100").unwrap();
3482 assert_eq!(encoded_chan_update_info, legacy_chan_update_info_with_some);
3484 // Check we fail if htlc_maximum_msat is not present in either the ChannelUpdateInfo itself
3485 // or the ChannelUpdate enclosed with `last_update_message`.
3486 let legacy_chan_update_info_with_some_and_fail_update: Vec<u8> = <Vec<u8>>::from_hex("b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f42400000271000000014").unwrap();
3487 let read_chan_update_info_res: Result<ChannelUpdateInfo, crate::ln::msgs::DecodeError> = crate::util::ser::Readable::read(&mut legacy_chan_update_info_with_some_and_fail_update.as_slice());
3488 assert!(read_chan_update_info_res.is_err());
3490 let legacy_chan_update_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100").unwrap();
3491 let read_chan_update_info_res: Result<ChannelUpdateInfo, crate::ln::msgs::DecodeError> = crate::util::ser::Readable::read(&mut legacy_chan_update_info_with_none.as_slice());
3492 assert!(read_chan_update_info_res.is_err());
3494 // 2. Test encoding/decoding of ChannelInfo
3495 // Check we can encode/decode ChannelInfo without ChannelUpdateInfo fields present.
3496 let chan_info_none_updates = ChannelInfo {
3497 features: channelmanager::provided_channel_features(&config),
3498 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3500 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3502 capacity_sats: None,
3503 announcement_message: None,
3504 announcement_received_time: 87654,
3507 let mut encoded_chan_info: Vec<u8> = Vec::new();
3508 assert!(chan_info_none_updates.write(&mut encoded_chan_info).is_ok());
3510 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3511 assert_eq!(chan_info_none_updates, read_chan_info);
3513 // Check we can encode/decode ChannelInfo with ChannelUpdateInfo fields present.
3514 let chan_info_some_updates = ChannelInfo {
3515 features: channelmanager::provided_channel_features(&config),
3516 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3517 one_to_two: Some(chan_update_info.clone()),
3518 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3519 two_to_one: Some(chan_update_info.clone()),
3520 capacity_sats: None,
3521 announcement_message: None,
3522 announcement_received_time: 87654,
3525 let mut encoded_chan_info: Vec<u8> = Vec::new();
3526 assert!(chan_info_some_updates.write(&mut encoded_chan_info).is_ok());
3528 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3529 assert_eq!(chan_info_some_updates, read_chan_info);
3531 // Check the serialization hasn't changed.
3532 let legacy_chan_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88043636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23083636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3533 assert_eq!(encoded_chan_info, legacy_chan_info_with_some);
3535 // Check we can decode legacy ChannelInfo, even if the `two_to_one` / `one_to_two` /
3536 // `last_update_message` fields fail to decode due to missing htlc_maximum_msat.
3537 let legacy_chan_info_with_some_and_fail_update = <Vec<u8>>::from_hex("fd01ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce8804b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f4240000027100000001406210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2308b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f424000002710000000140a01000c0100").unwrap();
3538 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_some_and_fail_update.as_slice()).unwrap();
3539 assert_eq!(read_chan_info.announcement_received_time, 87654);
3540 assert_eq!(read_chan_info.one_to_two, None);
3541 assert_eq!(read_chan_info.two_to_one, None);
3543 let legacy_chan_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("ba00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88042e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23082e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3544 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_none.as_slice()).unwrap();
3545 assert_eq!(read_chan_info.announcement_received_time, 87654);
3546 assert_eq!(read_chan_info.one_to_two, None);
3547 assert_eq!(read_chan_info.two_to_one, None);
3551 fn node_info_is_readable() {
3552 // 1. Check we can read a valid NodeAnnouncementInfo and fail on an invalid one
3553 let announcement_message = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000122013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010000701fffefdfc2607").unwrap();
3554 let announcement_message = NodeAnnouncement::read(&mut announcement_message.as_slice()).unwrap();
3555 let valid_node_ann_info = NodeAnnouncementInfo::Relayed(announcement_message);
3557 let mut encoded_valid_node_ann_info = Vec::new();
3558 assert!(valid_node_ann_info.write(&mut encoded_valid_node_ann_info).is_ok());
3559 let read_valid_node_ann_info = NodeAnnouncementInfo::read(&mut encoded_valid_node_ann_info.as_slice()).unwrap();
3560 assert_eq!(read_valid_node_ann_info, valid_node_ann_info);
3561 assert_eq!(read_valid_node_ann_info.addresses().len(), 1);
3563 let encoded_invalid_node_ann_info = <Vec<u8>>::from_hex("3f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d2").unwrap();
3564 let read_invalid_node_ann_info_res = NodeAnnouncementInfo::read(&mut encoded_invalid_node_ann_info.as_slice());
3565 assert!(read_invalid_node_ann_info_res.is_err());
3567 // 2. Check we can read a NodeInfo anyways, but set the NodeAnnouncementInfo to None if invalid
3568 let valid_node_info = NodeInfo {
3569 channels: Vec::new(),
3570 announcement_info: Some(valid_node_ann_info),
3573 let mut encoded_valid_node_info = Vec::new();
3574 assert!(valid_node_info.write(&mut encoded_valid_node_info).is_ok());
3575 let read_valid_node_info = NodeInfo::read(&mut encoded_valid_node_info.as_slice()).unwrap();
3576 assert_eq!(read_valid_node_info, valid_node_info);
3578 let encoded_invalid_node_info_hex = <Vec<u8>>::from_hex("4402403f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d20400").unwrap();
3579 let read_invalid_node_info = NodeInfo::read(&mut encoded_invalid_node_info_hex.as_slice()).unwrap();
3580 assert_eq!(read_invalid_node_info.announcement_info, None);
3584 fn test_node_info_keeps_compatibility() {
3585 let old_ann_info_with_addresses = <Vec<u8>>::from_hex("3f0009000708a000080a51220204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014104d2").unwrap();
3586 let ann_info_with_addresses = NodeAnnouncementInfo::read(&mut old_ann_info_with_addresses.as_slice())
3587 .expect("to be able to read an old NodeAnnouncementInfo with addresses");
3588 // This serialized info has no announcement_message but its address field should still be considered
3589 assert!(!ann_info_with_addresses.addresses().is_empty());
3593 fn test_node_id_display() {
3594 let node_id = NodeId([42; 33]);
3595 assert_eq!(format!("{}", &node_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
3599 fn is_tor_only_node() {
3600 let network_graph = create_network_graph();
3601 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3603 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3604 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3605 let node_1_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
3607 let announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3608 gossip_sync.handle_channel_announcement(&announcement).unwrap();
3610 let tcp_ip_v4 = SocketAddress::TcpIpV4 {
3611 addr: [255, 254, 253, 252],
3614 let tcp_ip_v6 = SocketAddress::TcpIpV6 {
3615 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
3618 let onion_v2 = SocketAddress::OnionV2([255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]);
3619 let onion_v3 = SocketAddress::OnionV3 {
3620 ed25519_pubkey: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224],
3625 let hostname = SocketAddress::Hostname {
3626 hostname: Hostname::try_from(String::from("host")).unwrap(),
3630 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3632 let announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3633 gossip_sync.handle_node_announcement(&announcement).unwrap();
3634 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3636 let announcement = get_signed_node_announcement(
3638 announcement.addresses = vec![
3639 tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone(),
3642 announcement.timestamp += 1000;
3644 node_1_privkey, &secp_ctx
3646 gossip_sync.handle_node_announcement(&announcement).unwrap();
3647 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3649 let announcement = get_signed_node_announcement(
3651 announcement.addresses = vec![
3652 tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3654 announcement.timestamp += 2000;
3656 node_1_privkey, &secp_ctx
3658 gossip_sync.handle_node_announcement(&announcement).unwrap();
3659 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3661 let announcement = get_signed_node_announcement(
3663 announcement.addresses = vec![
3664 tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3666 announcement.timestamp += 3000;
3668 node_1_privkey, &secp_ctx
3670 gossip_sync.handle_node_announcement(&announcement).unwrap();
3671 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3673 let announcement = get_signed_node_announcement(
3675 announcement.addresses = vec![onion_v2.clone(), onion_v3.clone()];
3676 announcement.timestamp += 4000;
3678 node_1_privkey, &secp_ctx
3680 gossip_sync.handle_node_announcement(&announcement).unwrap();
3681 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3683 let announcement = get_signed_node_announcement(
3685 announcement.addresses = vec![onion_v2.clone()];
3686 announcement.timestamp += 5000;
3688 node_1_privkey, &secp_ctx
3690 gossip_sync.handle_node_announcement(&announcement).unwrap();
3691 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3693 let announcement = get_signed_node_announcement(
3695 announcement.addresses = vec![tcp_ip_v4.clone()];
3696 announcement.timestamp += 6000;
3698 node_1_privkey, &secp_ctx
3700 gossip_sync.handle_node_announcement(&announcement).unwrap();
3701 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3709 use criterion::{black_box, Criterion};
3711 pub fn read_network_graph(bench: &mut Criterion) {
3712 let logger = crate::util::test_utils::TestLogger::new();
3713 let mut d = crate::routing::router::bench_utils::get_route_file().unwrap();
3714 let mut v = Vec::new();
3715 d.read_to_end(&mut v).unwrap();
3716 bench.bench_function("read_network_graph", |b| b.iter(||
3717 NetworkGraph::read(&mut std::io::Cursor::new(black_box(&v)), &logger).unwrap()
3721 pub fn write_network_graph(bench: &mut Criterion) {
3722 let logger = crate::util::test_utils::TestLogger::new();
3723 let mut d = crate::routing::router::bench_utils::get_route_file().unwrap();
3724 let net_graph = NetworkGraph::read(&mut d, &logger).unwrap();
3725 bench.bench_function("write_network_graph", |b| b.iter(||
3726 black_box(&net_graph).encode()