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::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 core::convert::TryFrom;
42 use crate::sync::{RwLock, RwLockReadGuard, LockTestExt};
43 #[cfg(feature = "std")]
44 use core::sync::atomic::{AtomicUsize, Ordering};
45 use crate::sync::Mutex;
46 use core::ops::{Bound, Deref};
47 use core::str::FromStr;
49 #[cfg(feature = "std")]
50 use std::time::{SystemTime, UNIX_EPOCH};
52 /// We remove stale channel directional info two weeks after the last update, per BOLT 7's
54 const STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14;
56 /// We stop tracking the removal of permanently failed nodes and channels one week after removal
57 const REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 7;
59 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
60 /// refuse to relay the message.
61 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
63 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
64 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
65 const MAX_SCIDS_PER_REPLY: usize = 8000;
67 /// Represents the compressed public key of a node
68 #[derive(Clone, Copy)]
69 pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
72 /// Create a new NodeId from a public key
73 pub fn from_pubkey(pubkey: &PublicKey) -> Self {
74 NodeId(pubkey.serialize())
77 /// Create a new NodeId from a slice of bytes
78 pub fn from_slice(bytes: &[u8]) -> Result<Self, DecodeError> {
79 if bytes.len() != PUBLIC_KEY_SIZE {
80 return Err(DecodeError::InvalidValue);
82 let mut data = [0; PUBLIC_KEY_SIZE];
83 data.copy_from_slice(bytes);
87 /// Get the public key slice from this NodeId
88 pub fn as_slice(&self) -> &[u8] {
92 /// Get the public key as an array from this NodeId
93 pub fn as_array(&self) -> &[u8; PUBLIC_KEY_SIZE] {
97 /// Get the public key from this NodeId
98 pub fn as_pubkey(&self) -> Result<PublicKey, secp256k1::Error> {
99 PublicKey::from_slice(&self.0)
103 impl fmt::Debug for NodeId {
104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105 write!(f, "NodeId({})", crate::util::logger::DebugBytes(&self.0))
108 impl fmt::Display for NodeId {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110 crate::util::logger::DebugBytes(&self.0).fmt(f)
114 impl core::hash::Hash for NodeId {
115 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
120 impl Eq for NodeId {}
122 impl PartialEq for NodeId {
123 fn eq(&self, other: &Self) -> bool {
124 self.0[..] == other.0[..]
128 impl cmp::PartialOrd for NodeId {
129 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
130 Some(self.cmp(other))
134 impl Ord for NodeId {
135 fn cmp(&self, other: &Self) -> cmp::Ordering {
136 self.0[..].cmp(&other.0[..])
140 impl Writeable for NodeId {
141 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
142 writer.write_all(&self.0)?;
147 impl Readable for NodeId {
148 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
149 let mut buf = [0; PUBLIC_KEY_SIZE];
150 reader.read_exact(&mut buf)?;
155 impl From<PublicKey> for NodeId {
156 fn from(pubkey: PublicKey) -> Self {
157 Self::from_pubkey(&pubkey)
161 impl TryFrom<NodeId> for PublicKey {
162 type Error = secp256k1::Error;
164 fn try_from(node_id: NodeId) -> Result<Self, Self::Error> {
169 impl FromStr for NodeId {
170 type Err = hex::parse::HexToArrayError;
172 fn from_str(s: &str) -> Result<Self, Self::Err> {
173 let data: [u8; PUBLIC_KEY_SIZE] = hex::FromHex::from_hex(s)?;
178 /// Represents the network as nodes and channels between them
179 pub struct NetworkGraph<L: Deref> where L::Target: Logger {
180 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
181 last_rapid_gossip_sync_timestamp: Mutex<Option<u32>>,
182 chain_hash: ChainHash,
184 // Lock order: channels -> nodes
185 channels: RwLock<IndexedMap<u64, ChannelInfo>>,
186 nodes: RwLock<IndexedMap<NodeId, NodeInfo>>,
187 // Lock order: removed_channels -> removed_nodes
189 // NOTE: In the following `removed_*` maps, we use seconds since UNIX epoch to track time instead
190 // of `std::time::Instant`s for a few reasons:
191 // * We want it to be possible to do tracking in no-std environments where we can compare
192 // a provided current UNIX timestamp with the time at which we started tracking.
193 // * In the future, if we decide to persist these maps, they will already be serializable.
194 // * Although we lose out on the platform's monotonic clock, the system clock in a std
195 // environment should be practical over the time period we are considering (on the order of a
198 /// Keeps track of short channel IDs for channels we have explicitly removed due to permanent
199 /// failure so that we don't resync them from gossip. Each SCID is mapped to the time (in seconds)
200 /// it was removed so that once some time passes, we can potentially resync it from gossip again.
201 removed_channels: Mutex<HashMap<u64, Option<u64>>>,
202 /// Keeps track of `NodeId`s we have explicitly removed due to permanent failure so that we don't
203 /// resync them from gossip. Each `NodeId` is mapped to the time (in seconds) it was removed so
204 /// that once some time passes, we can potentially resync it from gossip again.
205 removed_nodes: Mutex<HashMap<NodeId, Option<u64>>>,
206 /// Announcement messages which are awaiting an on-chain lookup to be processed.
207 pub(super) pending_checks: utxo::PendingChecks,
210 /// A read-only view of [`NetworkGraph`].
211 pub struct ReadOnlyNetworkGraph<'a> {
212 channels: RwLockReadGuard<'a, IndexedMap<u64, ChannelInfo>>,
213 nodes: RwLockReadGuard<'a, IndexedMap<NodeId, NodeInfo>>,
216 /// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
217 /// return packet by a node along the route. See [BOLT #4] for details.
219 /// [BOLT #4]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md
220 #[derive(Clone, Debug, PartialEq, Eq)]
221 pub enum NetworkUpdate {
222 /// An error indicating a `channel_update` messages should be applied via
223 /// [`NetworkGraph::update_channel`].
224 ChannelUpdateMessage {
225 /// The update to apply via [`NetworkGraph::update_channel`].
228 /// An error indicating that a channel failed to route a payment, which should be applied via
229 /// [`NetworkGraph::channel_failed_permanent`] if permanent.
231 /// The short channel id of the closed channel.
232 short_channel_id: u64,
233 /// Whether the channel should be permanently removed or temporarily disabled until a new
234 /// `channel_update` message is received.
237 /// An error indicating that a node failed to route a payment, which should be applied via
238 /// [`NetworkGraph::node_failed_permanent`] if permanent.
240 /// The node id of the failed node.
242 /// Whether the node should be permanently removed from consideration or can be restored
243 /// when a new `channel_update` message is received.
248 impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
249 (0, ChannelUpdateMessage) => {
252 (2, ChannelFailure) => {
253 (0, short_channel_id, required),
254 (2, is_permanent, required),
256 (4, NodeFailure) => {
257 (0, node_id, required),
258 (2, is_permanent, required),
262 /// Receives and validates network updates from peers,
263 /// stores authentic and relevant data as a network graph.
264 /// This network graph is then used for routing payments.
265 /// Provides interface to help with initial routing sync by
266 /// serving historical announcements.
267 pub struct P2PGossipSync<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref>
268 where U::Target: UtxoLookup, L::Target: Logger
271 utxo_lookup: RwLock<Option<U>>,
272 #[cfg(feature = "std")]
273 full_syncs_requested: AtomicUsize,
274 pending_events: Mutex<Vec<MessageSendEvent>>,
278 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> P2PGossipSync<G, U, L>
279 where U::Target: UtxoLookup, L::Target: Logger
281 /// Creates a new tracker of the actual state of the network of channels and nodes,
282 /// assuming an existing [`NetworkGraph`].
283 /// UTXO lookup is used to make sure announced channels exist on-chain, channel data is
284 /// correct, and the announcement is signed with channel owners' keys.
285 pub fn new(network_graph: G, utxo_lookup: Option<U>, logger: L) -> Self {
288 #[cfg(feature = "std")]
289 full_syncs_requested: AtomicUsize::new(0),
290 utxo_lookup: RwLock::new(utxo_lookup),
291 pending_events: Mutex::new(vec![]),
296 /// Adds a provider used to check new announcements. Does not affect
297 /// existing announcements unless they are updated.
298 /// Add, update or remove the provider would replace the current one.
299 pub fn add_utxo_lookup(&self, utxo_lookup: Option<U>) {
300 *self.utxo_lookup.write().unwrap() = utxo_lookup;
303 /// Gets a reference to the underlying [`NetworkGraph`] which was provided in
304 /// [`P2PGossipSync::new`].
306 /// This is not exported to bindings users as bindings don't support a reference-to-a-reference yet
307 pub fn network_graph(&self) -> &G {
311 #[cfg(feature = "std")]
312 /// Returns true when a full routing table sync should be performed with a peer.
313 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
314 //TODO: Determine whether to request a full sync based on the network map.
315 const FULL_SYNCS_TO_REQUEST: usize = 5;
316 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
317 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
324 /// Used to broadcast forward gossip messages which were validated async.
326 /// Note that this will ignore events other than `Broadcast*` or messages with too much excess
328 pub(super) fn forward_gossip_msg(&self, mut ev: MessageSendEvent) {
330 MessageSendEvent::BroadcastChannelAnnouncement { msg, ref mut update_msg } => {
331 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
332 if update_msg.as_ref()
333 .map(|msg| msg.contents.excess_data.len()).unwrap_or(0) > MAX_EXCESS_BYTES_FOR_RELAY
338 MessageSendEvent::BroadcastChannelUpdate { msg } => {
339 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
341 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
342 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY ||
343 msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY ||
344 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY
351 self.pending_events.lock().unwrap().push(ev);
355 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
356 /// Handles any network updates originating from [`Event`]s.
358 /// Note that this will skip applying any [`NetworkUpdate::ChannelUpdateMessage`] to avoid
359 /// leaking possibly identifying information of the sender to the public network.
361 /// [`Event`]: crate::events::Event
362 pub fn handle_network_update(&self, network_update: &NetworkUpdate) {
363 match *network_update {
364 NetworkUpdate::ChannelUpdateMessage { ref msg } => {
365 let short_channel_id = msg.contents.short_channel_id;
366 let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
367 let status = if is_enabled { "enabled" } else { "disabled" };
368 log_debug!(self.logger, "Skipping application of a channel update from a payment failure. Channel {} is {}.", short_channel_id, status);
370 NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } => {
372 log_debug!(self.logger, "Removing channel graph entry for {} due to a payment failure.", short_channel_id);
373 self.channel_failed_permanent(short_channel_id);
376 NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
378 log_debug!(self.logger,
379 "Removed node graph entry for {} due to a payment failure.", log_pubkey!(node_id));
380 self.node_failed_permanent(node_id);
386 /// Gets the chain hash for this network graph.
387 pub fn get_chain_hash(&self) -> ChainHash {
392 macro_rules! secp_verify_sig {
393 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr, $msg_type: expr ) => {
394 match $secp_ctx.verify_ecdsa($msg, $sig, $pubkey) {
397 return Err(LightningError {
398 err: format!("Invalid signature on {} message", $msg_type),
399 action: ErrorAction::SendWarningMessage {
400 msg: msgs::WarningMessage {
401 channel_id: ChannelId::new_zero(),
402 data: format!("Invalid signature on {} message", $msg_type),
404 log_level: Level::Trace,
412 macro_rules! get_pubkey_from_node_id {
413 ( $node_id: expr, $msg_type: expr ) => {
414 PublicKey::from_slice($node_id.as_slice())
415 .map_err(|_| LightningError {
416 err: format!("Invalid public key on {} message", $msg_type),
417 action: ErrorAction::SendWarningMessage {
418 msg: msgs::WarningMessage {
419 channel_id: ChannelId::new_zero(),
420 data: format!("Invalid public key on {} message", $msg_type),
422 log_level: Level::Trace
428 fn message_sha256d_hash<M: Writeable>(msg: &M) -> Sha256dHash {
429 let mut engine = Sha256dHash::engine();
430 msg.write(&mut engine).expect("In-memory structs should not fail to serialize");
431 Sha256dHash::from_engine(engine)
434 /// Verifies the signature of a [`NodeAnnouncement`].
436 /// Returns an error if it is invalid.
437 pub fn verify_node_announcement<C: Verification>(msg: &NodeAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
438 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg.contents)[..]);
439 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &get_pubkey_from_node_id!(msg.contents.node_id, "node_announcement"), "node_announcement");
444 /// Verifies all signatures included in a [`ChannelAnnouncement`].
446 /// Returns an error if one of the signatures is invalid.
447 pub fn verify_channel_announcement<C: Verification>(msg: &ChannelAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
448 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg.contents)[..]);
449 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");
450 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");
451 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");
452 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");
457 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> RoutingMessageHandler for P2PGossipSync<G, U, L>
458 where U::Target: UtxoLookup, L::Target: Logger
460 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
461 self.network_graph.update_node_from_announcement(msg)?;
462 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
463 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
464 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
467 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
468 self.network_graph.update_channel_from_announcement(msg, &*self.utxo_lookup.read().unwrap())?;
469 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
472 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
473 self.network_graph.update_channel(msg)?;
474 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
477 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
478 let mut channels = self.network_graph.channels.write().unwrap();
479 for (_, ref chan) in channels.range(starting_point..) {
480 if chan.announcement_message.is_some() {
481 let chan_announcement = chan.announcement_message.clone().unwrap();
482 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
483 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
484 if let Some(one_to_two) = chan.one_to_two.as_ref() {
485 one_to_two_announcement = one_to_two.last_update_message.clone();
487 if let Some(two_to_one) = chan.two_to_one.as_ref() {
488 two_to_one_announcement = two_to_one.last_update_message.clone();
490 return Some((chan_announcement, one_to_two_announcement, two_to_one_announcement));
492 // TODO: We may end up sending un-announced channel_updates if we are sending
493 // initial sync data while receiving announce/updates for this channel.
499 fn get_next_node_announcement(&self, starting_point: Option<&NodeId>) -> Option<NodeAnnouncement> {
500 let mut nodes = self.network_graph.nodes.write().unwrap();
501 let iter = if let Some(node_id) = starting_point {
502 nodes.range((Bound::Excluded(node_id), Bound::Unbounded))
506 for (_, ref node) in iter {
507 if let Some(node_info) = node.announcement_info.as_ref() {
508 if let Some(msg) = node_info.announcement_message.clone() {
516 /// Initiates a stateless sync of routing gossip information with a peer
517 /// using [`gossip_queries`]. The default strategy used by this implementation
518 /// is to sync the full block range with several peers.
520 /// We should expect one or more [`reply_channel_range`] messages in response
521 /// to our [`query_channel_range`]. Each reply will enqueue a [`query_scid`] message
522 /// to request gossip messages for each channel. The sync is considered complete
523 /// when the final [`reply_scids_end`] message is received, though we are not
524 /// tracking this directly.
526 /// [`gossip_queries`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#query-messages
527 /// [`reply_channel_range`]: msgs::ReplyChannelRange
528 /// [`query_channel_range`]: msgs::QueryChannelRange
529 /// [`query_scid`]: msgs::QueryShortChannelIds
530 /// [`reply_scids_end`]: msgs::ReplyShortChannelIdsEnd
531 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &Init, _inbound: bool) -> Result<(), ()> {
532 // We will only perform a sync with peers that support gossip_queries.
533 if !init_msg.features.supports_gossip_queries() {
534 // Don't disconnect peers for not supporting gossip queries. We may wish to have
535 // channels with peers even without being able to exchange gossip.
539 // The lightning network's gossip sync system is completely broken in numerous ways.
541 // Given no broadly-available set-reconciliation protocol, the only reasonable approach is
542 // to do a full sync from the first few peers we connect to, and then receive gossip
543 // updates from all our peers normally.
545 // Originally, we could simply tell a peer to dump us the entire gossip table on startup,
546 // wasting lots of bandwidth but ensuring we have the full network graph. After the initial
547 // dump peers would always send gossip and we'd stay up-to-date with whatever our peer has
550 // In order to reduce the bandwidth waste, "gossip queries" were introduced, allowing you
551 // to ask for the SCIDs of all channels in your peer's routing graph, and then only request
552 // channel data which you are missing. Except there was no way at all to identify which
553 // `channel_update`s you were missing, so you still had to request everything, just in a
554 // very complicated way with some queries instead of just getting the dump.
556 // Later, an option was added to fetch the latest timestamps of the `channel_update`s to
557 // make efficient sync possible, however it has yet to be implemented in lnd, which makes
558 // relying on it useless.
560 // After gossip queries were introduced, support for receiving a full gossip table dump on
561 // connection was removed from several nodes, making it impossible to get a full sync
562 // without using the "gossip queries" messages.
564 // Once you opt into "gossip queries" the only way to receive any gossip updates that a
565 // peer receives after you connect, you must send a `gossip_timestamp_filter` message. This
566 // message, as the name implies, tells the peer to not forward any gossip messages with a
567 // timestamp older than a given value (not the time the peer received the filter, but the
568 // timestamp in the update message, which is often hours behind when the peer received the
571 // Obnoxiously, `gossip_timestamp_filter` isn't *just* a filter, but its also a request for
572 // your peer to send you the full routing graph (subject to the filter). Thus, in order to
573 // tell a peer to send you any updates as it sees them, you have to also ask for the full
574 // routing graph to be synced. If you set a timestamp filter near the current time, peers
575 // will simply not forward any new updates they see to you which were generated some time
576 // ago (which is not uncommon). If you instead set a timestamp filter near 0 (or two weeks
577 // ago), you will always get the full routing graph from all your peers.
579 // Most lightning nodes today opt to simply turn off receiving gossip data which only
580 // propagated some time after it was generated, and, worse, often disable gossiping with
581 // several peers after their first connection. The second behavior can cause gossip to not
582 // propagate fully if there are cuts in the gossiping subgraph.
584 // In an attempt to cut a middle ground between always fetching the full graph from all of
585 // our peers and never receiving gossip from peers at all, we send all of our peers a
586 // `gossip_timestamp_filter`, with the filter time set either two weeks ago or an hour ago.
588 // For no-std builds, we bury our head in the sand and do a full sync on each connection.
589 #[allow(unused_mut, unused_assignments)]
590 let mut gossip_start_time = 0;
591 #[cfg(feature = "std")]
593 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
594 if self.should_request_full_sync(&their_node_id) {
595 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
597 gossip_start_time -= 60 * 60; // an hour ago
601 let mut pending_events = self.pending_events.lock().unwrap();
602 pending_events.push(MessageSendEvent::SendGossipTimestampFilter {
603 node_id: their_node_id.clone(),
604 msg: GossipTimestampFilter {
605 chain_hash: self.network_graph.chain_hash,
606 first_timestamp: gossip_start_time as u32, // 2106 issue!
607 timestamp_range: u32::max_value(),
613 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: ReplyChannelRange) -> Result<(), LightningError> {
614 // We don't make queries, so should never receive replies. If, in the future, the set
615 // reconciliation extensions to gossip queries become broadly supported, we should revert
616 // this code to its state pre-0.0.106.
620 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
621 // We don't make queries, so should never receive replies. If, in the future, the set
622 // reconciliation extensions to gossip queries become broadly supported, we should revert
623 // this code to its state pre-0.0.106.
627 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
628 /// are in the specified block range. Due to message size limits, large range
629 /// queries may result in several reply messages. This implementation enqueues
630 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
631 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
632 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
633 /// memory constrained systems.
634 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
635 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);
637 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
639 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
640 // If so, we manually cap the ending block to avoid this overflow.
641 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
643 // Per spec, we must reply to a query. Send an empty message when things are invalid.
644 if msg.chain_hash != self.network_graph.chain_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
645 let mut pending_events = self.pending_events.lock().unwrap();
646 pending_events.push(MessageSendEvent::SendReplyChannelRange {
647 node_id: their_node_id.clone(),
648 msg: ReplyChannelRange {
649 chain_hash: msg.chain_hash.clone(),
650 first_blocknum: msg.first_blocknum,
651 number_of_blocks: msg.number_of_blocks,
653 short_channel_ids: vec![],
656 return Err(LightningError {
657 err: String::from("query_channel_range could not be processed"),
658 action: ErrorAction::IgnoreError,
662 // Creates channel batches. We are not checking if the channel is routable
663 // (has at least one update). A peer may still want to know the channel
664 // exists even if its not yet routable.
665 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
666 let mut channels = self.network_graph.channels.write().unwrap();
667 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
668 if let Some(chan_announcement) = &chan.announcement_message {
669 // Construct a new batch if last one is full
670 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
671 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
674 let batch = batches.last_mut().unwrap();
675 batch.push(chan_announcement.contents.short_channel_id);
680 let mut pending_events = self.pending_events.lock().unwrap();
681 let batch_count = batches.len();
682 let mut prev_batch_endblock = msg.first_blocknum;
683 for (batch_index, batch) in batches.into_iter().enumerate() {
684 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
685 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
687 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
688 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
689 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
690 // significant diversion from the requirements set by the spec, and, in case of blocks
691 // with no channel opens (e.g. empty blocks), requires that we use the previous value
692 // and *not* derive the first_blocknum from the actual first block of the reply.
693 let first_blocknum = prev_batch_endblock;
695 // Each message carries the number of blocks (from the `first_blocknum`) its contents
696 // fit in. Though there is no requirement that we use exactly the number of blocks its
697 // contents are from, except for the bogus requirements c-lightning enforces, above.
699 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
700 // >= the query's end block. Thus, for the last reply, we calculate the difference
701 // between the query's end block and the start of the reply.
703 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
704 // first_blocknum will be either msg.first_blocknum or a higher block height.
705 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
706 (true, msg.end_blocknum() - first_blocknum)
708 // Prior replies should use the number of blocks that fit into the reply. Overflow
709 // safe since first_blocknum is always <= last SCID's block.
711 (false, block_from_scid(*batch.last().unwrap()) - first_blocknum)
714 prev_batch_endblock = first_blocknum + number_of_blocks;
716 pending_events.push(MessageSendEvent::SendReplyChannelRange {
717 node_id: their_node_id.clone(),
718 msg: ReplyChannelRange {
719 chain_hash: msg.chain_hash.clone(),
723 short_channel_ids: batch,
731 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
734 err: String::from("Not implemented"),
735 action: ErrorAction::IgnoreError,
739 fn provided_node_features(&self) -> NodeFeatures {
740 let mut features = NodeFeatures::empty();
741 features.set_gossip_queries_optional();
745 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
746 let mut features = InitFeatures::empty();
747 features.set_gossip_queries_optional();
751 fn processing_queue_high(&self) -> bool {
752 self.network_graph.pending_checks.too_many_checks_pending()
756 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> MessageSendEventsProvider for P2PGossipSync<G, U, L>
758 U::Target: UtxoLookup,
761 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
762 let mut ret = Vec::new();
763 let mut pending_events = self.pending_events.lock().unwrap();
764 core::mem::swap(&mut ret, &mut pending_events);
769 #[derive(Clone, Debug, PartialEq, Eq)]
770 /// Details about one direction of a channel as received within a [`ChannelUpdate`].
771 pub struct ChannelUpdateInfo {
772 /// When the last update to the channel direction was issued.
773 /// Value is opaque, as set in the announcement.
774 pub last_update: u32,
775 /// Whether the channel can be currently used for payments (in this one direction).
777 /// The difference in CLTV values that you must have when routing through this channel.
778 pub cltv_expiry_delta: u16,
779 /// The minimum value, which must be relayed to the next hop via the channel
780 pub htlc_minimum_msat: u64,
781 /// The maximum value which may be relayed to the next hop via the channel.
782 pub htlc_maximum_msat: u64,
783 /// Fees charged when the channel is used for routing
784 pub fees: RoutingFees,
785 /// Most recent update for the channel received from the network
786 /// Mostly redundant with the data we store in fields explicitly.
787 /// Everything else is useful only for sending out for initial routing sync.
788 /// Not stored if contains excess data to prevent DoS.
789 pub last_update_message: Option<ChannelUpdate>,
792 impl fmt::Display for ChannelUpdateInfo {
793 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
794 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)?;
799 impl Writeable for ChannelUpdateInfo {
800 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
801 write_tlv_fields!(writer, {
802 (0, self.last_update, required),
803 (2, self.enabled, required),
804 (4, self.cltv_expiry_delta, required),
805 (6, self.htlc_minimum_msat, required),
806 // Writing htlc_maximum_msat as an Option<u64> is required to maintain backwards
807 // compatibility with LDK versions prior to v0.0.110.
808 (8, Some(self.htlc_maximum_msat), required),
809 (10, self.fees, required),
810 (12, self.last_update_message, required),
816 impl Readable for ChannelUpdateInfo {
817 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
818 _init_tlv_field_var!(last_update, required);
819 _init_tlv_field_var!(enabled, required);
820 _init_tlv_field_var!(cltv_expiry_delta, required);
821 _init_tlv_field_var!(htlc_minimum_msat, required);
822 _init_tlv_field_var!(htlc_maximum_msat, option);
823 _init_tlv_field_var!(fees, required);
824 _init_tlv_field_var!(last_update_message, required);
826 read_tlv_fields!(reader, {
827 (0, last_update, required),
828 (2, enabled, required),
829 (4, cltv_expiry_delta, required),
830 (6, htlc_minimum_msat, required),
831 (8, htlc_maximum_msat, required),
832 (10, fees, required),
833 (12, last_update_message, required)
836 if let Some(htlc_maximum_msat) = htlc_maximum_msat {
837 Ok(ChannelUpdateInfo {
838 last_update: _init_tlv_based_struct_field!(last_update, required),
839 enabled: _init_tlv_based_struct_field!(enabled, required),
840 cltv_expiry_delta: _init_tlv_based_struct_field!(cltv_expiry_delta, required),
841 htlc_minimum_msat: _init_tlv_based_struct_field!(htlc_minimum_msat, required),
843 fees: _init_tlv_based_struct_field!(fees, required),
844 last_update_message: _init_tlv_based_struct_field!(last_update_message, required),
847 Err(DecodeError::InvalidValue)
852 #[derive(Clone, Debug, PartialEq, Eq)]
853 /// Details about a channel (both directions).
854 /// Received within a channel announcement.
855 pub struct ChannelInfo {
856 /// Protocol features of a channel communicated during its announcement
857 pub features: ChannelFeatures,
858 /// Source node of the first direction of a channel
859 pub node_one: NodeId,
860 /// Details about the first direction of a channel
861 pub one_to_two: Option<ChannelUpdateInfo>,
862 /// Source node of the second direction of a channel
863 pub node_two: NodeId,
864 /// Details about the second direction of a channel
865 pub two_to_one: Option<ChannelUpdateInfo>,
866 /// The channel capacity as seen on-chain, if chain lookup is available.
867 pub capacity_sats: Option<u64>,
868 /// An initial announcement of the channel
869 /// Mostly redundant with the data we store in fields explicitly.
870 /// Everything else is useful only for sending out for initial routing sync.
871 /// Not stored if contains excess data to prevent DoS.
872 pub announcement_message: Option<ChannelAnnouncement>,
873 /// The timestamp when we received the announcement, if we are running with feature = "std"
874 /// (which we can probably assume we are - no-std environments probably won't have a full
875 /// network graph in memory!).
876 announcement_received_time: u64,
880 /// Returns a [`DirectedChannelInfo`] for the channel directed to the given `target` from a
881 /// returned `source`, or `None` if `target` is not one of the channel's counterparties.
882 pub fn as_directed_to(&self, target: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
883 let (direction, source, outbound) = {
884 if target == &self.node_one {
885 (self.two_to_one.as_ref(), &self.node_two, false)
886 } else if target == &self.node_two {
887 (self.one_to_two.as_ref(), &self.node_one, true)
892 direction.map(|dir| (DirectedChannelInfo::new(self, dir, outbound), source))
895 /// Returns a [`DirectedChannelInfo`] for the channel directed from the given `source` to a
896 /// returned `target`, or `None` if `source` is not one of the channel's counterparties.
897 pub fn as_directed_from(&self, source: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
898 let (direction, target, outbound) = {
899 if source == &self.node_one {
900 (self.one_to_two.as_ref(), &self.node_two, true)
901 } else if source == &self.node_two {
902 (self.two_to_one.as_ref(), &self.node_one, false)
907 direction.map(|dir| (DirectedChannelInfo::new(self, dir, outbound), target))
910 /// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag.
911 pub fn get_directional_info(&self, channel_flags: u8) -> Option<&ChannelUpdateInfo> {
912 let direction = channel_flags & 1u8;
914 self.one_to_two.as_ref()
916 self.two_to_one.as_ref()
921 impl fmt::Display for ChannelInfo {
922 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
923 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
924 log_bytes!(self.features.encode()), &self.node_one, self.one_to_two, &self.node_two, self.two_to_one)?;
929 impl Writeable for ChannelInfo {
930 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
931 write_tlv_fields!(writer, {
932 (0, self.features, required),
933 (1, self.announcement_received_time, (default_value, 0)),
934 (2, self.node_one, required),
935 (4, self.one_to_two, required),
936 (6, self.node_two, required),
937 (8, self.two_to_one, required),
938 (10, self.capacity_sats, required),
939 (12, self.announcement_message, required),
945 // A wrapper allowing for the optional deseralization of ChannelUpdateInfo. Utilizing this is
946 // necessary to maintain backwards compatibility with previous serializations of `ChannelUpdateInfo`
947 // that may have no `htlc_maximum_msat` field set. In case the field is absent, we simply ignore
948 // the error and continue reading the `ChannelInfo`. Hopefully, we'll then eventually receive newer
949 // channel updates via the gossip network.
950 struct ChannelUpdateInfoDeserWrapper(Option<ChannelUpdateInfo>);
952 impl MaybeReadable for ChannelUpdateInfoDeserWrapper {
953 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
954 match crate::util::ser::Readable::read(reader) {
955 Ok(channel_update_option) => Ok(Some(Self(channel_update_option))),
956 Err(DecodeError::ShortRead) => Ok(None),
957 Err(DecodeError::InvalidValue) => Ok(None),
958 Err(err) => Err(err),
963 impl Readable for ChannelInfo {
964 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
965 _init_tlv_field_var!(features, required);
966 _init_tlv_field_var!(announcement_received_time, (default_value, 0));
967 _init_tlv_field_var!(node_one, required);
968 let mut one_to_two_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
969 _init_tlv_field_var!(node_two, required);
970 let mut two_to_one_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
971 _init_tlv_field_var!(capacity_sats, required);
972 _init_tlv_field_var!(announcement_message, required);
973 read_tlv_fields!(reader, {
974 (0, features, required),
975 (1, announcement_received_time, (default_value, 0)),
976 (2, node_one, required),
977 (4, one_to_two_wrap, upgradable_option),
978 (6, node_two, required),
979 (8, two_to_one_wrap, upgradable_option),
980 (10, capacity_sats, required),
981 (12, announcement_message, required),
985 features: _init_tlv_based_struct_field!(features, required),
986 node_one: _init_tlv_based_struct_field!(node_one, required),
987 one_to_two: one_to_two_wrap.map(|w| w.0).unwrap_or(None),
988 node_two: _init_tlv_based_struct_field!(node_two, required),
989 two_to_one: two_to_one_wrap.map(|w| w.0).unwrap_or(None),
990 capacity_sats: _init_tlv_based_struct_field!(capacity_sats, required),
991 announcement_message: _init_tlv_based_struct_field!(announcement_message, required),
992 announcement_received_time: _init_tlv_based_struct_field!(announcement_received_time, (default_value, 0)),
997 /// A wrapper around [`ChannelInfo`] representing information about the channel as directed from a
998 /// source node to a target node.
1000 pub struct DirectedChannelInfo<'a> {
1001 channel: &'a ChannelInfo,
1002 direction: &'a ChannelUpdateInfo,
1003 /// The direction this channel is in - if set, it indicates that we're traversing the channel
1004 /// from [`ChannelInfo::node_one`] to [`ChannelInfo::node_two`].
1005 from_node_one: bool,
1008 impl<'a> DirectedChannelInfo<'a> {
1010 fn new(channel: &'a ChannelInfo, direction: &'a ChannelUpdateInfo, from_node_one: bool) -> Self {
1011 Self { channel, direction, from_node_one }
1014 /// Returns information for the channel.
1016 pub fn channel(&self) -> &'a ChannelInfo { self.channel }
1018 /// Returns the [`EffectiveCapacity`] of the channel in the direction.
1020 /// This is either the total capacity from the funding transaction, if known, or the
1021 /// `htlc_maximum_msat` for the direction as advertised by the gossip network, if known,
1024 pub fn effective_capacity(&self) -> EffectiveCapacity {
1025 let mut htlc_maximum_msat = self.direction().htlc_maximum_msat;
1026 let capacity_msat = self.channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000);
1028 match capacity_msat {
1029 Some(capacity_msat) => {
1030 htlc_maximum_msat = cmp::min(htlc_maximum_msat, capacity_msat);
1031 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat }
1033 None => EffectiveCapacity::AdvertisedMaxHTLC { amount_msat: htlc_maximum_msat },
1037 /// Returns information for the direction.
1039 pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.direction }
1041 /// Returns the `node_id` of the source hop.
1043 /// Refers to the `node_id` forwarding the payment to the next hop.
1045 pub fn source(&self) -> &'a NodeId { if self.from_node_one { &self.channel.node_one } else { &self.channel.node_two } }
1047 /// Returns the `node_id` of the target hop.
1049 /// Refers to the `node_id` receiving the payment from the previous hop.
1051 pub fn target(&self) -> &'a NodeId { if self.from_node_one { &self.channel.node_two } else { &self.channel.node_one } }
1054 impl<'a> fmt::Debug for DirectedChannelInfo<'a> {
1055 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1056 f.debug_struct("DirectedChannelInfo")
1057 .field("channel", &self.channel)
1062 /// The effective capacity of a channel for routing purposes.
1064 /// While this may be smaller than the actual channel capacity, amounts greater than
1065 /// [`Self::as_msat`] should not be routed through the channel.
1066 #[derive(Clone, Copy, Debug, PartialEq)]
1067 pub enum EffectiveCapacity {
1068 /// The available liquidity in the channel known from being a channel counterparty, and thus a
1071 /// Either the inbound or outbound liquidity depending on the direction, denominated in
1073 liquidity_msat: u64,
1075 /// The maximum HTLC amount in one direction as advertised on the gossip network.
1077 /// The maximum HTLC amount denominated in millisatoshi.
1080 /// The total capacity of the channel as determined by the funding transaction.
1082 /// The funding amount denominated in millisatoshi.
1084 /// The maximum HTLC amount denominated in millisatoshi.
1085 htlc_maximum_msat: u64
1087 /// A capacity sufficient to route any payment, typically used for private channels provided by
1090 /// The maximum HTLC amount as provided by an invoice route hint.
1092 /// The maximum HTLC amount denominated in millisatoshi.
1095 /// A capacity that is unknown possibly because either the chain state is unavailable to know
1096 /// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
1100 /// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
1101 /// use when making routing decisions.
1102 pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
1104 impl EffectiveCapacity {
1105 /// Returns the effective capacity denominated in millisatoshi.
1106 pub fn as_msat(&self) -> u64 {
1108 EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
1109 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } => *amount_msat,
1110 EffectiveCapacity::Total { capacity_msat, .. } => *capacity_msat,
1111 EffectiveCapacity::HintMaxHTLC { amount_msat } => *amount_msat,
1112 EffectiveCapacity::Infinite => u64::max_value(),
1113 EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
1118 /// Fees for routing via a given channel or a node
1119 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash, Ord, PartialOrd)]
1120 pub struct RoutingFees {
1121 /// Flat routing fee in millisatoshis.
1123 /// Liquidity-based routing fee in millionths of a routed amount.
1124 /// In other words, 10000 is 1%.
1125 pub proportional_millionths: u32,
1128 impl_writeable_tlv_based!(RoutingFees, {
1129 (0, base_msat, required),
1130 (2, proportional_millionths, required)
1133 #[derive(Clone, Debug, PartialEq, Eq)]
1134 /// Information received in the latest node_announcement from this node.
1135 pub struct NodeAnnouncementInfo {
1136 /// Protocol features the node announced support for
1137 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,
1141 /// Color assigned to the node
1143 /// Moniker assigned to the node.
1144 /// May be invalid or malicious (eg control chars),
1145 /// should not be exposed to the user.
1146 pub alias: NodeAlias,
1147 /// An initial announcement of the node
1148 /// Mostly redundant with the data we store in fields explicitly.
1149 /// Everything else is useful only for sending out for initial routing sync.
1150 /// Not stored if contains excess data to prevent DoS.
1151 pub announcement_message: Option<NodeAnnouncement>
1154 impl NodeAnnouncementInfo {
1155 /// Internet-level addresses via which one can connect to the node
1156 pub fn addresses(&self) -> &[SocketAddress] {
1157 self.announcement_message.as_ref()
1158 .map(|msg| msg.contents.addresses.as_slice())
1159 .unwrap_or_default()
1163 impl Writeable for NodeAnnouncementInfo {
1164 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1165 let empty_addresses = Vec::<SocketAddress>::new();
1166 write_tlv_fields!(writer, {
1167 (0, self.features, required),
1168 (2, self.last_update, required),
1169 (4, self.rgb, required),
1170 (6, self.alias, required),
1171 (8, self.announcement_message, option),
1172 (10, empty_addresses, required_vec), // Versions prior to 0.0.115 require this field
1178 impl Readable for NodeAnnouncementInfo {
1179 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1180 _init_and_read_len_prefixed_tlv_fields!(reader, {
1181 (0, features, required),
1182 (2, last_update, required),
1184 (6, alias, required),
1185 (8, announcement_message, option),
1186 (10, _addresses, optional_vec), // deprecated, not used anymore
1188 let _: Option<Vec<SocketAddress>> = _addresses;
1189 Ok(Self { features: features.0.unwrap(), last_update: last_update.0.unwrap(), rgb: rgb.0.unwrap(),
1190 alias: alias.0.unwrap(), announcement_message })
1194 /// A user-defined name for a node, which may be used when displaying the node in a graph.
1196 /// Since node aliases are provided by third parties, they are a potential avenue for injection
1197 /// attacks. Care must be taken when processing.
1198 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
1199 pub struct NodeAlias(pub [u8; 32]);
1201 impl fmt::Display for NodeAlias {
1202 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1203 let first_null = self.0.iter().position(|b| *b == 0).unwrap_or(self.0.len());
1204 let bytes = self.0.split_at(first_null).0;
1205 match core::str::from_utf8(bytes) {
1206 Ok(alias) => PrintableString(alias).fmt(f)?,
1208 use core::fmt::Write;
1209 for c in bytes.iter().map(|b| *b as char) {
1210 // Display printable ASCII characters
1211 let control_symbol = core::char::REPLACEMENT_CHARACTER;
1212 let c = if c >= '\x20' && c <= '\x7e' { c } else { control_symbol };
1221 impl Writeable for NodeAlias {
1222 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1227 impl Readable for NodeAlias {
1228 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
1229 Ok(NodeAlias(Readable::read(r)?))
1233 #[derive(Clone, Debug, PartialEq, Eq)]
1234 /// Details about a node in the network, known from the network announcement.
1235 pub struct NodeInfo {
1236 /// All valid channels a node has announced
1237 pub channels: Vec<u64>,
1238 /// More information about a node from node_announcement.
1239 /// Optional because we store a Node entry after learning about it from
1240 /// a channel announcement, but before receiving a node announcement.
1241 pub announcement_info: Option<NodeAnnouncementInfo>
1245 /// Returns whether the node has only announced Tor addresses.
1246 pub fn is_tor_only(&self) -> bool {
1247 self.announcement_info
1249 .map(|info| info.addresses())
1250 .and_then(|addresses| (!addresses.is_empty()).then(|| addresses))
1251 .map(|addresses| addresses.iter().all(|address| address.is_tor()))
1256 impl fmt::Display for NodeInfo {
1257 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1258 write!(f, " channels: {:?}, announcement_info: {:?}",
1259 &self.channels[..], self.announcement_info)?;
1264 impl Writeable for NodeInfo {
1265 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1266 write_tlv_fields!(writer, {
1267 // Note that older versions of LDK wrote the lowest inbound fees here at type 0
1268 (2, self.announcement_info, option),
1269 (4, self.channels, required_vec),
1275 // A wrapper allowing for the optional deserialization of `NodeAnnouncementInfo`. Utilizing this is
1276 // necessary to maintain compatibility with previous serializations of `SocketAddress` that have an
1277 // invalid hostname set. We ignore and eat all errors until we are either able to read a
1278 // `NodeAnnouncementInfo` or hit a `ShortRead`, i.e., read the TLV field to the end.
1279 struct NodeAnnouncementInfoDeserWrapper(NodeAnnouncementInfo);
1281 impl MaybeReadable for NodeAnnouncementInfoDeserWrapper {
1282 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
1283 match crate::util::ser::Readable::read(reader) {
1284 Ok(node_announcement_info) => return Ok(Some(Self(node_announcement_info))),
1286 copy(reader, &mut sink()).unwrap();
1293 impl Readable for NodeInfo {
1294 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1295 // Historically, we tracked the lowest inbound fees for any node in order to use it as an
1296 // A* heuristic when routing. Sadly, these days many, many nodes have at least one channel
1297 // with zero inbound fees, causing that heuristic to provide little gain. Worse, because it
1298 // requires additional complexity and lookups during routing, it ends up being a
1299 // performance loss. Thus, we simply ignore the old field here and no longer track it.
1300 _init_and_read_len_prefixed_tlv_fields!(reader, {
1301 (0, _lowest_inbound_channel_fees, option),
1302 (2, announcement_info_wrap, upgradable_option),
1303 (4, channels, required_vec),
1305 let _: Option<RoutingFees> = _lowest_inbound_channel_fees;
1306 let announcement_info_wrap: Option<NodeAnnouncementInfoDeserWrapper> = announcement_info_wrap;
1309 announcement_info: announcement_info_wrap.map(|w| w.0),
1315 const SERIALIZATION_VERSION: u8 = 1;
1316 const MIN_SERIALIZATION_VERSION: u8 = 1;
1318 impl<L: Deref> Writeable for NetworkGraph<L> where L::Target: Logger {
1319 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1320 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1322 self.chain_hash.write(writer)?;
1323 let channels = self.channels.read().unwrap();
1324 (channels.len() as u64).write(writer)?;
1325 for (ref chan_id, ref chan_info) in channels.unordered_iter() {
1326 (*chan_id).write(writer)?;
1327 chan_info.write(writer)?;
1329 let nodes = self.nodes.read().unwrap();
1330 (nodes.len() as u64).write(writer)?;
1331 for (ref node_id, ref node_info) in nodes.unordered_iter() {
1332 node_id.write(writer)?;
1333 node_info.write(writer)?;
1336 let last_rapid_gossip_sync_timestamp = self.get_last_rapid_gossip_sync_timestamp();
1337 write_tlv_fields!(writer, {
1338 (1, last_rapid_gossip_sync_timestamp, option),
1344 impl<L: Deref> ReadableArgs<L> for NetworkGraph<L> where L::Target: Logger {
1345 fn read<R: io::Read>(reader: &mut R, logger: L) -> Result<NetworkGraph<L>, DecodeError> {
1346 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1348 let chain_hash: ChainHash = Readable::read(reader)?;
1349 let channels_count: u64 = Readable::read(reader)?;
1350 // In Nov, 2023 there were about 15,000 nodes; we cap allocations to 1.5x that.
1351 let mut channels = IndexedMap::with_capacity(cmp::min(channels_count as usize, 22500));
1352 for _ in 0..channels_count {
1353 let chan_id: u64 = Readable::read(reader)?;
1354 let chan_info = Readable::read(reader)?;
1355 channels.insert(chan_id, chan_info);
1357 let nodes_count: u64 = Readable::read(reader)?;
1358 // In Nov, 2023 there were about 69K channels; we cap allocations to 1.5x that.
1359 let mut nodes = IndexedMap::with_capacity(cmp::min(nodes_count as usize, 103500));
1360 for _ in 0..nodes_count {
1361 let node_id = Readable::read(reader)?;
1362 let node_info = Readable::read(reader)?;
1363 nodes.insert(node_id, node_info);
1366 let mut last_rapid_gossip_sync_timestamp: Option<u32> = None;
1367 read_tlv_fields!(reader, {
1368 (1, last_rapid_gossip_sync_timestamp, option),
1372 secp_ctx: Secp256k1::verification_only(),
1375 channels: RwLock::new(channels),
1376 nodes: RwLock::new(nodes),
1377 last_rapid_gossip_sync_timestamp: Mutex::new(last_rapid_gossip_sync_timestamp),
1378 removed_nodes: Mutex::new(new_hash_map()),
1379 removed_channels: Mutex::new(new_hash_map()),
1380 pending_checks: utxo::PendingChecks::new(),
1385 impl<L: Deref> fmt::Display for NetworkGraph<L> where L::Target: Logger {
1386 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1387 writeln!(f, "Network map\n[Channels]")?;
1388 for (key, val) in self.channels.read().unwrap().unordered_iter() {
1389 writeln!(f, " {}: {}", key, val)?;
1391 writeln!(f, "[Nodes]")?;
1392 for (&node_id, val) in self.nodes.read().unwrap().unordered_iter() {
1393 writeln!(f, " {}: {}", &node_id, val)?;
1399 impl<L: Deref> Eq for NetworkGraph<L> where L::Target: Logger {}
1400 impl<L: Deref> PartialEq for NetworkGraph<L> where L::Target: Logger {
1401 fn eq(&self, other: &Self) -> bool {
1402 // For a total lockorder, sort by position in memory and take the inner locks in that order.
1403 // (Assumes that we can't move within memory while a lock is held).
1404 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1405 let a = if ord { (&self.channels, &self.nodes) } else { (&other.channels, &other.nodes) };
1406 let b = if ord { (&other.channels, &other.nodes) } else { (&self.channels, &self.nodes) };
1407 let (channels_a, channels_b) = (a.0.unsafe_well_ordered_double_lock_self(), b.0.unsafe_well_ordered_double_lock_self());
1408 let (nodes_a, nodes_b) = (a.1.unsafe_well_ordered_double_lock_self(), b.1.unsafe_well_ordered_double_lock_self());
1409 self.chain_hash.eq(&other.chain_hash) && channels_a.eq(&channels_b) && nodes_a.eq(&nodes_b)
1413 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
1414 /// Creates a new, empty, network graph.
1415 pub fn new(network: Network, logger: L) -> NetworkGraph<L> {
1417 secp_ctx: Secp256k1::verification_only(),
1418 chain_hash: ChainHash::using_genesis_block(network),
1420 channels: RwLock::new(IndexedMap::new()),
1421 nodes: RwLock::new(IndexedMap::new()),
1422 last_rapid_gossip_sync_timestamp: Mutex::new(None),
1423 removed_channels: Mutex::new(new_hash_map()),
1424 removed_nodes: Mutex::new(new_hash_map()),
1425 pending_checks: utxo::PendingChecks::new(),
1429 /// Returns a read-only view of the network graph.
1430 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
1431 let channels = self.channels.read().unwrap();
1432 let nodes = self.nodes.read().unwrap();
1433 ReadOnlyNetworkGraph {
1439 /// The unix timestamp provided by the most recent rapid gossip sync.
1440 /// It will be set by the rapid sync process after every sync completion.
1441 pub fn get_last_rapid_gossip_sync_timestamp(&self) -> Option<u32> {
1442 self.last_rapid_gossip_sync_timestamp.lock().unwrap().clone()
1445 /// Update the unix timestamp provided by the most recent rapid gossip sync.
1446 /// This should be done automatically by the rapid sync process after every sync completion.
1447 pub fn set_last_rapid_gossip_sync_timestamp(&self, last_rapid_gossip_sync_timestamp: u32) {
1448 self.last_rapid_gossip_sync_timestamp.lock().unwrap().replace(last_rapid_gossip_sync_timestamp);
1451 /// Clears the `NodeAnnouncementInfo` field for all nodes in the `NetworkGraph` for testing
1454 pub fn clear_nodes_announcement_info(&self) {
1455 for node in self.nodes.write().unwrap().unordered_iter_mut() {
1456 node.1.announcement_info = None;
1460 /// For an already known node (from channel announcements), update its stored properties from a
1461 /// given node announcement.
1463 /// You probably don't want to call this directly, instead relying on a P2PGossipSync's
1464 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1465 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1466 pub fn update_node_from_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), LightningError> {
1467 verify_node_announcement(msg, &self.secp_ctx)?;
1468 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1471 /// For an already known node (from channel announcements), update its stored properties from a
1472 /// given node announcement without verifying the associated signatures. Because we aren't
1473 /// given the associated signatures here we cannot relay the node announcement to any of our
1475 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1476 self.update_node_from_announcement_intern(msg, None)
1479 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1480 let mut nodes = self.nodes.write().unwrap();
1481 match nodes.get_mut(&msg.node_id) {
1483 core::mem::drop(nodes);
1484 self.pending_checks.check_hold_pending_node_announcement(msg, full_msg)?;
1485 Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError})
1488 if let Some(node_info) = node.announcement_info.as_ref() {
1489 // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
1490 // updates to ensure you always have the latest one, only vaguely suggesting
1491 // that it be at least the current time.
1492 if node_info.last_update > msg.timestamp {
1493 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1494 } else if node_info.last_update == msg.timestamp {
1495 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1500 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1501 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1502 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1503 node.announcement_info = Some(NodeAnnouncementInfo {
1504 features: msg.features.clone(),
1505 last_update: msg.timestamp,
1508 announcement_message: if should_relay { full_msg.cloned() } else { None },
1516 /// Store or update channel info from a channel announcement.
1518 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1519 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1520 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1522 /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1523 /// the corresponding UTXO exists on chain and is correctly-formatted.
1524 pub fn update_channel_from_announcement<U: Deref>(
1525 &self, msg: &msgs::ChannelAnnouncement, utxo_lookup: &Option<U>,
1526 ) -> Result<(), LightningError>
1528 U::Target: UtxoLookup,
1530 verify_channel_announcement(msg, &self.secp_ctx)?;
1531 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), utxo_lookup)
1534 /// Store or update channel info from a channel announcement.
1536 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1537 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1538 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1540 /// This will skip verification of if the channel is actually on-chain.
1541 pub fn update_channel_from_announcement_no_lookup(
1542 &self, msg: &ChannelAnnouncement
1543 ) -> Result<(), LightningError> {
1544 self.update_channel_from_announcement::<&UtxoResolver>(msg, &None)
1547 /// Store or update channel info from a channel announcement without verifying the associated
1548 /// signatures. Because we aren't given the associated signatures here we cannot relay the
1549 /// channel announcement to any of our peers.
1551 /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1552 /// the corresponding UTXO exists on chain and is correctly-formatted.
1553 pub fn update_channel_from_unsigned_announcement<U: Deref>(
1554 &self, msg: &msgs::UnsignedChannelAnnouncement, utxo_lookup: &Option<U>
1555 ) -> Result<(), LightningError>
1557 U::Target: UtxoLookup,
1559 self.update_channel_from_unsigned_announcement_intern(msg, None, utxo_lookup)
1562 /// Update channel from partial announcement data received via rapid gossip sync
1564 /// `timestamp: u64`: Timestamp emulating the backdated original announcement receipt (by the
1565 /// rapid gossip sync server)
1567 /// All other parameters as used in [`msgs::UnsignedChannelAnnouncement`] fields.
1568 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> {
1569 if node_id_1 == node_id_2 {
1570 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1573 let node_1 = NodeId::from_pubkey(&node_id_1);
1574 let node_2 = NodeId::from_pubkey(&node_id_2);
1575 let channel_info = ChannelInfo {
1577 node_one: node_1.clone(),
1579 node_two: node_2.clone(),
1581 capacity_sats: None,
1582 announcement_message: None,
1583 announcement_received_time: timestamp,
1586 self.add_channel_between_nodes(short_channel_id, channel_info, None)
1589 fn add_channel_between_nodes(&self, short_channel_id: u64, channel_info: ChannelInfo, utxo_value: Option<u64>) -> Result<(), LightningError> {
1590 let mut channels = self.channels.write().unwrap();
1591 let mut nodes = self.nodes.write().unwrap();
1593 let node_id_a = channel_info.node_one.clone();
1594 let node_id_b = channel_info.node_two.clone();
1596 log_gossip!(self.logger, "Adding channel {} between nodes {} and {}", short_channel_id, node_id_a, node_id_b);
1598 match channels.entry(short_channel_id) {
1599 IndexedMapEntry::Occupied(mut entry) => {
1600 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1601 //in the blockchain API, we need to handle it smartly here, though it's unclear
1603 if utxo_value.is_some() {
1604 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1605 // only sometimes returns results. In any case remove the previous entry. Note
1606 // that the spec expects us to "blacklist" the node_ids involved, but we can't
1608 // a) we don't *require* a UTXO provider that always returns results.
1609 // b) we don't track UTXOs of channels we know about and remove them if they
1611 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1612 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), short_channel_id);
1613 *entry.get_mut() = channel_info;
1615 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1618 IndexedMapEntry::Vacant(entry) => {
1619 entry.insert(channel_info);
1623 for current_node_id in [node_id_a, node_id_b].iter() {
1624 match nodes.entry(current_node_id.clone()) {
1625 IndexedMapEntry::Occupied(node_entry) => {
1626 node_entry.into_mut().channels.push(short_channel_id);
1628 IndexedMapEntry::Vacant(node_entry) => {
1629 node_entry.insert(NodeInfo {
1630 channels: vec!(short_channel_id),
1631 announcement_info: None,
1640 fn update_channel_from_unsigned_announcement_intern<U: Deref>(
1641 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, utxo_lookup: &Option<U>
1642 ) -> Result<(), LightningError>
1644 U::Target: UtxoLookup,
1646 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1647 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1650 if msg.chain_hash != self.chain_hash {
1651 return Err(LightningError {
1652 err: "Channel announcement chain hash does not match genesis hash".to_owned(),
1653 action: ErrorAction::IgnoreAndLog(Level::Debug),
1658 let channels = self.channels.read().unwrap();
1660 if let Some(chan) = channels.get(&msg.short_channel_id) {
1661 if chan.capacity_sats.is_some() {
1662 // If we'd previously looked up the channel on-chain and checked the script
1663 // against what appears on-chain, ignore the duplicate announcement.
1665 // Because a reorg could replace one channel with another at the same SCID, if
1666 // the channel appears to be different, we re-validate. This doesn't expose us
1667 // to any more DoS risk than not, as a peer can always flood us with
1668 // randomly-generated SCID values anyway.
1670 // We use the Node IDs rather than the bitcoin_keys to check for "equivalence"
1671 // as we didn't (necessarily) store the bitcoin keys, and we only really care
1672 // if the peers on the channel changed anyway.
1673 if msg.node_id_1 == chan.node_one && msg.node_id_2 == chan.node_two {
1674 return Err(LightningError {
1675 err: "Already have chain-validated channel".to_owned(),
1676 action: ErrorAction::IgnoreDuplicateGossip
1679 } else if utxo_lookup.is_none() {
1680 // Similarly, if we can't check the chain right now anyway, ignore the
1681 // duplicate announcement without bothering to take the channels write lock.
1682 return Err(LightningError {
1683 err: "Already have non-chain-validated channel".to_owned(),
1684 action: ErrorAction::IgnoreDuplicateGossip
1691 let removed_channels = self.removed_channels.lock().unwrap();
1692 let removed_nodes = self.removed_nodes.lock().unwrap();
1693 if removed_channels.contains_key(&msg.short_channel_id) ||
1694 removed_nodes.contains_key(&msg.node_id_1) ||
1695 removed_nodes.contains_key(&msg.node_id_2) {
1696 return Err(LightningError{
1697 err: format!("Channel with SCID {} or one of its nodes was removed from our network graph recently", &msg.short_channel_id),
1698 action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1702 let utxo_value = self.pending_checks.check_channel_announcement(
1703 utxo_lookup, msg, full_msg)?;
1705 #[allow(unused_mut, unused_assignments)]
1706 let mut announcement_received_time = 0;
1707 #[cfg(feature = "std")]
1709 announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1712 let chan_info = ChannelInfo {
1713 features: msg.features.clone(),
1714 node_one: msg.node_id_1,
1716 node_two: msg.node_id_2,
1718 capacity_sats: utxo_value,
1719 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1720 { full_msg.cloned() } else { None },
1721 announcement_received_time,
1724 self.add_channel_between_nodes(msg.short_channel_id, chan_info, utxo_value)?;
1726 log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.short_channel_id, if !msg.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
1730 /// Marks a channel in the graph as failed permanently.
1732 /// The channel and any node for which this was their last channel are removed from the graph.
1733 pub fn channel_failed_permanent(&self, short_channel_id: u64) {
1734 #[cfg(feature = "std")]
1735 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1736 #[cfg(not(feature = "std"))]
1737 let current_time_unix = None;
1739 self.channel_failed_permanent_with_time(short_channel_id, current_time_unix)
1742 /// Marks a channel in the graph as failed permanently.
1744 /// The channel and any node for which this was their last channel are removed from the graph.
1745 fn channel_failed_permanent_with_time(&self, short_channel_id: u64, current_time_unix: Option<u64>) {
1746 let mut channels = self.channels.write().unwrap();
1747 if let Some(chan) = channels.remove(&short_channel_id) {
1748 let mut nodes = self.nodes.write().unwrap();
1749 self.removed_channels.lock().unwrap().insert(short_channel_id, current_time_unix);
1750 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1754 /// Marks a node in the graph as permanently failed, effectively removing it and its channels
1755 /// from local storage.
1756 pub fn node_failed_permanent(&self, node_id: &PublicKey) {
1757 #[cfg(feature = "std")]
1758 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1759 #[cfg(not(feature = "std"))]
1760 let current_time_unix = None;
1762 let node_id = NodeId::from_pubkey(node_id);
1763 let mut channels = self.channels.write().unwrap();
1764 let mut nodes = self.nodes.write().unwrap();
1765 let mut removed_channels = self.removed_channels.lock().unwrap();
1766 let mut removed_nodes = self.removed_nodes.lock().unwrap();
1768 if let Some(node) = nodes.remove(&node_id) {
1769 for scid in node.channels.iter() {
1770 if let Some(chan_info) = channels.remove(scid) {
1771 let other_node_id = if node_id == chan_info.node_one { chan_info.node_two } else { chan_info.node_one };
1772 if let IndexedMapEntry::Occupied(mut other_node_entry) = nodes.entry(other_node_id) {
1773 other_node_entry.get_mut().channels.retain(|chan_id| {
1776 if other_node_entry.get().channels.is_empty() {
1777 other_node_entry.remove_entry();
1780 removed_channels.insert(*scid, current_time_unix);
1783 removed_nodes.insert(node_id, current_time_unix);
1787 #[cfg(feature = "std")]
1788 /// Removes information about channels that we haven't heard any updates about in some time.
1789 /// This can be used regularly to prune the network graph of channels that likely no longer
1792 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1793 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1794 /// pruning occur for updates which are at least two weeks old, which we implement here.
1796 /// Note that for users of the `lightning-background-processor` crate this method may be
1797 /// automatically called regularly for you.
1799 /// This method will also cause us to stop tracking removed nodes and channels if they have been
1800 /// in the map for a while so that these can be resynced from gossip in the future.
1802 /// This method is only available with the `std` feature. See
1803 /// [`NetworkGraph::remove_stale_channels_and_tracking_with_time`] for `no-std` use.
1804 pub fn remove_stale_channels_and_tracking(&self) {
1805 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1806 self.remove_stale_channels_and_tracking_with_time(time);
1809 /// Removes information about channels that we haven't heard any updates about in some time.
1810 /// This can be used regularly to prune the network graph of channels that likely no longer
1813 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1814 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1815 /// pruning occur for updates which are at least two weeks old, which we implement here.
1817 /// This method will also cause us to stop tracking removed nodes and channels if they have been
1818 /// in the map for a while so that these can be resynced from gossip in the future.
1820 /// This function takes the current unix time as an argument. For users with the `std` feature
1821 /// enabled, [`NetworkGraph::remove_stale_channels_and_tracking`] may be preferable.
1822 pub fn remove_stale_channels_and_tracking_with_time(&self, current_time_unix: u64) {
1823 let mut channels = self.channels.write().unwrap();
1824 // Time out if we haven't received an update in at least 14 days.
1825 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1826 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1827 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1828 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1830 let mut scids_to_remove = Vec::new();
1831 for (scid, info) in channels.unordered_iter_mut() {
1832 if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1833 log_gossip!(self.logger, "Removing directional update one_to_two (0) for channel {} due to its timestamp {} being below {}",
1834 scid, info.one_to_two.as_ref().unwrap().last_update, min_time_unix);
1835 info.one_to_two = None;
1837 if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1838 log_gossip!(self.logger, "Removing directional update two_to_one (1) for channel {} due to its timestamp {} being below {}",
1839 scid, info.two_to_one.as_ref().unwrap().last_update, min_time_unix);
1840 info.two_to_one = None;
1842 if info.one_to_two.is_none() || info.two_to_one.is_none() {
1843 // We check the announcement_received_time here to ensure we don't drop
1844 // announcements that we just received and are just waiting for our peer to send a
1845 // channel_update for.
1846 let announcement_received_timestamp = info.announcement_received_time;
1847 if announcement_received_timestamp < min_time_unix as u64 {
1848 log_gossip!(self.logger, "Removing channel {} because both directional updates are missing and its announcement timestamp {} being below {}",
1849 scid, announcement_received_timestamp, min_time_unix);
1850 scids_to_remove.push(*scid);
1854 if !scids_to_remove.is_empty() {
1855 let mut nodes = self.nodes.write().unwrap();
1856 for scid in scids_to_remove {
1857 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1858 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
1859 self.removed_channels.lock().unwrap().insert(scid, Some(current_time_unix));
1863 let should_keep_tracking = |time: &mut Option<u64>| {
1864 if let Some(time) = time {
1865 current_time_unix.saturating_sub(*time) < REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS
1867 // NOTE: In the case of no-std, we won't have access to the current UNIX time at the time of removal,
1868 // so we'll just set the removal time here to the current UNIX time on the very next invocation
1869 // of this function.
1870 #[cfg(not(feature = "std"))]
1872 let mut tracked_time = Some(current_time_unix);
1873 core::mem::swap(time, &mut tracked_time);
1876 #[allow(unreachable_code)]
1880 self.removed_channels.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1881 self.removed_nodes.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1884 /// For an already known (from announcement) channel, update info about one of the directions
1887 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1888 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1889 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1891 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1892 /// materially in the future will be rejected.
1893 pub fn update_channel(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
1894 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), false)
1897 /// For an already known (from announcement) channel, update info about one of the directions
1898 /// of the channel without verifying the associated signatures. Because we aren't given the
1899 /// associated signatures here we cannot relay the channel update to any of our peers.
1901 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1902 /// materially in the future will be rejected.
1903 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1904 self.update_channel_internal(msg, None, None, false)
1907 /// For an already known (from announcement) channel, verify the given [`ChannelUpdate`].
1909 /// This checks whether the update currently is applicable by [`Self::update_channel`].
1911 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1912 /// materially in the future will be rejected.
1913 pub fn verify_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
1914 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), true)
1917 fn update_channel_internal(&self, msg: &msgs::UnsignedChannelUpdate,
1918 full_msg: Option<&msgs::ChannelUpdate>, sig: Option<&secp256k1::ecdsa::Signature>,
1919 only_verify: bool) -> Result<(), LightningError>
1921 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
1923 if msg.chain_hash != self.chain_hash {
1924 return Err(LightningError {
1925 err: "Channel update chain hash does not match genesis hash".to_owned(),
1926 action: ErrorAction::IgnoreAndLog(Level::Debug),
1930 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
1932 // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
1933 // disable this check during tests!
1934 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1935 if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
1936 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1938 if msg.timestamp as u64 > time + 60 * 60 * 24 {
1939 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1943 log_gossip!(self.logger, "Updating channel {} in direction {} with timestamp {}", msg.short_channel_id, msg.flags & 1, msg.timestamp);
1945 let mut channels = self.channels.write().unwrap();
1946 match channels.get_mut(&msg.short_channel_id) {
1948 core::mem::drop(channels);
1949 self.pending_checks.check_hold_pending_channel_update(msg, full_msg)?;
1950 return Err(LightningError {
1951 err: "Couldn't find channel for update".to_owned(),
1952 action: ErrorAction::IgnoreAndLog(Level::Gossip),
1956 if msg.htlc_maximum_msat > MAX_VALUE_MSAT {
1957 return Err(LightningError{err:
1958 "htlc_maximum_msat is larger than maximum possible msats".to_owned(),
1959 action: ErrorAction::IgnoreError});
1962 if let Some(capacity_sats) = channel.capacity_sats {
1963 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1964 // Don't query UTXO set here to reduce DoS risks.
1965 if capacity_sats > MAX_VALUE_MSAT / 1000 || msg.htlc_maximum_msat > capacity_sats * 1000 {
1966 return Err(LightningError{err:
1967 "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(),
1968 action: ErrorAction::IgnoreError});
1971 macro_rules! check_update_latest {
1972 ($target: expr) => {
1973 if let Some(existing_chan_info) = $target.as_ref() {
1974 // The timestamp field is somewhat of a misnomer - the BOLTs use it to
1975 // order updates to ensure you always have the latest one, only
1976 // suggesting that it be at least the current time. For
1977 // channel_updates specifically, the BOLTs discuss the possibility of
1978 // pruning based on the timestamp field being more than two weeks old,
1979 // but only in the non-normative section.
1980 if existing_chan_info.last_update > msg.timestamp {
1981 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1982 } else if existing_chan_info.last_update == msg.timestamp {
1983 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1989 macro_rules! get_new_channel_info {
1991 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1992 { full_msg.cloned() } else { None };
1994 let updated_channel_update_info = ChannelUpdateInfo {
1995 enabled: chan_enabled,
1996 last_update: msg.timestamp,
1997 cltv_expiry_delta: msg.cltv_expiry_delta,
1998 htlc_minimum_msat: msg.htlc_minimum_msat,
1999 htlc_maximum_msat: msg.htlc_maximum_msat,
2001 base_msat: msg.fee_base_msat,
2002 proportional_millionths: msg.fee_proportional_millionths,
2006 Some(updated_channel_update_info)
2010 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg)[..]);
2011 if msg.flags & 1 == 1 {
2012 check_update_latest!(channel.two_to_one);
2013 if let Some(sig) = sig {
2014 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
2015 err: "Couldn't parse source node pubkey".to_owned(),
2016 action: ErrorAction::IgnoreAndLog(Level::Debug)
2017 })?, "channel_update");
2020 channel.two_to_one = get_new_channel_info!();
2023 check_update_latest!(channel.one_to_two);
2024 if let Some(sig) = sig {
2025 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
2026 err: "Couldn't parse destination node pubkey".to_owned(),
2027 action: ErrorAction::IgnoreAndLog(Level::Debug)
2028 })?, "channel_update");
2031 channel.one_to_two = get_new_channel_info!();
2040 fn remove_channel_in_nodes(nodes: &mut IndexedMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
2041 macro_rules! remove_from_node {
2042 ($node_id: expr) => {
2043 if let IndexedMapEntry::Occupied(mut entry) = nodes.entry($node_id) {
2044 entry.get_mut().channels.retain(|chan_id| {
2045 short_channel_id != *chan_id
2047 if entry.get().channels.is_empty() {
2048 entry.remove_entry();
2051 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
2056 remove_from_node!(chan.node_one);
2057 remove_from_node!(chan.node_two);
2061 impl ReadOnlyNetworkGraph<'_> {
2062 /// Returns all known valid channels' short ids along with announced channel info.
2064 /// This is not exported to bindings users because we don't want to return lifetime'd references
2065 pub fn channels(&self) -> &IndexedMap<u64, ChannelInfo> {
2069 /// Returns information on a channel with the given id.
2070 pub fn channel(&self, short_channel_id: u64) -> Option<&ChannelInfo> {
2071 self.channels.get(&short_channel_id)
2074 #[cfg(c_bindings)] // Non-bindings users should use `channels`
2075 /// Returns the list of channels in the graph
2076 pub fn list_channels(&self) -> Vec<u64> {
2077 self.channels.unordered_keys().map(|c| *c).collect()
2080 /// Returns all known nodes' public keys along with announced node info.
2082 /// This is not exported to bindings users because we don't want to return lifetime'd references
2083 pub fn nodes(&self) -> &IndexedMap<NodeId, NodeInfo> {
2087 /// Returns information on a node with the given id.
2088 pub fn node(&self, node_id: &NodeId) -> Option<&NodeInfo> {
2089 self.nodes.get(node_id)
2092 #[cfg(c_bindings)] // Non-bindings users should use `nodes`
2093 /// Returns the list of nodes in the graph
2094 pub fn list_nodes(&self) -> Vec<NodeId> {
2095 self.nodes.unordered_keys().map(|n| *n).collect()
2098 /// Get network addresses by node id.
2099 /// Returns None if the requested node is completely unknown,
2100 /// or if node announcement for the node was never received.
2101 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<SocketAddress>> {
2102 self.nodes.get(&NodeId::from_pubkey(&pubkey))
2103 .and_then(|node| node.announcement_info.as_ref().map(|ann| ann.addresses().to_vec()))
2108 pub(crate) mod tests {
2109 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
2110 use crate::ln::channelmanager;
2111 use crate::ln::chan_utils::make_funding_redeemscript;
2112 #[cfg(feature = "std")]
2113 use crate::ln::features::InitFeatures;
2114 use crate::ln::msgs::SocketAddress;
2115 use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, NodeAlias, MAX_EXCESS_BYTES_FOR_RELAY, NodeId, RoutingFees, ChannelUpdateInfo, ChannelInfo, NodeAnnouncementInfo, NodeInfo};
2116 use crate::routing::utxo::{UtxoLookupError, UtxoResult};
2117 use crate::ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
2118 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
2119 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
2120 use crate::util::config::UserConfig;
2121 use crate::util::test_utils;
2122 use crate::util::ser::{Hostname, ReadableArgs, Readable, Writeable};
2123 use crate::util::scid_utils::scid_from_parts;
2125 use crate::routing::gossip::REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS;
2126 use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
2128 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
2129 use bitcoin::hashes::Hash;
2130 use bitcoin::hashes::hex::FromHex;
2131 use bitcoin::network::constants::Network;
2132 use bitcoin::blockdata::constants::ChainHash;
2133 use bitcoin::blockdata::script::ScriptBuf;
2134 use bitcoin::blockdata::transaction::TxOut;
2135 use bitcoin::secp256k1::{PublicKey, SecretKey};
2136 use bitcoin::secp256k1::{All, Secp256k1};
2139 use bitcoin::secp256k1;
2140 use crate::prelude::*;
2141 use crate::sync::Arc;
2143 fn create_network_graph() -> NetworkGraph<Arc<test_utils::TestLogger>> {
2144 let logger = Arc::new(test_utils::TestLogger::new());
2145 NetworkGraph::new(Network::Testnet, logger)
2148 fn create_gossip_sync(network_graph: &NetworkGraph<Arc<test_utils::TestLogger>>) -> (
2149 Secp256k1<All>, P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>,
2150 Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
2152 let secp_ctx = Secp256k1::new();
2153 let logger = Arc::new(test_utils::TestLogger::new());
2154 let gossip_sync = P2PGossipSync::new(network_graph, None, Arc::clone(&logger));
2155 (secp_ctx, gossip_sync)
2159 #[cfg(feature = "std")]
2160 fn request_full_sync_finite_times() {
2161 let network_graph = create_network_graph();
2162 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2163 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
2165 assert!(gossip_sync.should_request_full_sync(&node_id));
2166 assert!(gossip_sync.should_request_full_sync(&node_id));
2167 assert!(gossip_sync.should_request_full_sync(&node_id));
2168 assert!(gossip_sync.should_request_full_sync(&node_id));
2169 assert!(gossip_sync.should_request_full_sync(&node_id));
2170 assert!(!gossip_sync.should_request_full_sync(&node_id));
2173 pub(crate) fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
2174 let node_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_key));
2175 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2176 features: channelmanager::provided_node_features(&UserConfig::default()),
2180 alias: NodeAlias([0; 32]),
2181 addresses: Vec::new(),
2182 excess_address_data: Vec::new(),
2183 excess_data: Vec::new(),
2185 f(&mut unsigned_announcement);
2186 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2188 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2189 contents: unsigned_announcement
2193 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 {
2194 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
2195 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
2196 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2197 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2199 let mut unsigned_announcement = UnsignedChannelAnnouncement {
2200 features: channelmanager::provided_channel_features(&UserConfig::default()),
2201 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2202 short_channel_id: 0,
2203 node_id_1: NodeId::from_pubkey(&node_id_1),
2204 node_id_2: NodeId::from_pubkey(&node_id_2),
2205 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey)),
2206 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey)),
2207 excess_data: Vec::new(),
2209 f(&mut unsigned_announcement);
2210 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2211 ChannelAnnouncement {
2212 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_key),
2213 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_key),
2214 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_btckey),
2215 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_btckey),
2216 contents: unsigned_announcement,
2220 pub(crate) fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> ScriptBuf {
2221 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
2222 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
2223 make_funding_redeemscript(&PublicKey::from_secret_key(secp_ctx, &node_1_btckey),
2224 &PublicKey::from_secret_key(secp_ctx, &node_2_btckey)).to_v0_p2wsh()
2227 pub(crate) fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
2228 let mut unsigned_channel_update = UnsignedChannelUpdate {
2229 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2230 short_channel_id: 0,
2233 cltv_expiry_delta: 144,
2234 htlc_minimum_msat: 1_000_000,
2235 htlc_maximum_msat: 1_000_000,
2236 fee_base_msat: 10_000,
2237 fee_proportional_millionths: 20,
2238 excess_data: Vec::new()
2240 f(&mut unsigned_channel_update);
2241 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2243 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2244 contents: unsigned_channel_update
2249 fn handling_node_announcements() {
2250 let network_graph = create_network_graph();
2251 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2253 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2254 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2255 let zero_hash = Sha256dHash::hash(&[0; 32]);
2257 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2258 match gossip_sync.handle_node_announcement(&valid_announcement) {
2260 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
2264 // Announce a channel to add a corresponding node.
2265 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2266 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2267 Ok(res) => assert!(res),
2272 match gossip_sync.handle_node_announcement(&valid_announcement) {
2273 Ok(res) => assert!(res),
2277 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2278 match gossip_sync.handle_node_announcement(
2280 signature: secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey),
2281 contents: valid_announcement.contents.clone()
2284 Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
2287 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
2288 unsigned_announcement.timestamp += 1000;
2289 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2290 }, node_1_privkey, &secp_ctx);
2291 // Return false because contains excess data.
2292 match gossip_sync.handle_node_announcement(&announcement_with_data) {
2293 Ok(res) => assert!(!res),
2297 // Even though previous announcement was not relayed further, we still accepted it,
2298 // so we now won't accept announcements before the previous one.
2299 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
2300 unsigned_announcement.timestamp += 1000 - 10;
2301 }, node_1_privkey, &secp_ctx);
2302 match gossip_sync.handle_node_announcement(&outdated_announcement) {
2304 Err(e) => assert_eq!(e.err, "Update older than last processed update")
2309 fn handling_channel_announcements() {
2310 let secp_ctx = Secp256k1::new();
2311 let logger = test_utils::TestLogger::new();
2313 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2314 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2316 let good_script = get_channel_script(&secp_ctx);
2317 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2319 // Test if the UTXO lookups were not supported
2320 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2321 let mut gossip_sync = P2PGossipSync::new(&network_graph, None, &logger);
2322 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2323 Ok(res) => assert!(res),
2328 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2334 // If we receive announcement for the same channel (with UTXO lookups disabled),
2335 // drop new one on the floor, since we can't see any changes.
2336 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2338 Err(e) => assert_eq!(e.err, "Already have non-chain-validated channel")
2341 // Test if an associated transaction were not on-chain (or not confirmed).
2342 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2343 *chain_source.utxo_ret.lock().unwrap() = UtxoResult::Sync(Err(UtxoLookupError::UnknownTx));
2344 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2345 gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2347 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2348 unsigned_announcement.short_channel_id += 1;
2349 }, node_1_privkey, node_2_privkey, &secp_ctx);
2350 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2352 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2355 // Now test if the transaction is found in the UTXO set and the script is correct.
2356 *chain_source.utxo_ret.lock().unwrap() =
2357 UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script.clone() }));
2358 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2359 unsigned_announcement.short_channel_id += 2;
2360 }, node_1_privkey, node_2_privkey, &secp_ctx);
2361 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2362 Ok(res) => assert!(res),
2367 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2373 // If we receive announcement for the same channel, once we've validated it against the
2374 // chain, we simply ignore all new (duplicate) announcements.
2375 *chain_source.utxo_ret.lock().unwrap() =
2376 UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script }));
2377 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2379 Err(e) => assert_eq!(e.err, "Already have chain-validated channel")
2382 #[cfg(feature = "std")]
2384 use std::time::{SystemTime, UNIX_EPOCH};
2386 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2387 // Mark a node as permanently failed so it's tracked as removed.
2388 gossip_sync.network_graph().node_failed_permanent(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2390 // Return error and ignore valid channel announcement if one of the nodes has been tracked as removed.
2391 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2392 unsigned_announcement.short_channel_id += 3;
2393 }, node_1_privkey, node_2_privkey, &secp_ctx);
2394 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2396 Err(e) => assert_eq!(e.err, "Channel with SCID 3 or one of its nodes was removed from our network graph recently")
2399 gossip_sync.network_graph().remove_stale_channels_and_tracking_with_time(tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2401 // The above channel announcement should be handled as per normal now.
2402 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2403 Ok(res) => assert!(res),
2408 // Don't relay valid channels with excess data
2409 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2410 unsigned_announcement.short_channel_id += 4;
2411 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2412 }, node_1_privkey, node_2_privkey, &secp_ctx);
2413 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2414 Ok(res) => assert!(!res),
2418 let mut invalid_sig_announcement = valid_announcement.clone();
2419 invalid_sig_announcement.contents.excess_data = Vec::new();
2420 match gossip_sync.handle_channel_announcement(&invalid_sig_announcement) {
2422 Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
2425 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
2426 match gossip_sync.handle_channel_announcement(&channel_to_itself_announcement) {
2428 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2431 // Test that channel announcements with the wrong chain hash are ignored (network graph is testnet,
2432 // announcement is mainnet).
2433 let incorrect_chain_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2434 unsigned_announcement.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2435 }, node_1_privkey, node_2_privkey, &secp_ctx);
2436 match gossip_sync.handle_channel_announcement(&incorrect_chain_announcement) {
2438 Err(e) => assert_eq!(e.err, "Channel announcement chain hash does not match genesis hash")
2443 fn handling_channel_update() {
2444 let secp_ctx = Secp256k1::new();
2445 let logger = test_utils::TestLogger::new();
2446 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2447 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2448 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2450 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2451 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2453 let amount_sats = 1000_000;
2454 let short_channel_id;
2457 // Announce a channel we will update
2458 let good_script = get_channel_script(&secp_ctx);
2459 *chain_source.utxo_ret.lock().unwrap() =
2460 UtxoResult::Sync(Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() }));
2462 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2463 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2464 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2471 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2472 network_graph.verify_channel_update(&valid_channel_update).unwrap();
2473 match gossip_sync.handle_channel_update(&valid_channel_update) {
2474 Ok(res) => assert!(res),
2479 match network_graph.read_only().channels().get(&short_channel_id) {
2481 Some(channel_info) => {
2482 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
2483 assert!(channel_info.two_to_one.is_none());
2488 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2489 unsigned_channel_update.timestamp += 100;
2490 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2491 }, node_1_privkey, &secp_ctx);
2492 // Return false because contains excess data
2493 match gossip_sync.handle_channel_update(&valid_channel_update) {
2494 Ok(res) => assert!(!res),
2498 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2499 unsigned_channel_update.timestamp += 110;
2500 unsigned_channel_update.short_channel_id += 1;
2501 }, node_1_privkey, &secp_ctx);
2502 match gossip_sync.handle_channel_update(&valid_channel_update) {
2504 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2507 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2508 unsigned_channel_update.htlc_maximum_msat = MAX_VALUE_MSAT + 1;
2509 unsigned_channel_update.timestamp += 110;
2510 }, node_1_privkey, &secp_ctx);
2511 match gossip_sync.handle_channel_update(&valid_channel_update) {
2513 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
2516 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2517 unsigned_channel_update.htlc_maximum_msat = amount_sats * 1000 + 1;
2518 unsigned_channel_update.timestamp += 110;
2519 }, node_1_privkey, &secp_ctx);
2520 match gossip_sync.handle_channel_update(&valid_channel_update) {
2522 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
2525 // Even though previous update was not relayed further, we still accepted it,
2526 // so we now won't accept update before the previous one.
2527 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2528 unsigned_channel_update.timestamp += 100;
2529 }, node_1_privkey, &secp_ctx);
2530 match gossip_sync.handle_channel_update(&valid_channel_update) {
2532 Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
2535 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2536 unsigned_channel_update.timestamp += 500;
2537 }, node_1_privkey, &secp_ctx);
2538 let zero_hash = Sha256dHash::hash(&[0; 32]);
2539 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2540 invalid_sig_channel_update.signature = secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey);
2541 match gossip_sync.handle_channel_update(&invalid_sig_channel_update) {
2543 Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
2546 // Test that channel updates with the wrong chain hash are ignored (network graph is testnet, channel
2547 // update is mainet).
2548 let incorrect_chain_update = get_signed_channel_update(|unsigned_channel_update| {
2549 unsigned_channel_update.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2550 }, node_1_privkey, &secp_ctx);
2552 match gossip_sync.handle_channel_update(&incorrect_chain_update) {
2554 Err(e) => assert_eq!(e.err, "Channel update chain hash does not match genesis hash")
2559 fn handling_network_update() {
2560 let logger = test_utils::TestLogger::new();
2561 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2562 let secp_ctx = Secp256k1::new();
2564 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2565 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2566 let node_2_id = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2569 // There is no nodes in the table at the beginning.
2570 assert_eq!(network_graph.read_only().nodes().len(), 0);
2573 let short_channel_id;
2575 // Check we won't apply an update via `handle_network_update` for privacy reasons, but
2576 // can continue fine if we manually apply it.
2577 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2578 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2579 let chain_source: Option<&test_utils::TestChainSource> = None;
2580 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2581 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2583 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2584 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2586 network_graph.handle_network_update(&NetworkUpdate::ChannelUpdateMessage {
2587 msg: valid_channel_update.clone(),
2590 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2591 network_graph.update_channel(&valid_channel_update).unwrap();
2594 // Non-permanent failure doesn't touch the channel at all
2596 match network_graph.read_only().channels().get(&short_channel_id) {
2598 Some(channel_info) => {
2599 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2603 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2605 is_permanent: false,
2608 match network_graph.read_only().channels().get(&short_channel_id) {
2610 Some(channel_info) => {
2611 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2616 // Permanent closing deletes a channel
2617 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2622 assert_eq!(network_graph.read_only().channels().len(), 0);
2623 // Nodes are also deleted because there are no associated channels anymore
2624 assert_eq!(network_graph.read_only().nodes().len(), 0);
2627 // Get a new network graph since we don't want to track removed nodes in this test with "std"
2628 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2630 // Announce a channel to test permanent node failure
2631 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2632 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2633 let chain_source: Option<&test_utils::TestChainSource> = None;
2634 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2635 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2637 // Non-permanent node failure does not delete any nodes or channels
2638 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2640 is_permanent: false,
2643 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2644 assert!(network_graph.read_only().nodes().get(&NodeId::from_pubkey(&node_2_id)).is_some());
2646 // Permanent node failure deletes node and its channels
2647 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2652 assert_eq!(network_graph.read_only().nodes().len(), 0);
2653 // Channels are also deleted because the associated node has been deleted
2654 assert_eq!(network_graph.read_only().channels().len(), 0);
2659 fn test_channel_timeouts() {
2660 // Test the removal of channels with `remove_stale_channels_and_tracking`.
2661 let logger = test_utils::TestLogger::new();
2662 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2663 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2664 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &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();
2670 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2671 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2672 let chain_source: Option<&test_utils::TestChainSource> = None;
2673 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2674 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2676 // Submit two channel updates for each channel direction (update.flags bit).
2677 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2678 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2679 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2681 let valid_channel_update_2 = get_signed_channel_update(|update| {update.flags |=1;}, node_2_privkey, &secp_ctx);
2682 gossip_sync.handle_channel_update(&valid_channel_update_2).unwrap();
2683 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().two_to_one.is_some());
2685 network_graph.remove_stale_channels_and_tracking_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2686 assert_eq!(network_graph.read_only().channels().len(), 1);
2687 assert_eq!(network_graph.read_only().nodes().len(), 2);
2689 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2690 #[cfg(not(feature = "std"))] {
2691 // Make sure removed channels are tracked.
2692 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2694 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2695 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2697 #[cfg(feature = "std")]
2699 // In std mode, a further check is performed before fully removing the channel -
2700 // the channel_announcement must have been received at least two weeks ago. We
2701 // fudge that here by indicating the time has jumped two weeks.
2702 assert_eq!(network_graph.read_only().channels().len(), 1);
2703 assert_eq!(network_graph.read_only().nodes().len(), 2);
2705 // Note that the directional channel information will have been removed already..
2706 // We want to check that this will work even if *one* of the channel updates is recent,
2707 // so we should add it with a recent timestamp.
2708 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2709 use std::time::{SystemTime, UNIX_EPOCH};
2710 let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2711 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2712 unsigned_channel_update.timestamp = (announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
2713 }, node_1_privkey, &secp_ctx);
2714 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2715 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2716 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2717 // Make sure removed channels are tracked.
2718 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2719 // Provide a later time so that sufficient time has passed
2720 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2721 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2724 assert_eq!(network_graph.read_only().channels().len(), 0);
2725 assert_eq!(network_graph.read_only().nodes().len(), 0);
2726 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2728 #[cfg(feature = "std")]
2730 use std::time::{SystemTime, UNIX_EPOCH};
2732 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2734 // Clear tracked nodes and channels for clean slate
2735 network_graph.removed_channels.lock().unwrap().clear();
2736 network_graph.removed_nodes.lock().unwrap().clear();
2738 // Add a channel and nodes from channel announcement. So our network graph will
2739 // now only consist of two nodes and one channel between them.
2740 assert!(network_graph.update_channel_from_announcement(
2741 &valid_channel_announcement, &chain_source).is_ok());
2743 // Mark the channel as permanently failed. This will also remove the two nodes
2744 // and all of the entries will be tracked as removed.
2745 network_graph.channel_failed_permanent_with_time(short_channel_id, Some(tracking_time));
2747 // Should not remove from tracking if insufficient time has passed
2748 network_graph.remove_stale_channels_and_tracking_with_time(
2749 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS - 1);
2750 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1, "Removed channel count ≠1 with tracking_time {}", tracking_time);
2752 // Provide a later time so that sufficient time has passed
2753 network_graph.remove_stale_channels_and_tracking_with_time(
2754 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2755 assert!(network_graph.removed_channels.lock().unwrap().is_empty(), "Unexpectedly removed channels with tracking_time {}", tracking_time);
2756 assert!(network_graph.removed_nodes.lock().unwrap().is_empty(), "Unexpectedly removed nodes with tracking_time {}", tracking_time);
2759 #[cfg(not(feature = "std"))]
2761 // When we don't have access to the system clock, the time we started tracking removal will only
2762 // be that provided by the first call to `remove_stale_channels_and_tracking_with_time`. Hence,
2763 // only if sufficient time has passed after that first call, will the next call remove it from
2765 let removal_time = 1664619654;
2767 // Clear removed nodes and channels for clean slate
2768 network_graph.removed_channels.lock().unwrap().clear();
2769 network_graph.removed_nodes.lock().unwrap().clear();
2771 // Add a channel and nodes from channel announcement. So our network graph will
2772 // now only consist of two nodes and one channel between them.
2773 assert!(network_graph.update_channel_from_announcement(
2774 &valid_channel_announcement, &chain_source).is_ok());
2776 // Mark the channel as permanently failed. This will also remove the two nodes
2777 // and all of the entries will be tracked as removed.
2778 network_graph.channel_failed_permanent(short_channel_id);
2780 // The first time we call the following, the channel will have a removal time assigned.
2781 network_graph.remove_stale_channels_and_tracking_with_time(removal_time);
2782 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2784 // Provide a later time so that sufficient time has passed
2785 network_graph.remove_stale_channels_and_tracking_with_time(
2786 removal_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2787 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2788 assert!(network_graph.removed_nodes.lock().unwrap().is_empty());
2793 fn getting_next_channel_announcements() {
2794 let network_graph = create_network_graph();
2795 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2796 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2797 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2799 // Channels were not announced yet.
2800 let channels_with_announcements = gossip_sync.get_next_channel_announcement(0);
2801 assert!(channels_with_announcements.is_none());
2803 let short_channel_id;
2805 // Announce a channel we will update
2806 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2807 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2808 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2814 // Contains initial channel announcement now.
2815 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2816 if let Some(channel_announcements) = channels_with_announcements {
2817 let (_, ref update_1, ref update_2) = channel_announcements;
2818 assert_eq!(update_1, &None);
2819 assert_eq!(update_2, &None);
2825 // Valid channel update
2826 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2827 unsigned_channel_update.timestamp = 101;
2828 }, node_1_privkey, &secp_ctx);
2829 match gossip_sync.handle_channel_update(&valid_channel_update) {
2835 // Now contains an initial announcement and an update.
2836 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2837 if let Some(channel_announcements) = channels_with_announcements {
2838 let (_, ref update_1, ref update_2) = channel_announcements;
2839 assert_ne!(update_1, &None);
2840 assert_eq!(update_2, &None);
2846 // Channel update with excess data.
2847 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2848 unsigned_channel_update.timestamp = 102;
2849 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2850 }, node_1_privkey, &secp_ctx);
2851 match gossip_sync.handle_channel_update(&valid_channel_update) {
2857 // Test that announcements with excess data won't be returned
2858 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2859 if let Some(channel_announcements) = channels_with_announcements {
2860 let (_, ref update_1, ref update_2) = channel_announcements;
2861 assert_eq!(update_1, &None);
2862 assert_eq!(update_2, &None);
2867 // Further starting point have no channels after it
2868 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id + 1000);
2869 assert!(channels_with_announcements.is_none());
2873 fn getting_next_node_announcements() {
2874 let network_graph = create_network_graph();
2875 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2876 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2877 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2878 let node_id_1 = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2881 let next_announcements = gossip_sync.get_next_node_announcement(None);
2882 assert!(next_announcements.is_none());
2885 // Announce a channel to add 2 nodes
2886 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2887 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2893 // Nodes were never announced
2894 let next_announcements = gossip_sync.get_next_node_announcement(None);
2895 assert!(next_announcements.is_none());
2898 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2899 match gossip_sync.handle_node_announcement(&valid_announcement) {
2904 let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
2905 match gossip_sync.handle_node_announcement(&valid_announcement) {
2911 let next_announcements = gossip_sync.get_next_node_announcement(None);
2912 assert!(next_announcements.is_some());
2914 // Skip the first node.
2915 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
2916 assert!(next_announcements.is_some());
2919 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2920 let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
2921 unsigned_announcement.timestamp += 10;
2922 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2923 }, node_2_privkey, &secp_ctx);
2924 match gossip_sync.handle_node_announcement(&valid_announcement) {
2925 Ok(res) => assert!(!res),
2930 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
2931 assert!(next_announcements.is_none());
2935 fn network_graph_serialization() {
2936 let network_graph = create_network_graph();
2937 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2939 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2940 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2942 // Announce a channel to add a corresponding node.
2943 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2944 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2945 Ok(res) => assert!(res),
2949 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2950 match gossip_sync.handle_node_announcement(&valid_announcement) {
2955 let mut w = test_utils::TestVecWriter(Vec::new());
2956 assert!(!network_graph.read_only().nodes().is_empty());
2957 assert!(!network_graph.read_only().channels().is_empty());
2958 network_graph.write(&mut w).unwrap();
2960 let logger = Arc::new(test_utils::TestLogger::new());
2961 assert!(<NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), logger).unwrap() == network_graph);
2965 fn network_graph_tlv_serialization() {
2966 let network_graph = create_network_graph();
2967 network_graph.set_last_rapid_gossip_sync_timestamp(42);
2969 let mut w = test_utils::TestVecWriter(Vec::new());
2970 network_graph.write(&mut w).unwrap();
2972 let logger = Arc::new(test_utils::TestLogger::new());
2973 let reassembled_network_graph: NetworkGraph<_> = ReadableArgs::read(&mut io::Cursor::new(&w.0), logger).unwrap();
2974 assert!(reassembled_network_graph == network_graph);
2975 assert_eq!(reassembled_network_graph.get_last_rapid_gossip_sync_timestamp().unwrap(), 42);
2979 #[cfg(feature = "std")]
2980 fn calling_sync_routing_table() {
2981 use std::time::{SystemTime, UNIX_EPOCH};
2982 use crate::ln::msgs::Init;
2984 let network_graph = create_network_graph();
2985 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2986 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2987 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2989 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
2991 // It should ignore if gossip_queries feature is not enabled
2993 let init_msg = Init { features: InitFeatures::empty(), networks: None, remote_network_address: None };
2994 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
2995 let events = gossip_sync.get_and_clear_pending_msg_events();
2996 assert_eq!(events.len(), 0);
2999 // It should send a gossip_timestamp_filter with the correct information
3001 let mut features = InitFeatures::empty();
3002 features.set_gossip_queries_optional();
3003 let init_msg = Init { features, networks: None, remote_network_address: None };
3004 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3005 let events = gossip_sync.get_and_clear_pending_msg_events();
3006 assert_eq!(events.len(), 1);
3008 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
3009 assert_eq!(node_id, &node_id_1);
3010 assert_eq!(msg.chain_hash, chain_hash);
3011 let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
3012 assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
3013 assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
3014 assert_eq!(msg.timestamp_range, u32::max_value());
3016 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
3022 fn handling_query_channel_range() {
3023 let network_graph = create_network_graph();
3024 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3026 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3027 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3028 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3029 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
3031 let mut scids: Vec<u64> = vec![
3032 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
3033 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
3036 // used for testing multipart reply across blocks
3037 for block in 100000..=108001 {
3038 scids.push(scid_from_parts(block, 0, 0).unwrap());
3041 // used for testing resumption on same block
3042 scids.push(scid_from_parts(108001, 1, 0).unwrap());
3045 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
3046 unsigned_announcement.short_channel_id = scid;
3047 }, node_1_privkey, node_2_privkey, &secp_ctx);
3048 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3054 // Error when number_of_blocks=0
3055 do_handling_query_channel_range(
3059 chain_hash: chain_hash.clone(),
3061 number_of_blocks: 0,
3064 vec![ReplyChannelRange {
3065 chain_hash: chain_hash.clone(),
3067 number_of_blocks: 0,
3068 sync_complete: true,
3069 short_channel_ids: vec![]
3073 // Error when wrong chain
3074 do_handling_query_channel_range(
3078 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3080 number_of_blocks: 0xffff_ffff,
3083 vec![ReplyChannelRange {
3084 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3086 number_of_blocks: 0xffff_ffff,
3087 sync_complete: true,
3088 short_channel_ids: vec![],
3092 // Error when first_blocknum > 0xffffff
3093 do_handling_query_channel_range(
3097 chain_hash: chain_hash.clone(),
3098 first_blocknum: 0x01000000,
3099 number_of_blocks: 0xffff_ffff,
3102 vec![ReplyChannelRange {
3103 chain_hash: chain_hash.clone(),
3104 first_blocknum: 0x01000000,
3105 number_of_blocks: 0xffff_ffff,
3106 sync_complete: true,
3107 short_channel_ids: vec![]
3111 // Empty reply when max valid SCID block num
3112 do_handling_query_channel_range(
3116 chain_hash: chain_hash.clone(),
3117 first_blocknum: 0xffffff,
3118 number_of_blocks: 1,
3123 chain_hash: chain_hash.clone(),
3124 first_blocknum: 0xffffff,
3125 number_of_blocks: 1,
3126 sync_complete: true,
3127 short_channel_ids: vec![]
3132 // No results in valid query range
3133 do_handling_query_channel_range(
3137 chain_hash: chain_hash.clone(),
3138 first_blocknum: 1000,
3139 number_of_blocks: 1000,
3144 chain_hash: chain_hash.clone(),
3145 first_blocknum: 1000,
3146 number_of_blocks: 1000,
3147 sync_complete: true,
3148 short_channel_ids: vec![],
3153 // Overflow first_blocknum + number_of_blocks
3154 do_handling_query_channel_range(
3158 chain_hash: chain_hash.clone(),
3159 first_blocknum: 0xfe0000,
3160 number_of_blocks: 0xffffffff,
3165 chain_hash: chain_hash.clone(),
3166 first_blocknum: 0xfe0000,
3167 number_of_blocks: 0xffffffff - 0xfe0000,
3168 sync_complete: true,
3169 short_channel_ids: vec![
3170 0xfffffe_ffffff_ffff, // max
3176 // Single block exactly full
3177 do_handling_query_channel_range(
3181 chain_hash: chain_hash.clone(),
3182 first_blocknum: 100000,
3183 number_of_blocks: 8000,
3188 chain_hash: chain_hash.clone(),
3189 first_blocknum: 100000,
3190 number_of_blocks: 8000,
3191 sync_complete: true,
3192 short_channel_ids: (100000..=107999)
3193 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3199 // Multiple split on new block
3200 do_handling_query_channel_range(
3204 chain_hash: chain_hash.clone(),
3205 first_blocknum: 100000,
3206 number_of_blocks: 8001,
3211 chain_hash: chain_hash.clone(),
3212 first_blocknum: 100000,
3213 number_of_blocks: 7999,
3214 sync_complete: false,
3215 short_channel_ids: (100000..=107999)
3216 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3220 chain_hash: chain_hash.clone(),
3221 first_blocknum: 107999,
3222 number_of_blocks: 2,
3223 sync_complete: true,
3224 short_channel_ids: vec![
3225 scid_from_parts(108000, 0, 0).unwrap(),
3231 // Multiple split on same block
3232 do_handling_query_channel_range(
3236 chain_hash: chain_hash.clone(),
3237 first_blocknum: 100002,
3238 number_of_blocks: 8000,
3243 chain_hash: chain_hash.clone(),
3244 first_blocknum: 100002,
3245 number_of_blocks: 7999,
3246 sync_complete: false,
3247 short_channel_ids: (100002..=108001)
3248 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3252 chain_hash: chain_hash.clone(),
3253 first_blocknum: 108001,
3254 number_of_blocks: 1,
3255 sync_complete: true,
3256 short_channel_ids: vec![
3257 scid_from_parts(108001, 1, 0).unwrap(),
3264 fn do_handling_query_channel_range(
3265 gossip_sync: &P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
3266 test_node_id: &PublicKey,
3267 msg: QueryChannelRange,
3269 expected_replies: Vec<ReplyChannelRange>
3271 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
3272 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
3273 let query_end_blocknum = msg.end_blocknum();
3274 let result = gossip_sync.handle_query_channel_range(test_node_id, msg);
3277 assert!(result.is_ok());
3279 assert!(result.is_err());
3282 let events = gossip_sync.get_and_clear_pending_msg_events();
3283 assert_eq!(events.len(), expected_replies.len());
3285 for i in 0..events.len() {
3286 let expected_reply = &expected_replies[i];
3288 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
3289 assert_eq!(node_id, test_node_id);
3290 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
3291 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
3292 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
3293 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
3294 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
3296 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
3297 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
3298 assert!(msg.first_blocknum >= max_firstblocknum);
3299 max_firstblocknum = msg.first_blocknum;
3300 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
3302 // Check that the last block count is >= the query's end_blocknum
3303 if i == events.len() - 1 {
3304 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
3307 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
3313 fn handling_query_short_channel_ids() {
3314 let network_graph = create_network_graph();
3315 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3316 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3317 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
3319 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3321 let result = gossip_sync.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
3323 short_channel_ids: vec![0x0003e8_000000_0000],
3325 assert!(result.is_err());
3329 fn displays_node_alias() {
3330 let format_str_alias = |alias: &str| {
3331 let mut bytes = [0u8; 32];
3332 bytes[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
3333 format!("{}", NodeAlias(bytes))
3336 assert_eq!(format_str_alias("I\u{1F496}LDK! \u{26A1}"), "I\u{1F496}LDK! \u{26A1}");
3337 assert_eq!(format_str_alias("I\u{1F496}LDK!\0\u{26A1}"), "I\u{1F496}LDK!");
3338 assert_eq!(format_str_alias("I\u{1F496}LDK!\t\u{26A1}"), "I\u{1F496}LDK!\u{FFFD}\u{26A1}");
3340 let format_bytes_alias = |alias: &[u8]| {
3341 let mut bytes = [0u8; 32];
3342 bytes[..alias.len()].copy_from_slice(alias);
3343 format!("{}", NodeAlias(bytes))
3346 assert_eq!(format_bytes_alias(b"\xFFI <heart> LDK!"), "\u{FFFD}I <heart> LDK!");
3347 assert_eq!(format_bytes_alias(b"\xFFI <heart>\0LDK!"), "\u{FFFD}I <heart>");
3348 assert_eq!(format_bytes_alias(b"\xFFI <heart>\tLDK!"), "\u{FFFD}I <heart>\u{FFFD}LDK!");
3352 fn channel_info_is_readable() {
3353 let chanmon_cfgs = crate::ln::functional_test_utils::create_chanmon_cfgs(2);
3354 let node_cfgs = crate::ln::functional_test_utils::create_node_cfgs(2, &chanmon_cfgs);
3355 let node_chanmgrs = crate::ln::functional_test_utils::create_node_chanmgrs(2, &node_cfgs, &[None, None, None, None]);
3356 let nodes = crate::ln::functional_test_utils::create_network(2, &node_cfgs, &node_chanmgrs);
3357 let config = crate::ln::functional_test_utils::test_default_channel_config();
3359 // 1. Test encoding/decoding of ChannelUpdateInfo
3360 let chan_update_info = ChannelUpdateInfo {
3363 cltv_expiry_delta: 42,
3364 htlc_minimum_msat: 1234,
3365 htlc_maximum_msat: 5678,
3366 fees: RoutingFees { base_msat: 9, proportional_millionths: 10 },
3367 last_update_message: None,
3370 let mut encoded_chan_update_info: Vec<u8> = Vec::new();
3371 assert!(chan_update_info.write(&mut encoded_chan_update_info).is_ok());
3373 // First make sure we can read ChannelUpdateInfos we just wrote
3374 let read_chan_update_info: ChannelUpdateInfo = crate::util::ser::Readable::read(&mut encoded_chan_update_info.as_slice()).unwrap();
3375 assert_eq!(chan_update_info, read_chan_update_info);
3377 // Check the serialization hasn't changed.
3378 let legacy_chan_update_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c0100").unwrap();
3379 assert_eq!(encoded_chan_update_info, legacy_chan_update_info_with_some);
3381 // Check we fail if htlc_maximum_msat is not present in either the ChannelUpdateInfo itself
3382 // or the ChannelUpdate enclosed with `last_update_message`.
3383 let legacy_chan_update_info_with_some_and_fail_update: Vec<u8> = <Vec<u8>>::from_hex("b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f42400000271000000014").unwrap();
3384 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());
3385 assert!(read_chan_update_info_res.is_err());
3387 let legacy_chan_update_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100").unwrap();
3388 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());
3389 assert!(read_chan_update_info_res.is_err());
3391 // 2. Test encoding/decoding of ChannelInfo
3392 // Check we can encode/decode ChannelInfo without ChannelUpdateInfo fields present.
3393 let chan_info_none_updates = ChannelInfo {
3394 features: channelmanager::provided_channel_features(&config),
3395 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3397 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3399 capacity_sats: None,
3400 announcement_message: None,
3401 announcement_received_time: 87654,
3404 let mut encoded_chan_info: Vec<u8> = Vec::new();
3405 assert!(chan_info_none_updates.write(&mut encoded_chan_info).is_ok());
3407 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3408 assert_eq!(chan_info_none_updates, read_chan_info);
3410 // Check we can encode/decode ChannelInfo with ChannelUpdateInfo fields present.
3411 let chan_info_some_updates = ChannelInfo {
3412 features: channelmanager::provided_channel_features(&config),
3413 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3414 one_to_two: Some(chan_update_info.clone()),
3415 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3416 two_to_one: Some(chan_update_info.clone()),
3417 capacity_sats: None,
3418 announcement_message: None,
3419 announcement_received_time: 87654,
3422 let mut encoded_chan_info: Vec<u8> = Vec::new();
3423 assert!(chan_info_some_updates.write(&mut encoded_chan_info).is_ok());
3425 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3426 assert_eq!(chan_info_some_updates, read_chan_info);
3428 // Check the serialization hasn't changed.
3429 let legacy_chan_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88043636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23083636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3430 assert_eq!(encoded_chan_info, legacy_chan_info_with_some);
3432 // Check we can decode legacy ChannelInfo, even if the `two_to_one` / `one_to_two` /
3433 // `last_update_message` fields fail to decode due to missing htlc_maximum_msat.
3434 let legacy_chan_info_with_some_and_fail_update = <Vec<u8>>::from_hex("fd01ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce8804b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f4240000027100000001406210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2308b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f424000002710000000140a01000c0100").unwrap();
3435 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_some_and_fail_update.as_slice()).unwrap();
3436 assert_eq!(read_chan_info.announcement_received_time, 87654);
3437 assert_eq!(read_chan_info.one_to_two, None);
3438 assert_eq!(read_chan_info.two_to_one, None);
3440 let legacy_chan_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("ba00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88042e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23082e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3441 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_none.as_slice()).unwrap();
3442 assert_eq!(read_chan_info.announcement_received_time, 87654);
3443 assert_eq!(read_chan_info.one_to_two, None);
3444 assert_eq!(read_chan_info.two_to_one, None);
3448 fn node_info_is_readable() {
3449 // 1. Check we can read a valid NodeAnnouncementInfo and fail on an invalid one
3450 let announcement_message = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000122013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010000701fffefdfc2607").unwrap();
3451 let announcement_message = NodeAnnouncement::read(&mut announcement_message.as_slice()).unwrap();
3452 let valid_node_ann_info = NodeAnnouncementInfo {
3453 features: channelmanager::provided_node_features(&UserConfig::default()),
3456 alias: NodeAlias([0u8; 32]),
3457 announcement_message: Some(announcement_message)
3460 let mut encoded_valid_node_ann_info = Vec::new();
3461 assert!(valid_node_ann_info.write(&mut encoded_valid_node_ann_info).is_ok());
3462 let read_valid_node_ann_info = NodeAnnouncementInfo::read(&mut encoded_valid_node_ann_info.as_slice()).unwrap();
3463 assert_eq!(read_valid_node_ann_info, valid_node_ann_info);
3464 assert_eq!(read_valid_node_ann_info.addresses().len(), 1);
3466 let encoded_invalid_node_ann_info = <Vec<u8>>::from_hex("3f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d2").unwrap();
3467 let read_invalid_node_ann_info_res = NodeAnnouncementInfo::read(&mut encoded_invalid_node_ann_info.as_slice());
3468 assert!(read_invalid_node_ann_info_res.is_err());
3470 // 2. Check we can read a NodeInfo anyways, but set the NodeAnnouncementInfo to None if invalid
3471 let valid_node_info = NodeInfo {
3472 channels: Vec::new(),
3473 announcement_info: Some(valid_node_ann_info),
3476 let mut encoded_valid_node_info = Vec::new();
3477 assert!(valid_node_info.write(&mut encoded_valid_node_info).is_ok());
3478 let read_valid_node_info = NodeInfo::read(&mut encoded_valid_node_info.as_slice()).unwrap();
3479 assert_eq!(read_valid_node_info, valid_node_info);
3481 let encoded_invalid_node_info_hex = <Vec<u8>>::from_hex("4402403f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d20400").unwrap();
3482 let read_invalid_node_info = NodeInfo::read(&mut encoded_invalid_node_info_hex.as_slice()).unwrap();
3483 assert_eq!(read_invalid_node_info.announcement_info, None);
3487 fn test_node_info_keeps_compatibility() {
3488 let old_ann_info_with_addresses = <Vec<u8>>::from_hex("3f0009000708a000080a51220204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014104d2").unwrap();
3489 let ann_info_with_addresses = NodeAnnouncementInfo::read(&mut old_ann_info_with_addresses.as_slice())
3490 .expect("to be able to read an old NodeAnnouncementInfo with addresses");
3491 // This serialized info has an address field but no announcement_message, therefore the addresses returned by our function will still be empty
3492 assert!(ann_info_with_addresses.addresses().is_empty());
3496 fn test_node_id_display() {
3497 let node_id = NodeId([42; 33]);
3498 assert_eq!(format!("{}", &node_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
3502 fn is_tor_only_node() {
3503 let network_graph = create_network_graph();
3504 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3506 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3507 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3508 let node_1_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
3510 let announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3511 gossip_sync.handle_channel_announcement(&announcement).unwrap();
3513 let tcp_ip_v4 = SocketAddress::TcpIpV4 {
3514 addr: [255, 254, 253, 252],
3517 let tcp_ip_v6 = SocketAddress::TcpIpV6 {
3518 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
3521 let onion_v2 = SocketAddress::OnionV2([255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]);
3522 let onion_v3 = SocketAddress::OnionV3 {
3523 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],
3528 let hostname = SocketAddress::Hostname {
3529 hostname: Hostname::try_from(String::from("host")).unwrap(),
3533 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3535 let announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3536 gossip_sync.handle_node_announcement(&announcement).unwrap();
3537 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3539 let announcement = get_signed_node_announcement(
3541 announcement.addresses = vec![
3542 tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone(),
3545 announcement.timestamp += 1000;
3547 node_1_privkey, &secp_ctx
3549 gossip_sync.handle_node_announcement(&announcement).unwrap();
3550 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3552 let announcement = get_signed_node_announcement(
3554 announcement.addresses = vec![
3555 tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3557 announcement.timestamp += 2000;
3559 node_1_privkey, &secp_ctx
3561 gossip_sync.handle_node_announcement(&announcement).unwrap();
3562 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3564 let announcement = get_signed_node_announcement(
3566 announcement.addresses = vec![
3567 tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3569 announcement.timestamp += 3000;
3571 node_1_privkey, &secp_ctx
3573 gossip_sync.handle_node_announcement(&announcement).unwrap();
3574 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3576 let announcement = get_signed_node_announcement(
3578 announcement.addresses = vec![onion_v2.clone(), onion_v3.clone()];
3579 announcement.timestamp += 4000;
3581 node_1_privkey, &secp_ctx
3583 gossip_sync.handle_node_announcement(&announcement).unwrap();
3584 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3586 let announcement = get_signed_node_announcement(
3588 announcement.addresses = vec![onion_v2.clone()];
3589 announcement.timestamp += 5000;
3591 node_1_privkey, &secp_ctx
3593 gossip_sync.handle_node_announcement(&announcement).unwrap();
3594 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3596 let announcement = get_signed_node_announcement(
3598 announcement.addresses = vec![tcp_ip_v4.clone()];
3599 announcement.timestamp += 6000;
3601 node_1_privkey, &secp_ctx
3603 gossip_sync.handle_node_announcement(&announcement).unwrap();
3604 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3612 use criterion::{black_box, Criterion};
3614 pub fn read_network_graph(bench: &mut Criterion) {
3615 let logger = crate::util::test_utils::TestLogger::new();
3616 let mut d = crate::routing::router::bench_utils::get_route_file().unwrap();
3617 let mut v = Vec::new();
3618 d.read_to_end(&mut v).unwrap();
3619 bench.bench_function("read_network_graph", |b| b.iter(||
3620 NetworkGraph::read(&mut std::io::Cursor::new(black_box(&v)), &logger).unwrap()
3624 pub fn write_network_graph(bench: &mut Criterion) {
3625 let logger = crate::util::test_utils::TestLogger::new();
3626 let mut d = crate::routing::router::bench_utils::get_route_file().unwrap();
3627 let net_graph = NetworkGraph::read(&mut d, &logger).unwrap();
3628 bench.bench_function("write_network_graph", |b| b.iter(||
3629 black_box(&net_graph).encode()