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::amount::Amount;
13 use bitcoin::blockdata::constants::ChainHash;
15 use bitcoin::secp256k1;
16 use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
17 use bitcoin::secp256k1::Secp256k1;
18 use bitcoin::secp256k1::{PublicKey, Verification};
20 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
21 use bitcoin::hashes::Hash;
22 use bitcoin::network::Network;
24 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
25 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
27 use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, GossipTimestampFilter, NodeAnnouncement};
28 use crate::ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, SocketAddress, MAX_VALUE_MSAT};
29 use crate::ln::msgs::{QueryChannelRange, QueryShortChannelIds, ReplyChannelRange, ReplyShortChannelIdsEnd};
30 use crate::ln::types::ChannelId;
31 use crate::routing::utxo::{self, UtxoLookup, UtxoResolver};
32 use crate::util::indexed_map::{Entry as IndexedMapEntry, IndexedMap};
33 use crate::util::logger::{Level, Logger};
34 use crate::util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
35 use crate::util::ser::{MaybeReadable, Readable, ReadableArgs, RequiredWrapper, Writeable, Writer};
36 use crate::util::string::PrintableString;
39 use crate::io_extras::{copy, sink};
40 use crate::prelude::*;
41 use crate::sync::Mutex;
42 use crate::sync::{LockTestExt, RwLock, RwLockReadGuard};
43 use core::ops::{Bound, Deref};
44 use core::str::FromStr;
45 #[cfg(feature = "std")]
46 use core::sync::atomic::{AtomicUsize, Ordering};
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 that a channel failed to route a payment, which should be applied via
223 /// [`NetworkGraph::channel_failed_permanent`] if permanent.
225 /// The short channel id of the closed channel.
226 short_channel_id: u64,
227 /// Whether the channel should be permanently removed or temporarily disabled until a new
228 /// `channel_update` message is received.
231 /// An error indicating that a node failed to route a payment, which should be applied via
232 /// [`NetworkGraph::node_failed_permanent`] if permanent.
234 /// The node id of the failed node.
236 /// Whether the node should be permanently removed from consideration or can be restored
237 /// when a new `channel_update` message is received.
242 impl Writeable for NetworkUpdate {
243 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
245 Self::ChannelFailure { short_channel_id, is_permanent } => {
247 write_tlv_fields!(writer, {
248 (0, short_channel_id, required),
249 (2, is_permanent, required),
252 Self::NodeFailure { node_id, is_permanent } => {
254 write_tlv_fields!(writer, {
255 (0, node_id, required),
256 (2, is_permanent, required),
264 impl MaybeReadable for NetworkUpdate {
265 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
266 let id: u8 = Readable::read(reader)?;
269 // 0 was previously used for network updates containing a channel update, subsequently
270 // removed in LDK version 0.0.124.
271 let mut msg: RequiredWrapper<ChannelUpdate> = RequiredWrapper(None);
272 read_tlv_fields!(reader, {
275 Ok(Some(Self::ChannelFailure {
276 short_channel_id: msg.0.unwrap().contents.short_channel_id,
281 _init_and_read_len_prefixed_tlv_fields!(reader, {
282 (0, short_channel_id, required),
283 (2, is_permanent, required),
285 Ok(Some(Self::ChannelFailure {
286 short_channel_id: short_channel_id.0.unwrap(),
287 is_permanent: is_permanent.0.unwrap(),
291 _init_and_read_len_prefixed_tlv_fields!(reader, {
292 (0, node_id, required),
293 (2, is_permanent, required),
295 Ok(Some(Self::NodeFailure {
296 node_id: node_id.0.unwrap(),
297 is_permanent: is_permanent.0.unwrap(),
300 t if t % 2 == 0 => Err(DecodeError::UnknownRequiredFeature),
306 /// Receives and validates network updates from peers,
307 /// stores authentic and relevant data as a network graph.
308 /// This network graph is then used for routing payments.
309 /// Provides interface to help with initial routing sync by
310 /// serving historical announcements.
311 pub struct P2PGossipSync<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref>
312 where U::Target: UtxoLookup, L::Target: Logger
315 utxo_lookup: RwLock<Option<U>>,
316 #[cfg(feature = "std")]
317 full_syncs_requested: AtomicUsize,
318 pending_events: Mutex<Vec<MessageSendEvent>>,
322 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> P2PGossipSync<G, U, L>
323 where U::Target: UtxoLookup, L::Target: Logger
325 /// Creates a new tracker of the actual state of the network of channels and nodes,
326 /// assuming an existing [`NetworkGraph`].
327 /// UTXO lookup is used to make sure announced channels exist on-chain, channel data is
328 /// correct, and the announcement is signed with channel owners' keys.
329 pub fn new(network_graph: G, utxo_lookup: Option<U>, logger: L) -> Self {
332 #[cfg(feature = "std")]
333 full_syncs_requested: AtomicUsize::new(0),
334 utxo_lookup: RwLock::new(utxo_lookup),
335 pending_events: Mutex::new(vec![]),
340 /// Adds a provider used to check new announcements. Does not affect
341 /// existing announcements unless they are updated.
342 /// Add, update or remove the provider would replace the current one.
343 pub fn add_utxo_lookup(&self, utxo_lookup: Option<U>) {
344 *self.utxo_lookup.write().unwrap() = utxo_lookup;
347 /// Gets a reference to the underlying [`NetworkGraph`] which was provided in
348 /// [`P2PGossipSync::new`].
350 /// This is not exported to bindings users as bindings don't support a reference-to-a-reference yet
351 pub fn network_graph(&self) -> &G {
355 #[cfg(feature = "std")]
356 /// Returns true when a full routing table sync should be performed with a peer.
357 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
358 //TODO: Determine whether to request a full sync based on the network map.
359 const FULL_SYNCS_TO_REQUEST: usize = 5;
360 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
361 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
368 /// Used to broadcast forward gossip messages which were validated async.
370 /// Note that this will ignore events other than `Broadcast*` or messages with too much excess
372 pub(super) fn forward_gossip_msg(&self, mut ev: MessageSendEvent) {
374 MessageSendEvent::BroadcastChannelAnnouncement { msg, ref mut update_msg } => {
375 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
376 if update_msg.as_ref()
377 .map(|msg| msg.contents.excess_data.len()).unwrap_or(0) > MAX_EXCESS_BYTES_FOR_RELAY
382 MessageSendEvent::BroadcastChannelUpdate { msg } => {
383 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
385 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
386 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY ||
387 msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY ||
388 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY
395 self.pending_events.lock().unwrap().push(ev);
399 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
400 /// Handles any network updates originating from [`Event`]s.
402 /// [`Event`]: crate::events::Event
403 pub fn handle_network_update(&self, network_update: &NetworkUpdate) {
404 match *network_update {
405 NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } => {
407 log_debug!(self.logger, "Removing channel graph entry for {} due to a payment failure.", short_channel_id);
408 self.channel_failed_permanent(short_channel_id);
411 NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
413 log_debug!(self.logger,
414 "Removed node graph entry for {} due to a payment failure.", log_pubkey!(node_id));
415 self.node_failed_permanent(node_id);
421 /// Gets the chain hash for this network graph.
422 pub fn get_chain_hash(&self) -> ChainHash {
427 macro_rules! secp_verify_sig {
428 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr, $msg_type: expr ) => {
429 match $secp_ctx.verify_ecdsa($msg, $sig, $pubkey) {
432 return Err(LightningError {
433 err: format!("Invalid signature on {} message", $msg_type),
434 action: ErrorAction::SendWarningMessage {
435 msg: msgs::WarningMessage {
436 channel_id: ChannelId::new_zero(),
437 data: format!("Invalid signature on {} message", $msg_type),
439 log_level: Level::Trace,
447 macro_rules! get_pubkey_from_node_id {
448 ( $node_id: expr, $msg_type: expr ) => {
449 PublicKey::from_slice($node_id.as_slice())
450 .map_err(|_| LightningError {
451 err: format!("Invalid public key on {} message", $msg_type),
452 action: ErrorAction::SendWarningMessage {
453 msg: msgs::WarningMessage {
454 channel_id: ChannelId::new_zero(),
455 data: format!("Invalid public key on {} message", $msg_type),
457 log_level: Level::Trace
463 fn message_sha256d_hash<M: Writeable>(msg: &M) -> Sha256dHash {
464 let mut engine = Sha256dHash::engine();
465 msg.write(&mut engine).expect("In-memory structs should not fail to serialize");
466 Sha256dHash::from_engine(engine)
469 /// Verifies the signature of a [`NodeAnnouncement`].
471 /// Returns an error if it is invalid.
472 pub fn verify_node_announcement<C: Verification>(msg: &NodeAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
473 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg.contents)[..]);
474 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &get_pubkey_from_node_id!(msg.contents.node_id, "node_announcement"), "node_announcement");
479 /// Verifies all signatures included in a [`ChannelAnnouncement`].
481 /// Returns an error if one of the signatures is invalid.
482 pub fn verify_channel_announcement<C: Verification>(msg: &ChannelAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
483 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg.contents)[..]);
484 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");
485 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");
486 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");
487 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");
492 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> RoutingMessageHandler for P2PGossipSync<G, U, L>
493 where U::Target: UtxoLookup, L::Target: Logger
495 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
496 self.network_graph.update_node_from_announcement(msg)?;
497 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
498 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
499 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
502 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
503 self.network_graph.update_channel_from_announcement(msg, &*self.utxo_lookup.read().unwrap())?;
504 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
507 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
508 self.network_graph.update_channel(msg)?;
509 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
512 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
513 let mut channels = self.network_graph.channels.write().unwrap();
514 for (_, ref chan) in channels.range(starting_point..) {
515 if chan.announcement_message.is_some() {
516 let chan_announcement = chan.announcement_message.clone().unwrap();
517 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
518 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
519 if let Some(one_to_two) = chan.one_to_two.as_ref() {
520 one_to_two_announcement = one_to_two.last_update_message.clone();
522 if let Some(two_to_one) = chan.two_to_one.as_ref() {
523 two_to_one_announcement = two_to_one.last_update_message.clone();
525 return Some((chan_announcement, one_to_two_announcement, two_to_one_announcement));
527 // TODO: We may end up sending un-announced channel_updates if we are sending
528 // initial sync data while receiving announce/updates for this channel.
534 fn get_next_node_announcement(&self, starting_point: Option<&NodeId>) -> Option<NodeAnnouncement> {
535 let mut nodes = self.network_graph.nodes.write().unwrap();
536 let iter = if let Some(node_id) = starting_point {
537 nodes.range((Bound::Excluded(node_id), Bound::Unbounded))
541 for (_, ref node) in iter {
542 if let Some(node_info) = node.announcement_info.as_ref() {
543 if let NodeAnnouncementInfo::Relayed(announcement) = node_info {
544 return Some(announcement.clone());
551 /// Initiates a stateless sync of routing gossip information with a peer
552 /// using [`gossip_queries`]. The default strategy used by this implementation
553 /// is to sync the full block range with several peers.
555 /// We should expect one or more [`reply_channel_range`] messages in response
556 /// to our [`query_channel_range`]. Each reply will enqueue a [`query_scid`] message
557 /// to request gossip messages for each channel. The sync is considered complete
558 /// when the final [`reply_scids_end`] message is received, though we are not
559 /// tracking this directly.
561 /// [`gossip_queries`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#query-messages
562 /// [`reply_channel_range`]: msgs::ReplyChannelRange
563 /// [`query_channel_range`]: msgs::QueryChannelRange
564 /// [`query_scid`]: msgs::QueryShortChannelIds
565 /// [`reply_scids_end`]: msgs::ReplyShortChannelIdsEnd
566 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &Init, _inbound: bool) -> Result<(), ()> {
567 // We will only perform a sync with peers that support gossip_queries.
568 if !init_msg.features.supports_gossip_queries() {
569 // Don't disconnect peers for not supporting gossip queries. We may wish to have
570 // channels with peers even without being able to exchange gossip.
574 // The lightning network's gossip sync system is completely broken in numerous ways.
576 // Given no broadly-available set-reconciliation protocol, the only reasonable approach is
577 // to do a full sync from the first few peers we connect to, and then receive gossip
578 // updates from all our peers normally.
580 // Originally, we could simply tell a peer to dump us the entire gossip table on startup,
581 // wasting lots of bandwidth but ensuring we have the full network graph. After the initial
582 // dump peers would always send gossip and we'd stay up-to-date with whatever our peer has
585 // In order to reduce the bandwidth waste, "gossip queries" were introduced, allowing you
586 // to ask for the SCIDs of all channels in your peer's routing graph, and then only request
587 // channel data which you are missing. Except there was no way at all to identify which
588 // `channel_update`s you were missing, so you still had to request everything, just in a
589 // very complicated way with some queries instead of just getting the dump.
591 // Later, an option was added to fetch the latest timestamps of the `channel_update`s to
592 // make efficient sync possible, however it has yet to be implemented in lnd, which makes
593 // relying on it useless.
595 // After gossip queries were introduced, support for receiving a full gossip table dump on
596 // connection was removed from several nodes, making it impossible to get a full sync
597 // without using the "gossip queries" messages.
599 // Once you opt into "gossip queries" the only way to receive any gossip updates that a
600 // peer receives after you connect, you must send a `gossip_timestamp_filter` message. This
601 // message, as the name implies, tells the peer to not forward any gossip messages with a
602 // timestamp older than a given value (not the time the peer received the filter, but the
603 // timestamp in the update message, which is often hours behind when the peer received the
606 // Obnoxiously, `gossip_timestamp_filter` isn't *just* a filter, but its also a request for
607 // your peer to send you the full routing graph (subject to the filter). Thus, in order to
608 // tell a peer to send you any updates as it sees them, you have to also ask for the full
609 // routing graph to be synced. If you set a timestamp filter near the current time, peers
610 // will simply not forward any new updates they see to you which were generated some time
611 // ago (which is not uncommon). If you instead set a timestamp filter near 0 (or two weeks
612 // ago), you will always get the full routing graph from all your peers.
614 // Most lightning nodes today opt to simply turn off receiving gossip data which only
615 // propagated some time after it was generated, and, worse, often disable gossiping with
616 // several peers after their first connection. The second behavior can cause gossip to not
617 // propagate fully if there are cuts in the gossiping subgraph.
619 // In an attempt to cut a middle ground between always fetching the full graph from all of
620 // our peers and never receiving gossip from peers at all, we send all of our peers a
621 // `gossip_timestamp_filter`, with the filter time set either two weeks ago or an hour ago.
623 // For no-std builds, we bury our head in the sand and do a full sync on each connection.
624 #[allow(unused_mut, unused_assignments)]
625 let mut gossip_start_time = 0;
626 #[cfg(feature = "std")]
628 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
629 if self.should_request_full_sync(&their_node_id) {
630 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
632 gossip_start_time -= 60 * 60; // an hour ago
636 let mut pending_events = self.pending_events.lock().unwrap();
637 pending_events.push(MessageSendEvent::SendGossipTimestampFilter {
638 node_id: their_node_id.clone(),
639 msg: GossipTimestampFilter {
640 chain_hash: self.network_graph.chain_hash,
641 first_timestamp: gossip_start_time as u32, // 2106 issue!
642 timestamp_range: u32::max_value(),
648 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: ReplyChannelRange) -> Result<(), LightningError> {
649 // We don't make queries, so should never receive replies. If, in the future, the set
650 // reconciliation extensions to gossip queries become broadly supported, we should revert
651 // this code to its state pre-0.0.106.
655 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
656 // We don't make queries, so should never receive replies. If, in the future, the set
657 // reconciliation extensions to gossip queries become broadly supported, we should revert
658 // this code to its state pre-0.0.106.
662 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
663 /// are in the specified block range. Due to message size limits, large range
664 /// queries may result in several reply messages. This implementation enqueues
665 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
666 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
667 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
668 /// memory constrained systems.
669 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
670 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);
672 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
674 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
675 // If so, we manually cap the ending block to avoid this overflow.
676 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
678 // Per spec, we must reply to a query. Send an empty message when things are invalid.
679 if msg.chain_hash != self.network_graph.chain_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
680 let mut pending_events = self.pending_events.lock().unwrap();
681 pending_events.push(MessageSendEvent::SendReplyChannelRange {
682 node_id: their_node_id.clone(),
683 msg: ReplyChannelRange {
684 chain_hash: msg.chain_hash.clone(),
685 first_blocknum: msg.first_blocknum,
686 number_of_blocks: msg.number_of_blocks,
688 short_channel_ids: vec![],
691 return Err(LightningError {
692 err: String::from("query_channel_range could not be processed"),
693 action: ErrorAction::IgnoreError,
697 // Creates channel batches. We are not checking if the channel is routable
698 // (has at least one update). A peer may still want to know the channel
699 // exists even if its not yet routable.
700 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
701 let mut channels = self.network_graph.channels.write().unwrap();
702 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
703 if let Some(chan_announcement) = &chan.announcement_message {
704 // Construct a new batch if last one is full
705 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
706 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
709 let batch = batches.last_mut().unwrap();
710 batch.push(chan_announcement.contents.short_channel_id);
715 let mut pending_events = self.pending_events.lock().unwrap();
716 let batch_count = batches.len();
717 let mut prev_batch_endblock = msg.first_blocknum;
718 for (batch_index, batch) in batches.into_iter().enumerate() {
719 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
720 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
722 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
723 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
724 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
725 // significant diversion from the requirements set by the spec, and, in case of blocks
726 // with no channel opens (e.g. empty blocks), requires that we use the previous value
727 // and *not* derive the first_blocknum from the actual first block of the reply.
728 let first_blocknum = prev_batch_endblock;
730 // Each message carries the number of blocks (from the `first_blocknum`) its contents
731 // fit in. Though there is no requirement that we use exactly the number of blocks its
732 // contents are from, except for the bogus requirements c-lightning enforces, above.
734 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
735 // >= the query's end block. Thus, for the last reply, we calculate the difference
736 // between the query's end block and the start of the reply.
738 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
739 // first_blocknum will be either msg.first_blocknum or a higher block height.
740 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
741 (true, msg.end_blocknum() - first_blocknum)
743 // Prior replies should use the number of blocks that fit into the reply. Overflow
744 // safe since first_blocknum is always <= last SCID's block.
746 (false, block_from_scid(*batch.last().unwrap()) - first_blocknum)
749 prev_batch_endblock = first_blocknum + number_of_blocks;
751 pending_events.push(MessageSendEvent::SendReplyChannelRange {
752 node_id: their_node_id.clone(),
753 msg: ReplyChannelRange {
754 chain_hash: msg.chain_hash.clone(),
758 short_channel_ids: batch,
766 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
769 err: String::from("Not implemented"),
770 action: ErrorAction::IgnoreError,
774 fn provided_node_features(&self) -> NodeFeatures {
775 let mut features = NodeFeatures::empty();
776 features.set_gossip_queries_optional();
780 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
781 let mut features = InitFeatures::empty();
782 features.set_gossip_queries_optional();
786 fn processing_queue_high(&self) -> bool {
787 self.network_graph.pending_checks.too_many_checks_pending()
791 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> MessageSendEventsProvider for P2PGossipSync<G, U, L>
793 U::Target: UtxoLookup,
796 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
797 let mut ret = Vec::new();
798 let mut pending_events = self.pending_events.lock().unwrap();
799 core::mem::swap(&mut ret, &mut pending_events);
804 #[derive(Clone, Debug, PartialEq, Eq)]
805 /// Details about one direction of a channel as received within a [`ChannelUpdate`].
806 pub struct ChannelUpdateInfo {
807 /// When the last update to the channel direction was issued.
808 /// Value is opaque, as set in the announcement.
809 pub last_update: u32,
810 /// Whether the channel can be currently used for payments (in this one direction).
812 /// The difference in CLTV values that you must have when routing through this channel.
813 pub cltv_expiry_delta: u16,
814 /// The minimum value, which must be relayed to the next hop via the channel
815 pub htlc_minimum_msat: u64,
816 /// The maximum value which may be relayed to the next hop via the channel.
817 pub htlc_maximum_msat: u64,
818 /// Fees charged when the channel is used for routing
819 pub fees: RoutingFees,
820 /// Most recent update for the channel received from the network
821 /// Mostly redundant with the data we store in fields explicitly.
822 /// Everything else is useful only for sending out for initial routing sync.
823 /// Not stored if contains excess data to prevent DoS.
824 pub last_update_message: Option<ChannelUpdate>,
827 impl fmt::Display for ChannelUpdateInfo {
828 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
829 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)?;
834 impl Writeable for ChannelUpdateInfo {
835 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
836 write_tlv_fields!(writer, {
837 (0, self.last_update, required),
838 (2, self.enabled, required),
839 (4, self.cltv_expiry_delta, required),
840 (6, self.htlc_minimum_msat, required),
841 // Writing htlc_maximum_msat as an Option<u64> is required to maintain backwards
842 // compatibility with LDK versions prior to v0.0.110.
843 (8, Some(self.htlc_maximum_msat), required),
844 (10, self.fees, required),
845 (12, self.last_update_message, required),
851 impl Readable for ChannelUpdateInfo {
852 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
853 _init_tlv_field_var!(last_update, required);
854 _init_tlv_field_var!(enabled, required);
855 _init_tlv_field_var!(cltv_expiry_delta, required);
856 _init_tlv_field_var!(htlc_minimum_msat, required);
857 _init_tlv_field_var!(htlc_maximum_msat, option);
858 _init_tlv_field_var!(fees, required);
859 _init_tlv_field_var!(last_update_message, required);
861 read_tlv_fields!(reader, {
862 (0, last_update, required),
863 (2, enabled, required),
864 (4, cltv_expiry_delta, required),
865 (6, htlc_minimum_msat, required),
866 (8, htlc_maximum_msat, required),
867 (10, fees, required),
868 (12, last_update_message, required)
871 if let Some(htlc_maximum_msat) = htlc_maximum_msat {
872 Ok(ChannelUpdateInfo {
873 last_update: _init_tlv_based_struct_field!(last_update, required),
874 enabled: _init_tlv_based_struct_field!(enabled, required),
875 cltv_expiry_delta: _init_tlv_based_struct_field!(cltv_expiry_delta, required),
876 htlc_minimum_msat: _init_tlv_based_struct_field!(htlc_minimum_msat, required),
878 fees: _init_tlv_based_struct_field!(fees, required),
879 last_update_message: _init_tlv_based_struct_field!(last_update_message, required),
882 Err(DecodeError::InvalidValue)
887 #[derive(Clone, Debug, PartialEq, Eq)]
888 /// Details about a channel (both directions).
889 /// Received within a channel announcement.
890 pub struct ChannelInfo {
891 /// Protocol features of a channel communicated during its announcement
892 pub features: ChannelFeatures,
893 /// Source node of the first direction of a channel
894 pub node_one: NodeId,
895 /// Details about the first direction of a channel
896 pub one_to_two: Option<ChannelUpdateInfo>,
897 /// Source node of the second direction of a channel
898 pub node_two: NodeId,
899 /// Details about the second direction of a channel
900 pub two_to_one: Option<ChannelUpdateInfo>,
901 /// The channel capacity as seen on-chain, if chain lookup is available.
902 pub capacity_sats: Option<u64>,
903 /// An initial announcement of the channel
904 /// Mostly redundant with the data we store in fields explicitly.
905 /// Everything else is useful only for sending out for initial routing sync.
906 /// Not stored if contains excess data to prevent DoS.
907 pub announcement_message: Option<ChannelAnnouncement>,
908 /// The timestamp when we received the announcement, if we are running with feature = "std"
909 /// (which we can probably assume we are - no-std environments probably won't have a full
910 /// network graph in memory!).
911 announcement_received_time: u64,
915 /// Returns a [`DirectedChannelInfo`] for the channel directed to the given `target` from a
916 /// returned `source`, or `None` if `target` is not one of the channel's counterparties.
917 pub fn as_directed_to(&self, target: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
918 if self.one_to_two.is_none() || self.two_to_one.is_none() { return None; }
919 let (direction, source, outbound) = {
920 if target == &self.node_one {
921 (self.two_to_one.as_ref(), &self.node_two, false)
922 } else if target == &self.node_two {
923 (self.one_to_two.as_ref(), &self.node_one, true)
928 let dir = direction.expect("We checked that both directions are available at the start");
929 Some((DirectedChannelInfo::new(self, dir, outbound), source))
932 /// Returns a [`DirectedChannelInfo`] for the channel directed from the given `source` to a
933 /// returned `target`, or `None` if `source` is not one of the channel's counterparties.
934 pub fn as_directed_from(&self, source: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
935 if self.one_to_two.is_none() || self.two_to_one.is_none() { return None; }
936 let (direction, target, outbound) = {
937 if source == &self.node_one {
938 (self.one_to_two.as_ref(), &self.node_two, true)
939 } else if source == &self.node_two {
940 (self.two_to_one.as_ref(), &self.node_one, false)
945 let dir = direction.expect("We checked that both directions are available at the start");
946 Some((DirectedChannelInfo::new(self, dir, outbound), target))
949 /// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag.
950 pub fn get_directional_info(&self, channel_flags: u8) -> Option<&ChannelUpdateInfo> {
951 let direction = channel_flags & 1u8;
953 self.one_to_two.as_ref()
955 self.two_to_one.as_ref()
960 impl fmt::Display for ChannelInfo {
961 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
962 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
963 log_bytes!(self.features.encode()), &self.node_one, self.one_to_two, &self.node_two, self.two_to_one)?;
968 impl Writeable for ChannelInfo {
969 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
970 write_tlv_fields!(writer, {
971 (0, self.features, required),
972 (1, self.announcement_received_time, (default_value, 0)),
973 (2, self.node_one, required),
974 (4, self.one_to_two, required),
975 (6, self.node_two, required),
976 (8, self.two_to_one, required),
977 (10, self.capacity_sats, required),
978 (12, self.announcement_message, required),
984 // A wrapper allowing for the optional deseralization of ChannelUpdateInfo. Utilizing this is
985 // necessary to maintain backwards compatibility with previous serializations of `ChannelUpdateInfo`
986 // that may have no `htlc_maximum_msat` field set. In case the field is absent, we simply ignore
987 // the error and continue reading the `ChannelInfo`. Hopefully, we'll then eventually receive newer
988 // channel updates via the gossip network.
989 struct ChannelUpdateInfoDeserWrapper(Option<ChannelUpdateInfo>);
991 impl MaybeReadable for ChannelUpdateInfoDeserWrapper {
992 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
993 match crate::util::ser::Readable::read(reader) {
994 Ok(channel_update_option) => Ok(Some(Self(channel_update_option))),
995 Err(DecodeError::ShortRead) => Ok(None),
996 Err(DecodeError::InvalidValue) => Ok(None),
997 Err(err) => Err(err),
1002 impl Readable for ChannelInfo {
1003 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1004 _init_tlv_field_var!(features, required);
1005 _init_tlv_field_var!(announcement_received_time, (default_value, 0));
1006 _init_tlv_field_var!(node_one, required);
1007 let mut one_to_two_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
1008 _init_tlv_field_var!(node_two, required);
1009 let mut two_to_one_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
1010 _init_tlv_field_var!(capacity_sats, required);
1011 _init_tlv_field_var!(announcement_message, required);
1012 read_tlv_fields!(reader, {
1013 (0, features, required),
1014 (1, announcement_received_time, (default_value, 0)),
1015 (2, node_one, required),
1016 (4, one_to_two_wrap, upgradable_option),
1017 (6, node_two, required),
1018 (8, two_to_one_wrap, upgradable_option),
1019 (10, capacity_sats, required),
1020 (12, announcement_message, required),
1024 features: _init_tlv_based_struct_field!(features, required),
1025 node_one: _init_tlv_based_struct_field!(node_one, required),
1026 one_to_two: one_to_two_wrap.map(|w| w.0).unwrap_or(None),
1027 node_two: _init_tlv_based_struct_field!(node_two, required),
1028 two_to_one: two_to_one_wrap.map(|w| w.0).unwrap_or(None),
1029 capacity_sats: _init_tlv_based_struct_field!(capacity_sats, required),
1030 announcement_message: _init_tlv_based_struct_field!(announcement_message, required),
1031 announcement_received_time: _init_tlv_based_struct_field!(announcement_received_time, (default_value, 0)),
1036 /// A wrapper around [`ChannelInfo`] representing information about the channel as directed from a
1037 /// source node to a target node.
1039 pub struct DirectedChannelInfo<'a> {
1040 channel: &'a ChannelInfo,
1041 direction: &'a ChannelUpdateInfo,
1042 /// The direction this channel is in - if set, it indicates that we're traversing the channel
1043 /// from [`ChannelInfo::node_one`] to [`ChannelInfo::node_two`].
1044 from_node_one: bool,
1047 impl<'a> DirectedChannelInfo<'a> {
1049 fn new(channel: &'a ChannelInfo, direction: &'a ChannelUpdateInfo, from_node_one: bool) -> Self {
1050 Self { channel, direction, from_node_one }
1053 /// Returns information for the channel.
1055 pub fn channel(&self) -> &'a ChannelInfo { self.channel }
1057 /// Returns the [`EffectiveCapacity`] of the channel in the direction.
1059 /// This is either the total capacity from the funding transaction, if known, or the
1060 /// `htlc_maximum_msat` for the direction as advertised by the gossip network, if known,
1063 pub fn effective_capacity(&self) -> EffectiveCapacity {
1064 let mut htlc_maximum_msat = self.direction().htlc_maximum_msat;
1065 let capacity_msat = self.channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000);
1067 match capacity_msat {
1068 Some(capacity_msat) => {
1069 htlc_maximum_msat = cmp::min(htlc_maximum_msat, capacity_msat);
1070 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat }
1072 None => EffectiveCapacity::AdvertisedMaxHTLC { amount_msat: htlc_maximum_msat },
1076 /// Returns information for the direction.
1078 pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.direction }
1080 /// Returns the `node_id` of the source hop.
1082 /// Refers to the `node_id` forwarding the payment to the next hop.
1084 pub fn source(&self) -> &'a NodeId { if self.from_node_one { &self.channel.node_one } else { &self.channel.node_two } }
1086 /// Returns the `node_id` of the target hop.
1088 /// Refers to the `node_id` receiving the payment from the previous hop.
1090 pub fn target(&self) -> &'a NodeId { if self.from_node_one { &self.channel.node_two } else { &self.channel.node_one } }
1093 impl<'a> fmt::Debug for DirectedChannelInfo<'a> {
1094 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1095 f.debug_struct("DirectedChannelInfo")
1096 .field("channel", &self.channel)
1101 /// The effective capacity of a channel for routing purposes.
1103 /// While this may be smaller than the actual channel capacity, amounts greater than
1104 /// [`Self::as_msat`] should not be routed through the channel.
1105 #[derive(Clone, Copy, Debug, PartialEq)]
1106 pub enum EffectiveCapacity {
1107 /// The available liquidity in the channel known from being a channel counterparty, and thus a
1110 /// Either the inbound or outbound liquidity depending on the direction, denominated in
1112 liquidity_msat: u64,
1114 /// The maximum HTLC amount in one direction as advertised on the gossip network.
1116 /// The maximum HTLC amount denominated in millisatoshi.
1119 /// The total capacity of the channel as determined by the funding transaction.
1121 /// The funding amount denominated in millisatoshi.
1123 /// The maximum HTLC amount denominated in millisatoshi.
1124 htlc_maximum_msat: u64
1126 /// A capacity sufficient to route any payment, typically used for private channels provided by
1129 /// The maximum HTLC amount as provided by an invoice route hint.
1131 /// The maximum HTLC amount denominated in millisatoshi.
1134 /// A capacity that is unknown possibly because either the chain state is unavailable to know
1135 /// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
1139 /// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
1140 /// use when making routing decisions.
1141 pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
1143 impl EffectiveCapacity {
1144 /// Returns the effective capacity denominated in millisatoshi.
1145 pub fn as_msat(&self) -> u64 {
1147 EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
1148 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } => *amount_msat,
1149 EffectiveCapacity::Total { capacity_msat, .. } => *capacity_msat,
1150 EffectiveCapacity::HintMaxHTLC { amount_msat } => *amount_msat,
1151 EffectiveCapacity::Infinite => u64::max_value(),
1152 EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
1157 /// Fees for routing via a given channel or a node
1158 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash, Ord, PartialOrd)]
1159 pub struct RoutingFees {
1160 /// Flat routing fee in millisatoshis.
1162 /// Liquidity-based routing fee in millionths of a routed amount.
1163 /// In other words, 10000 is 1%.
1164 pub proportional_millionths: u32,
1167 impl_writeable_tlv_based!(RoutingFees, {
1168 (0, base_msat, required),
1169 (2, proportional_millionths, required)
1172 #[derive(Clone, Debug, PartialEq, Eq)]
1173 /// Non-relayable information received in the latest node_announcement from this node.
1174 pub struct NodeAnnouncementDetails {
1175 /// Protocol features the node announced support for
1176 pub features: NodeFeatures,
1178 /// When the last known update to the node state was issued.
1179 /// Value is opaque, as set in the announcement.
1180 pub last_update: u32,
1182 /// Color assigned to the node
1185 /// Moniker assigned to the node.
1186 /// May be invalid or malicious (eg control chars),
1187 /// should not be exposed to the user.
1188 pub alias: NodeAlias,
1190 /// Internet-level addresses via which one can connect to the node
1191 pub addresses: Vec<SocketAddress>,
1194 #[derive(Clone, Debug, PartialEq, Eq)]
1195 /// Information received in the latest node_announcement from this node.
1196 pub enum NodeAnnouncementInfo {
1197 /// An initial announcement of the node
1198 /// Everything else is useful only for sending out for initial routing sync.
1199 /// Not stored if contains excess data to prevent DoS.
1200 Relayed(NodeAnnouncement),
1202 /// Non-relayable information received in the latest node_announcement from this node.
1203 Local(NodeAnnouncementDetails),
1206 impl NodeAnnouncementInfo {
1208 /// Protocol features the node announced support for
1209 pub fn features(&self) -> &NodeFeatures {
1211 NodeAnnouncementInfo::Relayed(relayed) => {
1212 &relayed.contents.features
1214 NodeAnnouncementInfo::Local(local) => {
1220 /// When the last known update to the node state was issued.
1222 /// Value may or may not be a timestamp, depending on the policy of the origin node.
1223 pub fn last_update(&self) -> u32 {
1225 NodeAnnouncementInfo::Relayed(relayed) => {
1226 relayed.contents.timestamp
1228 NodeAnnouncementInfo::Local(local) => {
1234 /// Color assigned to the node
1235 pub fn rgb(&self) -> [u8; 3] {
1237 NodeAnnouncementInfo::Relayed(relayed) => {
1238 relayed.contents.rgb
1240 NodeAnnouncementInfo::Local(local) => {
1246 /// Moniker assigned to the node.
1248 /// May be invalid or malicious (eg control chars), should not be exposed to the user.
1249 pub fn alias(&self) -> &NodeAlias {
1251 NodeAnnouncementInfo::Relayed(relayed) => {
1252 &relayed.contents.alias
1254 NodeAnnouncementInfo::Local(local) => {
1260 /// Internet-level addresses via which one can connect to the node
1261 pub fn addresses(&self) -> &Vec<SocketAddress> {
1263 NodeAnnouncementInfo::Relayed(relayed) => {
1264 &relayed.contents.addresses
1266 NodeAnnouncementInfo::Local(local) => {
1272 /// An initial announcement of the node
1274 /// Not stored if contains excess data to prevent DoS.
1275 pub fn announcement_message(&self) -> Option<&NodeAnnouncement> {
1277 NodeAnnouncementInfo::Relayed(announcement) => {
1280 NodeAnnouncementInfo::Local(_) => {
1287 impl Writeable for NodeAnnouncementInfo {
1288 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1289 let features = self.features();
1290 let last_update = self.last_update();
1291 let rgb = self.rgb();
1292 let alias = self.alias();
1293 let addresses = self.addresses();
1294 let announcement_message = self.announcement_message();
1296 write_tlv_fields!(writer, {
1297 (0, features, required),
1298 (2, last_update, required),
1300 (6, alias, required),
1301 (8, announcement_message, option),
1302 (10, *addresses, required_vec), // Versions 0.0.115 through 0.0.123 only serialized an empty vec
1308 impl Readable for NodeAnnouncementInfo {
1309 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1310 _init_and_read_len_prefixed_tlv_fields!(reader, {
1311 (0, features, required),
1312 (2, last_update, required),
1314 (6, alias, required),
1315 (8, announcement_message, option),
1316 (10, addresses, required_vec),
1318 if let Some(announcement) = announcement_message {
1319 Ok(Self::Relayed(announcement))
1321 Ok(Self::Local(NodeAnnouncementDetails {
1322 features: features.0.unwrap(),
1323 last_update: last_update.0.unwrap(),
1324 rgb: rgb.0.unwrap(),
1325 alias: alias.0.unwrap(),
1332 /// A user-defined name for a node, which may be used when displaying the node in a graph.
1334 /// Since node aliases are provided by third parties, they are a potential avenue for injection
1335 /// attacks. Care must be taken when processing.
1336 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
1337 pub struct NodeAlias(pub [u8; 32]);
1339 impl fmt::Display for NodeAlias {
1340 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1341 let first_null = self.0.iter().position(|b| *b == 0).unwrap_or(self.0.len());
1342 let bytes = self.0.split_at(first_null).0;
1343 match core::str::from_utf8(bytes) {
1344 Ok(alias) => PrintableString(alias).fmt(f)?,
1346 use core::fmt::Write;
1347 for c in bytes.iter().map(|b| *b as char) {
1348 // Display printable ASCII characters
1349 let control_symbol = core::char::REPLACEMENT_CHARACTER;
1350 let c = if c >= '\x20' && c <= '\x7e' { c } else { control_symbol };
1359 impl Writeable for NodeAlias {
1360 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1365 impl Readable for NodeAlias {
1366 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
1367 Ok(NodeAlias(Readable::read(r)?))
1371 #[derive(Clone, Debug, PartialEq, Eq)]
1372 /// Details about a node in the network, known from the network announcement.
1373 pub struct NodeInfo {
1374 /// All valid channels a node has announced
1375 pub channels: Vec<u64>,
1376 /// More information about a node from node_announcement.
1377 /// Optional because we store a Node entry after learning about it from
1378 /// a channel announcement, but before receiving a node announcement.
1379 pub announcement_info: Option<NodeAnnouncementInfo>
1383 /// Returns whether the node has only announced Tor addresses.
1384 pub fn is_tor_only(&self) -> bool {
1385 self.announcement_info
1387 .map(|info| info.addresses())
1388 .and_then(|addresses| (!addresses.is_empty()).then(|| addresses))
1389 .map(|addresses| addresses.iter().all(|address| address.is_tor()))
1394 impl fmt::Display for NodeInfo {
1395 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1396 write!(f, " channels: {:?}, announcement_info: {:?}",
1397 &self.channels[..], self.announcement_info)?;
1402 impl Writeable for NodeInfo {
1403 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1404 write_tlv_fields!(writer, {
1405 // Note that older versions of LDK wrote the lowest inbound fees here at type 0
1406 (2, self.announcement_info, option),
1407 (4, self.channels, required_vec),
1413 // A wrapper allowing for the optional deserialization of `NodeAnnouncementInfo`. Utilizing this is
1414 // necessary to maintain compatibility with previous serializations of `SocketAddress` that have an
1415 // invalid hostname set. We ignore and eat all errors until we are either able to read a
1416 // `NodeAnnouncementInfo` or hit a `ShortRead`, i.e., read the TLV field to the end.
1417 struct NodeAnnouncementInfoDeserWrapper(NodeAnnouncementInfo);
1419 impl MaybeReadable for NodeAnnouncementInfoDeserWrapper {
1420 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
1421 match crate::util::ser::Readable::read(reader) {
1422 Ok(node_announcement_info) => return Ok(Some(Self(node_announcement_info))),
1424 copy(reader, &mut sink()).unwrap();
1431 impl Readable for NodeInfo {
1432 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1433 // Historically, we tracked the lowest inbound fees for any node in order to use it as an
1434 // A* heuristic when routing. Sadly, these days many, many nodes have at least one channel
1435 // with zero inbound fees, causing that heuristic to provide little gain. Worse, because it
1436 // requires additional complexity and lookups during routing, it ends up being a
1437 // performance loss. Thus, we simply ignore the old field here and no longer track it.
1438 _init_and_read_len_prefixed_tlv_fields!(reader, {
1439 (0, _lowest_inbound_channel_fees, option),
1440 (2, announcement_info_wrap, upgradable_option),
1441 (4, channels, required_vec),
1443 let _: Option<RoutingFees> = _lowest_inbound_channel_fees;
1444 let announcement_info_wrap: Option<NodeAnnouncementInfoDeserWrapper> = announcement_info_wrap;
1447 announcement_info: announcement_info_wrap.map(|w| w.0),
1453 const SERIALIZATION_VERSION: u8 = 1;
1454 const MIN_SERIALIZATION_VERSION: u8 = 1;
1456 impl<L: Deref> Writeable for NetworkGraph<L> where L::Target: Logger {
1457 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1458 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1460 self.chain_hash.write(writer)?;
1461 let channels = self.channels.read().unwrap();
1462 (channels.len() as u64).write(writer)?;
1463 for (ref chan_id, ref chan_info) in channels.unordered_iter() {
1464 (*chan_id).write(writer)?;
1465 chan_info.write(writer)?;
1467 let nodes = self.nodes.read().unwrap();
1468 (nodes.len() as u64).write(writer)?;
1469 for (ref node_id, ref node_info) in nodes.unordered_iter() {
1470 node_id.write(writer)?;
1471 node_info.write(writer)?;
1474 let last_rapid_gossip_sync_timestamp = self.get_last_rapid_gossip_sync_timestamp();
1475 write_tlv_fields!(writer, {
1476 (1, last_rapid_gossip_sync_timestamp, option),
1482 impl<L: Deref> ReadableArgs<L> for NetworkGraph<L> where L::Target: Logger {
1483 fn read<R: io::Read>(reader: &mut R, logger: L) -> Result<NetworkGraph<L>, DecodeError> {
1484 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1486 let chain_hash: ChainHash = Readable::read(reader)?;
1487 let channels_count: u64 = Readable::read(reader)?;
1488 // In Nov, 2023 there were about 15,000 nodes; we cap allocations to 1.5x that.
1489 let mut channels = IndexedMap::with_capacity(cmp::min(channels_count as usize, 22500));
1490 for _ in 0..channels_count {
1491 let chan_id: u64 = Readable::read(reader)?;
1492 let chan_info = Readable::read(reader)?;
1493 channels.insert(chan_id, chan_info);
1495 let nodes_count: u64 = Readable::read(reader)?;
1496 // In Nov, 2023 there were about 69K channels; we cap allocations to 1.5x that.
1497 let mut nodes = IndexedMap::with_capacity(cmp::min(nodes_count as usize, 103500));
1498 for _ in 0..nodes_count {
1499 let node_id = Readable::read(reader)?;
1500 let node_info = Readable::read(reader)?;
1501 nodes.insert(node_id, node_info);
1504 let mut last_rapid_gossip_sync_timestamp: Option<u32> = None;
1505 read_tlv_fields!(reader, {
1506 (1, last_rapid_gossip_sync_timestamp, option),
1510 secp_ctx: Secp256k1::verification_only(),
1513 channels: RwLock::new(channels),
1514 nodes: RwLock::new(nodes),
1515 last_rapid_gossip_sync_timestamp: Mutex::new(last_rapid_gossip_sync_timestamp),
1516 removed_nodes: Mutex::new(new_hash_map()),
1517 removed_channels: Mutex::new(new_hash_map()),
1518 pending_checks: utxo::PendingChecks::new(),
1523 impl<L: Deref> fmt::Display for NetworkGraph<L> where L::Target: Logger {
1524 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1525 writeln!(f, "Network map\n[Channels]")?;
1526 for (key, val) in self.channels.read().unwrap().unordered_iter() {
1527 writeln!(f, " {}: {}", key, val)?;
1529 writeln!(f, "[Nodes]")?;
1530 for (&node_id, val) in self.nodes.read().unwrap().unordered_iter() {
1531 writeln!(f, " {}: {}", &node_id, val)?;
1537 impl<L: Deref> Eq for NetworkGraph<L> where L::Target: Logger {}
1538 impl<L: Deref> PartialEq for NetworkGraph<L> where L::Target: Logger {
1539 fn eq(&self, other: &Self) -> bool {
1540 // For a total lockorder, sort by position in memory and take the inner locks in that order.
1541 // (Assumes that we can't move within memory while a lock is held).
1542 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1543 let a = if ord { (&self.channels, &self.nodes) } else { (&other.channels, &other.nodes) };
1544 let b = if ord { (&other.channels, &other.nodes) } else { (&self.channels, &self.nodes) };
1545 let (channels_a, channels_b) = (a.0.unsafe_well_ordered_double_lock_self(), b.0.unsafe_well_ordered_double_lock_self());
1546 let (nodes_a, nodes_b) = (a.1.unsafe_well_ordered_double_lock_self(), b.1.unsafe_well_ordered_double_lock_self());
1547 self.chain_hash.eq(&other.chain_hash) && channels_a.eq(&channels_b) && nodes_a.eq(&nodes_b)
1551 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
1552 /// Creates a new, empty, network graph.
1553 pub fn new(network: Network, logger: L) -> NetworkGraph<L> {
1555 secp_ctx: Secp256k1::verification_only(),
1556 chain_hash: ChainHash::using_genesis_block(network),
1558 channels: RwLock::new(IndexedMap::new()),
1559 nodes: RwLock::new(IndexedMap::new()),
1560 last_rapid_gossip_sync_timestamp: Mutex::new(None),
1561 removed_channels: Mutex::new(new_hash_map()),
1562 removed_nodes: Mutex::new(new_hash_map()),
1563 pending_checks: utxo::PendingChecks::new(),
1567 /// Returns a read-only view of the network graph.
1568 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
1569 let channels = self.channels.read().unwrap();
1570 let nodes = self.nodes.read().unwrap();
1571 ReadOnlyNetworkGraph {
1577 /// The unix timestamp provided by the most recent rapid gossip sync.
1578 /// It will be set by the rapid sync process after every sync completion.
1579 pub fn get_last_rapid_gossip_sync_timestamp(&self) -> Option<u32> {
1580 self.last_rapid_gossip_sync_timestamp.lock().unwrap().clone()
1583 /// Update the unix timestamp provided by the most recent rapid gossip sync.
1584 /// This should be done automatically by the rapid sync process after every sync completion.
1585 pub fn set_last_rapid_gossip_sync_timestamp(&self, last_rapid_gossip_sync_timestamp: u32) {
1586 self.last_rapid_gossip_sync_timestamp.lock().unwrap().replace(last_rapid_gossip_sync_timestamp);
1589 /// Clears the `NodeAnnouncementInfo` field for all nodes in the `NetworkGraph` for testing
1592 pub fn clear_nodes_announcement_info(&self) {
1593 for node in self.nodes.write().unwrap().unordered_iter_mut() {
1594 node.1.announcement_info = None;
1598 /// For an already known node (from channel announcements), update its stored properties from a
1599 /// given node announcement.
1601 /// You probably don't want to call this directly, instead relying on a P2PGossipSync's
1602 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1603 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1604 pub fn update_node_from_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), LightningError> {
1605 verify_node_announcement(msg, &self.secp_ctx)?;
1606 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1609 /// For an already known node (from channel announcements), update its stored properties from a
1610 /// given node announcement without verifying the associated signatures. Because we aren't
1611 /// given the associated signatures here we cannot relay the node announcement to any of our
1613 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1614 self.update_node_from_announcement_intern(msg, None)
1617 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1618 let mut nodes = self.nodes.write().unwrap();
1619 match nodes.get_mut(&msg.node_id) {
1621 core::mem::drop(nodes);
1622 self.pending_checks.check_hold_pending_node_announcement(msg, full_msg)?;
1623 Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError})
1626 if let Some(node_info) = node.announcement_info.as_ref() {
1627 // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
1628 // updates to ensure you always have the latest one, only vaguely suggesting
1629 // that it be at least the current time.
1630 if node_info.last_update() > msg.timestamp {
1631 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1632 } else if node_info.last_update() == msg.timestamp {
1633 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1638 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1639 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1640 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1642 node.announcement_info = if let (Some(signed_announcement), true) = (full_msg, should_relay) {
1643 Some(NodeAnnouncementInfo::Relayed(signed_announcement.clone()))
1645 Some(NodeAnnouncementInfo::Local(NodeAnnouncementDetails {
1646 features: msg.features.clone(),
1647 last_update: msg.timestamp,
1650 addresses: msg.addresses.clone(),
1659 /// Store or update channel info from a channel announcement.
1661 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1662 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1663 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1665 /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1666 /// the corresponding UTXO exists on chain and is correctly-formatted.
1667 pub fn update_channel_from_announcement<U: Deref>(
1668 &self, msg: &msgs::ChannelAnnouncement, utxo_lookup: &Option<U>,
1669 ) -> Result<(), LightningError>
1671 U::Target: UtxoLookup,
1673 verify_channel_announcement(msg, &self.secp_ctx)?;
1674 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), utxo_lookup)
1677 /// Store or update channel info from a channel announcement.
1679 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1680 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1681 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1683 /// This will skip verification of if the channel is actually on-chain.
1684 pub fn update_channel_from_announcement_no_lookup(
1685 &self, msg: &ChannelAnnouncement
1686 ) -> Result<(), LightningError> {
1687 self.update_channel_from_announcement::<&UtxoResolver>(msg, &None)
1690 /// Store or update channel info from a channel announcement without verifying the associated
1691 /// signatures. Because we aren't given the associated signatures here we cannot relay the
1692 /// channel announcement to any of our peers.
1694 /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1695 /// the corresponding UTXO exists on chain and is correctly-formatted.
1696 pub fn update_channel_from_unsigned_announcement<U: Deref>(
1697 &self, msg: &msgs::UnsignedChannelAnnouncement, utxo_lookup: &Option<U>
1698 ) -> Result<(), LightningError>
1700 U::Target: UtxoLookup,
1702 self.update_channel_from_unsigned_announcement_intern(msg, None, utxo_lookup)
1705 /// Update channel from partial announcement data received via rapid gossip sync
1707 /// `timestamp: u64`: Timestamp emulating the backdated original announcement receipt (by the
1708 /// rapid gossip sync server)
1710 /// All other parameters as used in [`msgs::UnsignedChannelAnnouncement`] fields.
1711 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> {
1712 if node_id_1 == node_id_2 {
1713 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1716 let node_1 = NodeId::from_pubkey(&node_id_1);
1717 let node_2 = NodeId::from_pubkey(&node_id_2);
1718 let channel_info = ChannelInfo {
1720 node_one: node_1.clone(),
1722 node_two: node_2.clone(),
1724 capacity_sats: None,
1725 announcement_message: None,
1726 announcement_received_time: timestamp,
1729 self.add_channel_between_nodes(short_channel_id, channel_info, None)
1732 fn add_channel_between_nodes(&self, short_channel_id: u64, channel_info: ChannelInfo, utxo_value: Option<Amount>) -> Result<(), LightningError> {
1733 let mut channels = self.channels.write().unwrap();
1734 let mut nodes = self.nodes.write().unwrap();
1736 let node_id_a = channel_info.node_one.clone();
1737 let node_id_b = channel_info.node_two.clone();
1739 log_gossip!(self.logger, "Adding channel {} between nodes {} and {}", short_channel_id, node_id_a, node_id_b);
1741 match channels.entry(short_channel_id) {
1742 IndexedMapEntry::Occupied(mut entry) => {
1743 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1744 //in the blockchain API, we need to handle it smartly here, though it's unclear
1746 if utxo_value.is_some() {
1747 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1748 // only sometimes returns results. In any case remove the previous entry. Note
1749 // that the spec expects us to "blacklist" the node_ids involved, but we can't
1751 // a) we don't *require* a UTXO provider that always returns results.
1752 // b) we don't track UTXOs of channels we know about and remove them if they
1754 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1755 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), short_channel_id);
1756 *entry.get_mut() = channel_info;
1758 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1761 IndexedMapEntry::Vacant(entry) => {
1762 entry.insert(channel_info);
1766 for current_node_id in [node_id_a, node_id_b].iter() {
1767 match nodes.entry(current_node_id.clone()) {
1768 IndexedMapEntry::Occupied(node_entry) => {
1769 node_entry.into_mut().channels.push(short_channel_id);
1771 IndexedMapEntry::Vacant(node_entry) => {
1772 node_entry.insert(NodeInfo {
1773 channels: vec!(short_channel_id),
1774 announcement_info: None,
1783 fn update_channel_from_unsigned_announcement_intern<U: Deref>(
1784 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, utxo_lookup: &Option<U>
1785 ) -> Result<(), LightningError>
1787 U::Target: UtxoLookup,
1789 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1790 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1793 if msg.chain_hash != self.chain_hash {
1794 return Err(LightningError {
1795 err: "Channel announcement chain hash does not match genesis hash".to_owned(),
1796 action: ErrorAction::IgnoreAndLog(Level::Debug),
1801 let channels = self.channels.read().unwrap();
1803 if let Some(chan) = channels.get(&msg.short_channel_id) {
1804 if chan.capacity_sats.is_some() {
1805 // If we'd previously looked up the channel on-chain and checked the script
1806 // against what appears on-chain, ignore the duplicate announcement.
1808 // Because a reorg could replace one channel with another at the same SCID, if
1809 // the channel appears to be different, we re-validate. This doesn't expose us
1810 // to any more DoS risk than not, as a peer can always flood us with
1811 // randomly-generated SCID values anyway.
1813 // We use the Node IDs rather than the bitcoin_keys to check for "equivalence"
1814 // as we didn't (necessarily) store the bitcoin keys, and we only really care
1815 // if the peers on the channel changed anyway.
1816 if msg.node_id_1 == chan.node_one && msg.node_id_2 == chan.node_two {
1817 return Err(LightningError {
1818 err: "Already have chain-validated channel".to_owned(),
1819 action: ErrorAction::IgnoreDuplicateGossip
1822 } else if utxo_lookup.is_none() {
1823 // Similarly, if we can't check the chain right now anyway, ignore the
1824 // duplicate announcement without bothering to take the channels write lock.
1825 return Err(LightningError {
1826 err: "Already have non-chain-validated channel".to_owned(),
1827 action: ErrorAction::IgnoreDuplicateGossip
1834 let removed_channels = self.removed_channels.lock().unwrap();
1835 let removed_nodes = self.removed_nodes.lock().unwrap();
1836 if removed_channels.contains_key(&msg.short_channel_id) ||
1837 removed_nodes.contains_key(&msg.node_id_1) ||
1838 removed_nodes.contains_key(&msg.node_id_2) {
1839 return Err(LightningError{
1840 err: format!("Channel with SCID {} or one of its nodes was removed from our network graph recently", &msg.short_channel_id),
1841 action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1845 let utxo_value = self.pending_checks.check_channel_announcement(
1846 utxo_lookup, msg, full_msg)?;
1848 #[allow(unused_mut, unused_assignments)]
1849 let mut announcement_received_time = 0;
1850 #[cfg(feature = "std")]
1852 announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1855 let chan_info = ChannelInfo {
1856 features: msg.features.clone(),
1857 node_one: msg.node_id_1,
1859 node_two: msg.node_id_2,
1861 capacity_sats: utxo_value.map(|a| a.to_sat()),
1862 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1863 { full_msg.cloned() } else { None },
1864 announcement_received_time,
1867 self.add_channel_between_nodes(msg.short_channel_id, chan_info, utxo_value)?;
1869 log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.short_channel_id, if !msg.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
1873 /// Marks a channel in the graph as failed permanently.
1875 /// The channel and any node for which this was their last channel are removed from the graph.
1876 pub fn channel_failed_permanent(&self, short_channel_id: u64) {
1877 #[cfg(feature = "std")]
1878 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1879 #[cfg(not(feature = "std"))]
1880 let current_time_unix = None;
1882 self.channel_failed_permanent_with_time(short_channel_id, current_time_unix)
1885 /// Marks a channel in the graph as failed permanently.
1887 /// The channel and any node for which this was their last channel are removed from the graph.
1888 fn channel_failed_permanent_with_time(&self, short_channel_id: u64, current_time_unix: Option<u64>) {
1889 let mut channels = self.channels.write().unwrap();
1890 if let Some(chan) = channels.remove(&short_channel_id) {
1891 let mut nodes = self.nodes.write().unwrap();
1892 self.removed_channels.lock().unwrap().insert(short_channel_id, current_time_unix);
1893 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1897 /// Marks a node in the graph as permanently failed, effectively removing it and its channels
1898 /// from local storage.
1899 pub fn node_failed_permanent(&self, node_id: &PublicKey) {
1900 #[cfg(feature = "std")]
1901 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1902 #[cfg(not(feature = "std"))]
1903 let current_time_unix = None;
1905 let node_id = NodeId::from_pubkey(node_id);
1906 let mut channels = self.channels.write().unwrap();
1907 let mut nodes = self.nodes.write().unwrap();
1908 let mut removed_channels = self.removed_channels.lock().unwrap();
1909 let mut removed_nodes = self.removed_nodes.lock().unwrap();
1911 if let Some(node) = nodes.remove(&node_id) {
1912 for scid in node.channels.iter() {
1913 if let Some(chan_info) = channels.remove(scid) {
1914 let other_node_id = if node_id == chan_info.node_one { chan_info.node_two } else { chan_info.node_one };
1915 if let IndexedMapEntry::Occupied(mut other_node_entry) = nodes.entry(other_node_id) {
1916 other_node_entry.get_mut().channels.retain(|chan_id| {
1919 if other_node_entry.get().channels.is_empty() {
1920 other_node_entry.remove_entry();
1923 removed_channels.insert(*scid, current_time_unix);
1926 removed_nodes.insert(node_id, current_time_unix);
1930 #[cfg(feature = "std")]
1931 /// Removes information about channels that we haven't heard any updates about in some time.
1932 /// This can be used regularly to prune the network graph of channels that likely no longer
1935 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1936 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1937 /// pruning occur for updates which are at least two weeks old, which we implement here.
1939 /// Note that for users of the `lightning-background-processor` crate this method may be
1940 /// automatically called regularly for you.
1942 /// This method will also cause us to stop tracking removed nodes and channels if they have been
1943 /// in the map for a while so that these can be resynced from gossip in the future.
1945 /// This method is only available with the `std` feature. See
1946 /// [`NetworkGraph::remove_stale_channels_and_tracking_with_time`] for `no-std` use.
1947 pub fn remove_stale_channels_and_tracking(&self) {
1948 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1949 self.remove_stale_channels_and_tracking_with_time(time);
1952 /// Removes information about channels that we haven't heard any updates about in some time.
1953 /// This can be used regularly to prune the network graph of channels that likely no longer
1956 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1957 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1958 /// pruning occur for updates which are at least two weeks old, which we implement here.
1960 /// This method will also cause us to stop tracking removed nodes and channels if they have been
1961 /// in the map for a while so that these can be resynced from gossip in the future.
1963 /// This function takes the current unix time as an argument. For users with the `std` feature
1964 /// enabled, [`NetworkGraph::remove_stale_channels_and_tracking`] may be preferable.
1965 pub fn remove_stale_channels_and_tracking_with_time(&self, current_time_unix: u64) {
1966 let mut channels = self.channels.write().unwrap();
1967 // Time out if we haven't received an update in at least 14 days.
1968 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1969 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1970 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1971 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1973 let mut scids_to_remove = Vec::new();
1974 for (scid, info) in channels.unordered_iter_mut() {
1975 if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1976 log_gossip!(self.logger, "Removing directional update one_to_two (0) for channel {} due to its timestamp {} being below {}",
1977 scid, info.one_to_two.as_ref().unwrap().last_update, min_time_unix);
1978 info.one_to_two = None;
1980 if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1981 log_gossip!(self.logger, "Removing directional update two_to_one (1) for channel {} due to its timestamp {} being below {}",
1982 scid, info.two_to_one.as_ref().unwrap().last_update, min_time_unix);
1983 info.two_to_one = None;
1985 if info.one_to_two.is_none() || info.two_to_one.is_none() {
1986 // We check the announcement_received_time here to ensure we don't drop
1987 // announcements that we just received and are just waiting for our peer to send a
1988 // channel_update for.
1989 let announcement_received_timestamp = info.announcement_received_time;
1990 if announcement_received_timestamp < min_time_unix as u64 {
1991 log_gossip!(self.logger, "Removing channel {} because both directional updates are missing and its announcement timestamp {} being below {}",
1992 scid, announcement_received_timestamp, min_time_unix);
1993 scids_to_remove.push(*scid);
1997 if !scids_to_remove.is_empty() {
1998 let mut nodes = self.nodes.write().unwrap();
1999 for scid in scids_to_remove {
2000 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
2001 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
2002 self.removed_channels.lock().unwrap().insert(scid, Some(current_time_unix));
2006 let should_keep_tracking = |time: &mut Option<u64>| {
2007 if let Some(time) = time {
2008 current_time_unix.saturating_sub(*time) < REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS
2010 // NOTE: In the case of no-std, we won't have access to the current UNIX time at the time of removal,
2011 // so we'll just set the removal time here to the current UNIX time on the very next invocation
2012 // of this function.
2013 #[cfg(not(feature = "std"))]
2015 let mut tracked_time = Some(current_time_unix);
2016 core::mem::swap(time, &mut tracked_time);
2019 #[allow(unreachable_code)]
2023 self.removed_channels.lock().unwrap().retain(|_, time| should_keep_tracking(time));
2024 self.removed_nodes.lock().unwrap().retain(|_, time| should_keep_tracking(time));
2027 /// For an already known (from announcement) channel, update info about one of the directions
2030 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
2031 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
2032 /// routing messages from a source using a protocol other than the lightning P2P protocol.
2034 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
2035 /// materially in the future will be rejected.
2036 pub fn update_channel(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
2037 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), false)
2040 /// For an already known (from announcement) channel, update info about one of the directions
2041 /// of the channel without verifying the associated signatures. Because we aren't given the
2042 /// associated signatures here we cannot relay the channel update to any of our peers.
2044 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
2045 /// materially in the future will be rejected.
2046 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
2047 self.update_channel_internal(msg, None, None, false)
2050 /// For an already known (from announcement) channel, verify the given [`ChannelUpdate`].
2052 /// This checks whether the update currently is applicable by [`Self::update_channel`].
2054 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
2055 /// materially in the future will be rejected.
2056 pub fn verify_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
2057 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), true)
2060 fn update_channel_internal(&self, msg: &msgs::UnsignedChannelUpdate,
2061 full_msg: Option<&msgs::ChannelUpdate>, sig: Option<&secp256k1::ecdsa::Signature>,
2062 only_verify: bool) -> Result<(), LightningError>
2064 let chan_enabled = msg.channel_flags & (1 << 1) != (1 << 1);
2066 if msg.chain_hash != self.chain_hash {
2067 return Err(LightningError {
2068 err: "Channel update chain hash does not match genesis hash".to_owned(),
2069 action: ErrorAction::IgnoreAndLog(Level::Debug),
2073 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
2075 // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
2076 // disable this check during tests!
2077 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2078 if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
2079 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
2081 if msg.timestamp as u64 > time + 60 * 60 * 24 {
2082 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
2088 "Updating channel {} in direction {} with timestamp {}",
2089 msg.short_channel_id,
2090 msg.channel_flags & 1,
2094 let mut channels = self.channels.write().unwrap();
2095 match channels.get_mut(&msg.short_channel_id) {
2097 core::mem::drop(channels);
2098 self.pending_checks.check_hold_pending_channel_update(msg, full_msg)?;
2099 return Err(LightningError {
2100 err: "Couldn't find channel for update".to_owned(),
2101 action: ErrorAction::IgnoreAndLog(Level::Gossip),
2105 if msg.htlc_maximum_msat > MAX_VALUE_MSAT {
2106 return Err(LightningError{err:
2107 "htlc_maximum_msat is larger than maximum possible msats".to_owned(),
2108 action: ErrorAction::IgnoreError});
2111 if let Some(capacity_sats) = channel.capacity_sats {
2112 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
2113 // Don't query UTXO set here to reduce DoS risks.
2114 if capacity_sats > MAX_VALUE_MSAT / 1000 || msg.htlc_maximum_msat > capacity_sats * 1000 {
2115 return Err(LightningError{err:
2116 "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(),
2117 action: ErrorAction::IgnoreError});
2120 macro_rules! check_update_latest {
2121 ($target: expr) => {
2122 if let Some(existing_chan_info) = $target.as_ref() {
2123 // The timestamp field is somewhat of a misnomer - the BOLTs use it to
2124 // order updates to ensure you always have the latest one, only
2125 // suggesting that it be at least the current time. For
2126 // channel_updates specifically, the BOLTs discuss the possibility of
2127 // pruning based on the timestamp field being more than two weeks old,
2128 // but only in the non-normative section.
2129 if existing_chan_info.last_update > msg.timestamp {
2130 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2131 } else if existing_chan_info.last_update == msg.timestamp {
2132 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2138 macro_rules! get_new_channel_info {
2140 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
2141 { full_msg.cloned() } else { None };
2143 let updated_channel_update_info = ChannelUpdateInfo {
2144 enabled: chan_enabled,
2145 last_update: msg.timestamp,
2146 cltv_expiry_delta: msg.cltv_expiry_delta,
2147 htlc_minimum_msat: msg.htlc_minimum_msat,
2148 htlc_maximum_msat: msg.htlc_maximum_msat,
2150 base_msat: msg.fee_base_msat,
2151 proportional_millionths: msg.fee_proportional_millionths,
2155 Some(updated_channel_update_info)
2159 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg)[..]);
2160 if msg.channel_flags & 1 == 1 {
2161 check_update_latest!(channel.two_to_one);
2162 if let Some(sig) = sig {
2163 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
2164 err: "Couldn't parse source node pubkey".to_owned(),
2165 action: ErrorAction::IgnoreAndLog(Level::Debug)
2166 })?, "channel_update");
2169 channel.two_to_one = get_new_channel_info!();
2172 check_update_latest!(channel.one_to_two);
2173 if let Some(sig) = sig {
2174 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
2175 err: "Couldn't parse destination node pubkey".to_owned(),
2176 action: ErrorAction::IgnoreAndLog(Level::Debug)
2177 })?, "channel_update");
2180 channel.one_to_two = get_new_channel_info!();
2189 fn remove_channel_in_nodes(nodes: &mut IndexedMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
2190 macro_rules! remove_from_node {
2191 ($node_id: expr) => {
2192 if let IndexedMapEntry::Occupied(mut entry) = nodes.entry($node_id) {
2193 entry.get_mut().channels.retain(|chan_id| {
2194 short_channel_id != *chan_id
2196 if entry.get().channels.is_empty() {
2197 entry.remove_entry();
2200 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
2205 remove_from_node!(chan.node_one);
2206 remove_from_node!(chan.node_two);
2210 impl ReadOnlyNetworkGraph<'_> {
2211 /// Returns all known valid channels' short ids along with announced channel info.
2213 /// This is not exported to bindings users because we don't want to return lifetime'd references
2214 pub fn channels(&self) -> &IndexedMap<u64, ChannelInfo> {
2218 /// Returns information on a channel with the given id.
2219 pub fn channel(&self, short_channel_id: u64) -> Option<&ChannelInfo> {
2220 self.channels.get(&short_channel_id)
2223 #[cfg(c_bindings)] // Non-bindings users should use `channels`
2224 /// Returns the list of channels in the graph
2225 pub fn list_channels(&self) -> Vec<u64> {
2226 self.channels.unordered_keys().map(|c| *c).collect()
2229 /// Returns all known nodes' public keys along with announced node info.
2231 /// This is not exported to bindings users because we don't want to return lifetime'd references
2232 pub fn nodes(&self) -> &IndexedMap<NodeId, NodeInfo> {
2236 /// Returns information on a node with the given id.
2237 pub fn node(&self, node_id: &NodeId) -> Option<&NodeInfo> {
2238 self.nodes.get(node_id)
2241 #[cfg(c_bindings)] // Non-bindings users should use `nodes`
2242 /// Returns the list of nodes in the graph
2243 pub fn list_nodes(&self) -> Vec<NodeId> {
2244 self.nodes.unordered_keys().map(|n| *n).collect()
2247 /// Get network addresses by node id.
2248 /// Returns None if the requested node is completely unknown,
2249 /// or if node announcement for the node was never received.
2250 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<SocketAddress>> {
2251 self.nodes.get(&NodeId::from_pubkey(&pubkey))
2252 .and_then(|node| node.announcement_info.as_ref().map(|ann| ann.addresses().to_vec()))
2257 pub(crate) mod tests {
2258 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
2259 use crate::ln::channelmanager;
2260 use crate::ln::chan_utils::make_funding_redeemscript;
2261 #[cfg(feature = "std")]
2262 use crate::ln::features::InitFeatures;
2263 use crate::ln::msgs::SocketAddress;
2264 use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, NodeAlias, MAX_EXCESS_BYTES_FOR_RELAY, NodeId, RoutingFees, ChannelUpdateInfo, ChannelInfo, NodeAnnouncementInfo, NodeInfo};
2265 use crate::routing::utxo::{UtxoLookupError, UtxoResult};
2266 use crate::ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
2267 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
2268 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
2269 use crate::util::config::UserConfig;
2270 use crate::util::test_utils;
2271 use crate::util::ser::{Hostname, ReadableArgs, Readable, Writeable};
2272 use crate::util::scid_utils::scid_from_parts;
2274 use crate::routing::gossip::REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS;
2275 use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
2277 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
2278 use bitcoin::hashes::Hash;
2279 use bitcoin::hashes::hex::FromHex;
2280 use bitcoin::network::Network;
2281 use bitcoin::amount::Amount;
2282 use bitcoin::blockdata::constants::ChainHash;
2283 use bitcoin::blockdata::script::ScriptBuf;
2284 use bitcoin::blockdata::transaction::TxOut;
2285 use bitcoin::secp256k1::{PublicKey, SecretKey};
2286 use bitcoin::secp256k1::{All, Secp256k1};
2289 use bitcoin::secp256k1;
2290 use crate::prelude::*;
2291 use crate::sync::Arc;
2293 fn create_network_graph() -> NetworkGraph<Arc<test_utils::TestLogger>> {
2294 let logger = Arc::new(test_utils::TestLogger::new());
2295 NetworkGraph::new(Network::Testnet, logger)
2298 fn create_gossip_sync(network_graph: &NetworkGraph<Arc<test_utils::TestLogger>>) -> (
2299 Secp256k1<All>, P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>,
2300 Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
2302 let secp_ctx = Secp256k1::new();
2303 let logger = Arc::new(test_utils::TestLogger::new());
2304 let gossip_sync = P2PGossipSync::new(network_graph, None, Arc::clone(&logger));
2305 (secp_ctx, gossip_sync)
2309 #[cfg(feature = "std")]
2310 fn request_full_sync_finite_times() {
2311 let network_graph = create_network_graph();
2312 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2313 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
2315 assert!(gossip_sync.should_request_full_sync(&node_id));
2316 assert!(gossip_sync.should_request_full_sync(&node_id));
2317 assert!(gossip_sync.should_request_full_sync(&node_id));
2318 assert!(gossip_sync.should_request_full_sync(&node_id));
2319 assert!(gossip_sync.should_request_full_sync(&node_id));
2320 assert!(!gossip_sync.should_request_full_sync(&node_id));
2323 pub(crate) fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
2324 let node_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_key));
2325 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2326 features: channelmanager::provided_node_features(&UserConfig::default()),
2330 alias: NodeAlias([0; 32]),
2331 addresses: Vec::new(),
2332 excess_address_data: Vec::new(),
2333 excess_data: Vec::new(),
2335 f(&mut unsigned_announcement);
2336 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2338 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2339 contents: unsigned_announcement
2343 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 {
2344 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
2345 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
2346 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2347 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2349 let mut unsigned_announcement = UnsignedChannelAnnouncement {
2350 features: channelmanager::provided_channel_features(&UserConfig::default()),
2351 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2352 short_channel_id: 0,
2353 node_id_1: NodeId::from_pubkey(&node_id_1),
2354 node_id_2: NodeId::from_pubkey(&node_id_2),
2355 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey)),
2356 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey)),
2357 excess_data: Vec::new(),
2359 f(&mut unsigned_announcement);
2360 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2361 ChannelAnnouncement {
2362 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_key),
2363 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_key),
2364 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_btckey),
2365 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_btckey),
2366 contents: unsigned_announcement,
2370 pub(crate) fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> ScriptBuf {
2371 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
2372 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
2373 make_funding_redeemscript(&PublicKey::from_secret_key(secp_ctx, &node_1_btckey),
2374 &PublicKey::from_secret_key(secp_ctx, &node_2_btckey)).to_p2wsh()
2377 pub(crate) fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
2378 let mut unsigned_channel_update = UnsignedChannelUpdate {
2379 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2380 short_channel_id: 0,
2382 message_flags: 1, // Only must_be_one
2384 cltv_expiry_delta: 144,
2385 htlc_minimum_msat: 1_000_000,
2386 htlc_maximum_msat: 1_000_000,
2387 fee_base_msat: 10_000,
2388 fee_proportional_millionths: 20,
2389 excess_data: Vec::new()
2391 f(&mut unsigned_channel_update);
2392 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2394 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2395 contents: unsigned_channel_update
2400 fn handling_node_announcements() {
2401 let network_graph = create_network_graph();
2402 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2404 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2405 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2406 let zero_hash = Sha256dHash::hash(&[0; 32]);
2408 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2409 match gossip_sync.handle_node_announcement(&valid_announcement) {
2411 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
2415 // Announce a channel to add a corresponding node.
2416 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2417 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2418 Ok(res) => assert!(res),
2423 match gossip_sync.handle_node_announcement(&valid_announcement) {
2424 Ok(res) => assert!(res),
2428 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2429 match gossip_sync.handle_node_announcement(
2431 signature: secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey),
2432 contents: valid_announcement.contents.clone()
2435 Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
2438 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
2439 unsigned_announcement.timestamp += 1000;
2440 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2441 }, node_1_privkey, &secp_ctx);
2442 // Return false because contains excess data.
2443 match gossip_sync.handle_node_announcement(&announcement_with_data) {
2444 Ok(res) => assert!(!res),
2448 // Even though previous announcement was not relayed further, we still accepted it,
2449 // so we now won't accept announcements before the previous one.
2450 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
2451 unsigned_announcement.timestamp += 1000 - 10;
2452 }, node_1_privkey, &secp_ctx);
2453 match gossip_sync.handle_node_announcement(&outdated_announcement) {
2455 Err(e) => assert_eq!(e.err, "Update older than last processed update")
2460 fn handling_channel_announcements() {
2461 let secp_ctx = Secp256k1::new();
2462 let logger = test_utils::TestLogger::new();
2464 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2465 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2467 let good_script = get_channel_script(&secp_ctx);
2468 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2470 // Test if the UTXO lookups were not supported
2471 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2472 let mut gossip_sync = P2PGossipSync::new(&network_graph, None, &logger);
2473 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2474 Ok(res) => assert!(res),
2479 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2485 // If we receive announcement for the same channel (with UTXO lookups disabled),
2486 // drop new one on the floor, since we can't see any changes.
2487 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2489 Err(e) => assert_eq!(e.err, "Already have non-chain-validated channel")
2492 // Test if an associated transaction were not on-chain (or not confirmed).
2493 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2494 *chain_source.utxo_ret.lock().unwrap() = UtxoResult::Sync(Err(UtxoLookupError::UnknownTx));
2495 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2496 gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2498 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2499 unsigned_announcement.short_channel_id += 1;
2500 }, node_1_privkey, node_2_privkey, &secp_ctx);
2501 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2503 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2506 // Now test if the transaction is found in the UTXO set and the script is correct.
2507 *chain_source.utxo_ret.lock().unwrap() =
2508 UtxoResult::Sync(Ok(TxOut { value: Amount::ZERO, script_pubkey: good_script.clone() }));
2509 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2510 unsigned_announcement.short_channel_id += 2;
2511 }, node_1_privkey, node_2_privkey, &secp_ctx);
2512 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2513 Ok(res) => assert!(res),
2518 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2524 // If we receive announcement for the same channel, once we've validated it against the
2525 // chain, we simply ignore all new (duplicate) announcements.
2526 *chain_source.utxo_ret.lock().unwrap() =
2527 UtxoResult::Sync(Ok(TxOut { value: Amount::ZERO, script_pubkey: good_script }));
2528 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2530 Err(e) => assert_eq!(e.err, "Already have chain-validated channel")
2533 #[cfg(feature = "std")]
2535 use std::time::{SystemTime, UNIX_EPOCH};
2537 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2538 // Mark a node as permanently failed so it's tracked as removed.
2539 gossip_sync.network_graph().node_failed_permanent(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2541 // Return error and ignore valid channel announcement if one of the nodes has been tracked as removed.
2542 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2543 unsigned_announcement.short_channel_id += 3;
2544 }, node_1_privkey, node_2_privkey, &secp_ctx);
2545 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2547 Err(e) => assert_eq!(e.err, "Channel with SCID 3 or one of its nodes was removed from our network graph recently")
2550 gossip_sync.network_graph().remove_stale_channels_and_tracking_with_time(tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2552 // The above channel announcement should be handled as per normal now.
2553 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2554 Ok(res) => assert!(res),
2559 // Don't relay valid channels with excess data
2560 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2561 unsigned_announcement.short_channel_id += 4;
2562 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2563 }, node_1_privkey, node_2_privkey, &secp_ctx);
2564 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2565 Ok(res) => assert!(!res),
2569 let mut invalid_sig_announcement = valid_announcement.clone();
2570 invalid_sig_announcement.contents.excess_data = Vec::new();
2571 match gossip_sync.handle_channel_announcement(&invalid_sig_announcement) {
2573 Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
2576 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
2577 match gossip_sync.handle_channel_announcement(&channel_to_itself_announcement) {
2579 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2582 // Test that channel announcements with the wrong chain hash are ignored (network graph is testnet,
2583 // announcement is mainnet).
2584 let incorrect_chain_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2585 unsigned_announcement.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2586 }, node_1_privkey, node_2_privkey, &secp_ctx);
2587 match gossip_sync.handle_channel_announcement(&incorrect_chain_announcement) {
2589 Err(e) => assert_eq!(e.err, "Channel announcement chain hash does not match genesis hash")
2594 fn handling_channel_update() {
2595 let secp_ctx = Secp256k1::new();
2596 let logger = test_utils::TestLogger::new();
2597 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2598 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2599 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2601 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2602 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2604 let amount_sats = Amount::from_sat(1000_000);
2605 let short_channel_id;
2608 // Announce a channel we will update
2609 let good_script = get_channel_script(&secp_ctx);
2610 *chain_source.utxo_ret.lock().unwrap() =
2611 UtxoResult::Sync(Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() }));
2613 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2614 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2615 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2622 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2623 network_graph.verify_channel_update(&valid_channel_update).unwrap();
2624 match gossip_sync.handle_channel_update(&valid_channel_update) {
2625 Ok(res) => assert!(res),
2630 match network_graph.read_only().channels().get(&short_channel_id) {
2632 Some(channel_info) => {
2633 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
2634 assert!(channel_info.two_to_one.is_none());
2639 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2640 unsigned_channel_update.timestamp += 100;
2641 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2642 }, node_1_privkey, &secp_ctx);
2643 // Return false because contains excess data
2644 match gossip_sync.handle_channel_update(&valid_channel_update) {
2645 Ok(res) => assert!(!res),
2649 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2650 unsigned_channel_update.timestamp += 110;
2651 unsigned_channel_update.short_channel_id += 1;
2652 }, node_1_privkey, &secp_ctx);
2653 match gossip_sync.handle_channel_update(&valid_channel_update) {
2655 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2658 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2659 unsigned_channel_update.htlc_maximum_msat = MAX_VALUE_MSAT + 1;
2660 unsigned_channel_update.timestamp += 110;
2661 }, node_1_privkey, &secp_ctx);
2662 match gossip_sync.handle_channel_update(&valid_channel_update) {
2664 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
2667 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2668 unsigned_channel_update.htlc_maximum_msat = amount_sats.to_sat() * 1000 + 1;
2669 unsigned_channel_update.timestamp += 110;
2670 }, node_1_privkey, &secp_ctx);
2671 match gossip_sync.handle_channel_update(&valid_channel_update) {
2673 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
2676 // Even though previous update was not relayed further, we still accepted it,
2677 // so we now won't accept update before the previous one.
2678 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2679 unsigned_channel_update.timestamp += 100;
2680 }, node_1_privkey, &secp_ctx);
2681 match gossip_sync.handle_channel_update(&valid_channel_update) {
2683 Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
2686 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2687 unsigned_channel_update.timestamp += 500;
2688 }, node_1_privkey, &secp_ctx);
2689 let zero_hash = Sha256dHash::hash(&[0; 32]);
2690 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2691 invalid_sig_channel_update.signature = secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey);
2692 match gossip_sync.handle_channel_update(&invalid_sig_channel_update) {
2694 Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
2697 // Test that channel updates with the wrong chain hash are ignored (network graph is testnet, channel
2698 // update is mainet).
2699 let incorrect_chain_update = get_signed_channel_update(|unsigned_channel_update| {
2700 unsigned_channel_update.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2701 }, node_1_privkey, &secp_ctx);
2703 match gossip_sync.handle_channel_update(&incorrect_chain_update) {
2705 Err(e) => assert_eq!(e.err, "Channel update chain hash does not match genesis hash")
2710 fn handling_network_update() {
2711 let logger = test_utils::TestLogger::new();
2712 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2713 let secp_ctx = Secp256k1::new();
2715 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2716 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2717 let node_2_id = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2720 // There is no nodes in the table at the beginning.
2721 assert_eq!(network_graph.read_only().nodes().len(), 0);
2724 let short_channel_id;
2726 // Check that we can manually apply a channel update.
2727 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2728 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2729 let chain_source: Option<&test_utils::TestChainSource> = None;
2730 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2731 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2733 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2735 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2736 network_graph.update_channel(&valid_channel_update).unwrap();
2737 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2740 // Non-permanent failure doesn't touch the channel at all
2742 match network_graph.read_only().channels().get(&short_channel_id) {
2744 Some(channel_info) => {
2745 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2749 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2751 is_permanent: false,
2754 match network_graph.read_only().channels().get(&short_channel_id) {
2756 Some(channel_info) => {
2757 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2762 // Permanent closing deletes a channel
2763 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2768 assert_eq!(network_graph.read_only().channels().len(), 0);
2769 // Nodes are also deleted because there are no associated channels anymore
2770 assert_eq!(network_graph.read_only().nodes().len(), 0);
2773 // Get a new network graph since we don't want to track removed nodes in this test with "std"
2774 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2776 // Announce a channel to test permanent node failure
2777 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2778 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2779 let chain_source: Option<&test_utils::TestChainSource> = None;
2780 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2781 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2783 // Non-permanent node failure does not delete any nodes or channels
2784 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2786 is_permanent: false,
2789 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2790 assert!(network_graph.read_only().nodes().get(&NodeId::from_pubkey(&node_2_id)).is_some());
2792 // Permanent node failure deletes node and its channels
2793 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2798 assert_eq!(network_graph.read_only().nodes().len(), 0);
2799 // Channels are also deleted because the associated node has been deleted
2800 assert_eq!(network_graph.read_only().channels().len(), 0);
2805 fn test_channel_timeouts() {
2806 // Test the removal of channels with `remove_stale_channels_and_tracking`.
2807 let logger = test_utils::TestLogger::new();
2808 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2809 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2810 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2811 let secp_ctx = Secp256k1::new();
2813 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2814 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2816 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2817 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2818 let chain_source: Option<&test_utils::TestChainSource> = None;
2819 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2820 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2822 // Submit two channel updates for each channel direction (update.flags bit).
2823 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2824 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2825 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2827 let valid_channel_update_2 = get_signed_channel_update(|update| {update.channel_flags |=1;}, node_2_privkey, &secp_ctx);
2828 gossip_sync.handle_channel_update(&valid_channel_update_2).unwrap();
2829 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().two_to_one.is_some());
2831 network_graph.remove_stale_channels_and_tracking_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2832 assert_eq!(network_graph.read_only().channels().len(), 1);
2833 assert_eq!(network_graph.read_only().nodes().len(), 2);
2835 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2836 #[cfg(not(feature = "std"))] {
2837 // Make sure removed channels are tracked.
2838 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2840 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2841 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2843 #[cfg(feature = "std")]
2845 // In std mode, a further check is performed before fully removing the channel -
2846 // the channel_announcement must have been received at least two weeks ago. We
2847 // fudge that here by indicating the time has jumped two weeks.
2848 assert_eq!(network_graph.read_only().channels().len(), 1);
2849 assert_eq!(network_graph.read_only().nodes().len(), 2);
2851 // Note that the directional channel information will have been removed already..
2852 // We want to check that this will work even if *one* of the channel updates is recent,
2853 // so we should add it with a recent timestamp.
2854 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2855 use std::time::{SystemTime, UNIX_EPOCH};
2856 let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2857 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2858 unsigned_channel_update.timestamp = (announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
2859 }, node_1_privkey, &secp_ctx);
2860 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2861 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2862 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2863 // Make sure removed channels are tracked.
2864 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2865 // Provide a later time so that sufficient time has passed
2866 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2867 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2870 assert_eq!(network_graph.read_only().channels().len(), 0);
2871 assert_eq!(network_graph.read_only().nodes().len(), 0);
2872 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2874 #[cfg(feature = "std")]
2876 use std::time::{SystemTime, UNIX_EPOCH};
2878 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2880 // Clear tracked nodes and channels for clean slate
2881 network_graph.removed_channels.lock().unwrap().clear();
2882 network_graph.removed_nodes.lock().unwrap().clear();
2884 // Add a channel and nodes from channel announcement. So our network graph will
2885 // now only consist of two nodes and one channel between them.
2886 assert!(network_graph.update_channel_from_announcement(
2887 &valid_channel_announcement, &chain_source).is_ok());
2889 // Mark the channel as permanently failed. This will also remove the two nodes
2890 // and all of the entries will be tracked as removed.
2891 network_graph.channel_failed_permanent_with_time(short_channel_id, Some(tracking_time));
2893 // Should not remove from tracking if insufficient time has passed
2894 network_graph.remove_stale_channels_and_tracking_with_time(
2895 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS - 1);
2896 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1, "Removed channel count ≠1 with tracking_time {}", tracking_time);
2898 // Provide a later time so that sufficient time has passed
2899 network_graph.remove_stale_channels_and_tracking_with_time(
2900 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2901 assert!(network_graph.removed_channels.lock().unwrap().is_empty(), "Unexpectedly removed channels with tracking_time {}", tracking_time);
2902 assert!(network_graph.removed_nodes.lock().unwrap().is_empty(), "Unexpectedly removed nodes with tracking_time {}", tracking_time);
2905 #[cfg(not(feature = "std"))]
2907 // When we don't have access to the system clock, the time we started tracking removal will only
2908 // be that provided by the first call to `remove_stale_channels_and_tracking_with_time`. Hence,
2909 // only if sufficient time has passed after that first call, will the next call remove it from
2911 let removal_time = 1664619654;
2913 // Clear removed nodes and channels for clean slate
2914 network_graph.removed_channels.lock().unwrap().clear();
2915 network_graph.removed_nodes.lock().unwrap().clear();
2917 // Add a channel and nodes from channel announcement. So our network graph will
2918 // now only consist of two nodes and one channel between them.
2919 assert!(network_graph.update_channel_from_announcement(
2920 &valid_channel_announcement, &chain_source).is_ok());
2922 // Mark the channel as permanently failed. This will also remove the two nodes
2923 // and all of the entries will be tracked as removed.
2924 network_graph.channel_failed_permanent(short_channel_id);
2926 // The first time we call the following, the channel will have a removal time assigned.
2927 network_graph.remove_stale_channels_and_tracking_with_time(removal_time);
2928 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2930 // Provide a later time so that sufficient time has passed
2931 network_graph.remove_stale_channels_and_tracking_with_time(
2932 removal_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2933 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2934 assert!(network_graph.removed_nodes.lock().unwrap().is_empty());
2939 fn getting_next_channel_announcements() {
2940 let network_graph = create_network_graph();
2941 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2942 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2943 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2945 // Channels were not announced yet.
2946 let channels_with_announcements = gossip_sync.get_next_channel_announcement(0);
2947 assert!(channels_with_announcements.is_none());
2949 let short_channel_id;
2951 // Announce a channel we will update
2952 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2953 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2954 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2960 // Contains initial channel announcement now.
2961 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2962 if let Some(channel_announcements) = channels_with_announcements {
2963 let (_, ref update_1, ref update_2) = channel_announcements;
2964 assert_eq!(update_1, &None);
2965 assert_eq!(update_2, &None);
2971 // Valid channel update
2972 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2973 unsigned_channel_update.timestamp = 101;
2974 }, node_1_privkey, &secp_ctx);
2975 match gossip_sync.handle_channel_update(&valid_channel_update) {
2981 // Now contains an initial announcement and an update.
2982 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2983 if let Some(channel_announcements) = channels_with_announcements {
2984 let (_, ref update_1, ref update_2) = channel_announcements;
2985 assert_ne!(update_1, &None);
2986 assert_eq!(update_2, &None);
2992 // Channel update with excess data.
2993 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2994 unsigned_channel_update.timestamp = 102;
2995 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2996 }, node_1_privkey, &secp_ctx);
2997 match gossip_sync.handle_channel_update(&valid_channel_update) {
3003 // Test that announcements with excess data won't be returned
3004 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
3005 if let Some(channel_announcements) = channels_with_announcements {
3006 let (_, ref update_1, ref update_2) = channel_announcements;
3007 assert_eq!(update_1, &None);
3008 assert_eq!(update_2, &None);
3013 // Further starting point have no channels after it
3014 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id + 1000);
3015 assert!(channels_with_announcements.is_none());
3019 fn getting_next_node_announcements() {
3020 let network_graph = create_network_graph();
3021 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3022 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3023 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3024 let node_id_1 = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
3027 let next_announcements = gossip_sync.get_next_node_announcement(None);
3028 assert!(next_announcements.is_none());
3031 // Announce a channel to add 2 nodes
3032 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3033 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
3039 // Nodes were never announced
3040 let next_announcements = gossip_sync.get_next_node_announcement(None);
3041 assert!(next_announcements.is_none());
3044 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3045 match gossip_sync.handle_node_announcement(&valid_announcement) {
3050 let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
3051 match gossip_sync.handle_node_announcement(&valid_announcement) {
3057 let next_announcements = gossip_sync.get_next_node_announcement(None);
3058 assert!(next_announcements.is_some());
3060 // Skip the first node.
3061 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3062 assert!(next_announcements.is_some());
3065 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
3066 let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
3067 unsigned_announcement.timestamp += 10;
3068 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
3069 }, node_2_privkey, &secp_ctx);
3070 match gossip_sync.handle_node_announcement(&valid_announcement) {
3071 Ok(res) => assert!(!res),
3076 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3077 assert!(next_announcements.is_none());
3081 fn network_graph_serialization() {
3082 let network_graph = create_network_graph();
3083 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3085 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3086 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3088 // Announce a channel to add a corresponding node.
3089 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3090 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3091 Ok(res) => assert!(res),
3095 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3096 match gossip_sync.handle_node_announcement(&valid_announcement) {
3101 let mut w = test_utils::TestVecWriter(Vec::new());
3102 assert!(!network_graph.read_only().nodes().is_empty());
3103 assert!(!network_graph.read_only().channels().is_empty());
3104 network_graph.write(&mut w).unwrap();
3106 let logger = Arc::new(test_utils::TestLogger::new());
3107 assert!(<NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), logger).unwrap() == network_graph);
3111 fn network_graph_tlv_serialization() {
3112 let network_graph = create_network_graph();
3113 network_graph.set_last_rapid_gossip_sync_timestamp(42);
3115 let mut w = test_utils::TestVecWriter(Vec::new());
3116 network_graph.write(&mut w).unwrap();
3118 let logger = Arc::new(test_utils::TestLogger::new());
3119 let reassembled_network_graph: NetworkGraph<_> = ReadableArgs::read(&mut io::Cursor::new(&w.0), logger).unwrap();
3120 assert!(reassembled_network_graph == network_graph);
3121 assert_eq!(reassembled_network_graph.get_last_rapid_gossip_sync_timestamp().unwrap(), 42);
3125 #[cfg(feature = "std")]
3126 fn calling_sync_routing_table() {
3127 use std::time::{SystemTime, UNIX_EPOCH};
3128 use crate::ln::msgs::Init;
3130 let network_graph = create_network_graph();
3131 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3132 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
3133 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
3135 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3137 // It should ignore if gossip_queries feature is not enabled
3139 let init_msg = Init { features: InitFeatures::empty(), networks: None, remote_network_address: None };
3140 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3141 let events = gossip_sync.get_and_clear_pending_msg_events();
3142 assert_eq!(events.len(), 0);
3145 // It should send a gossip_timestamp_filter with the correct information
3147 let mut features = InitFeatures::empty();
3148 features.set_gossip_queries_optional();
3149 let init_msg = Init { features, networks: None, remote_network_address: None };
3150 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3151 let events = gossip_sync.get_and_clear_pending_msg_events();
3152 assert_eq!(events.len(), 1);
3154 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
3155 assert_eq!(node_id, &node_id_1);
3156 assert_eq!(msg.chain_hash, chain_hash);
3157 let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
3158 assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
3159 assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
3160 assert_eq!(msg.timestamp_range, u32::max_value());
3162 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
3168 fn handling_query_channel_range() {
3169 let network_graph = create_network_graph();
3170 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3172 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3173 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3174 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3175 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
3177 let mut scids: Vec<u64> = vec![
3178 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
3179 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
3182 // used for testing multipart reply across blocks
3183 for block in 100000..=108001 {
3184 scids.push(scid_from_parts(block, 0, 0).unwrap());
3187 // used for testing resumption on same block
3188 scids.push(scid_from_parts(108001, 1, 0).unwrap());
3191 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
3192 unsigned_announcement.short_channel_id = scid;
3193 }, node_1_privkey, node_2_privkey, &secp_ctx);
3194 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3200 // Error when number_of_blocks=0
3201 do_handling_query_channel_range(
3205 chain_hash: chain_hash.clone(),
3207 number_of_blocks: 0,
3210 vec![ReplyChannelRange {
3211 chain_hash: chain_hash.clone(),
3213 number_of_blocks: 0,
3214 sync_complete: true,
3215 short_channel_ids: vec![]
3219 // Error when wrong chain
3220 do_handling_query_channel_range(
3224 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3226 number_of_blocks: 0xffff_ffff,
3229 vec![ReplyChannelRange {
3230 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3232 number_of_blocks: 0xffff_ffff,
3233 sync_complete: true,
3234 short_channel_ids: vec![],
3238 // Error when first_blocknum > 0xffffff
3239 do_handling_query_channel_range(
3243 chain_hash: chain_hash.clone(),
3244 first_blocknum: 0x01000000,
3245 number_of_blocks: 0xffff_ffff,
3248 vec![ReplyChannelRange {
3249 chain_hash: chain_hash.clone(),
3250 first_blocknum: 0x01000000,
3251 number_of_blocks: 0xffff_ffff,
3252 sync_complete: true,
3253 short_channel_ids: vec![]
3257 // Empty reply when max valid SCID block num
3258 do_handling_query_channel_range(
3262 chain_hash: chain_hash.clone(),
3263 first_blocknum: 0xffffff,
3264 number_of_blocks: 1,
3269 chain_hash: chain_hash.clone(),
3270 first_blocknum: 0xffffff,
3271 number_of_blocks: 1,
3272 sync_complete: true,
3273 short_channel_ids: vec![]
3278 // No results in valid query range
3279 do_handling_query_channel_range(
3283 chain_hash: chain_hash.clone(),
3284 first_blocknum: 1000,
3285 number_of_blocks: 1000,
3290 chain_hash: chain_hash.clone(),
3291 first_blocknum: 1000,
3292 number_of_blocks: 1000,
3293 sync_complete: true,
3294 short_channel_ids: vec![],
3299 // Overflow first_blocknum + number_of_blocks
3300 do_handling_query_channel_range(
3304 chain_hash: chain_hash.clone(),
3305 first_blocknum: 0xfe0000,
3306 number_of_blocks: 0xffffffff,
3311 chain_hash: chain_hash.clone(),
3312 first_blocknum: 0xfe0000,
3313 number_of_blocks: 0xffffffff - 0xfe0000,
3314 sync_complete: true,
3315 short_channel_ids: vec![
3316 0xfffffe_ffffff_ffff, // max
3322 // Single block exactly full
3323 do_handling_query_channel_range(
3327 chain_hash: chain_hash.clone(),
3328 first_blocknum: 100000,
3329 number_of_blocks: 8000,
3334 chain_hash: chain_hash.clone(),
3335 first_blocknum: 100000,
3336 number_of_blocks: 8000,
3337 sync_complete: true,
3338 short_channel_ids: (100000..=107999)
3339 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3345 // Multiple split on new block
3346 do_handling_query_channel_range(
3350 chain_hash: chain_hash.clone(),
3351 first_blocknum: 100000,
3352 number_of_blocks: 8001,
3357 chain_hash: chain_hash.clone(),
3358 first_blocknum: 100000,
3359 number_of_blocks: 7999,
3360 sync_complete: false,
3361 short_channel_ids: (100000..=107999)
3362 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3366 chain_hash: chain_hash.clone(),
3367 first_blocknum: 107999,
3368 number_of_blocks: 2,
3369 sync_complete: true,
3370 short_channel_ids: vec![
3371 scid_from_parts(108000, 0, 0).unwrap(),
3377 // Multiple split on same block
3378 do_handling_query_channel_range(
3382 chain_hash: chain_hash.clone(),
3383 first_blocknum: 100002,
3384 number_of_blocks: 8000,
3389 chain_hash: chain_hash.clone(),
3390 first_blocknum: 100002,
3391 number_of_blocks: 7999,
3392 sync_complete: false,
3393 short_channel_ids: (100002..=108001)
3394 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3398 chain_hash: chain_hash.clone(),
3399 first_blocknum: 108001,
3400 number_of_blocks: 1,
3401 sync_complete: true,
3402 short_channel_ids: vec![
3403 scid_from_parts(108001, 1, 0).unwrap(),
3410 fn do_handling_query_channel_range(
3411 gossip_sync: &P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
3412 test_node_id: &PublicKey,
3413 msg: QueryChannelRange,
3415 expected_replies: Vec<ReplyChannelRange>
3417 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
3418 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
3419 let query_end_blocknum = msg.end_blocknum();
3420 let result = gossip_sync.handle_query_channel_range(test_node_id, msg);
3423 assert!(result.is_ok());
3425 assert!(result.is_err());
3428 let events = gossip_sync.get_and_clear_pending_msg_events();
3429 assert_eq!(events.len(), expected_replies.len());
3431 for i in 0..events.len() {
3432 let expected_reply = &expected_replies[i];
3434 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
3435 assert_eq!(node_id, test_node_id);
3436 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
3437 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
3438 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
3439 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
3440 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
3442 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
3443 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
3444 assert!(msg.first_blocknum >= max_firstblocknum);
3445 max_firstblocknum = msg.first_blocknum;
3446 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
3448 // Check that the last block count is >= the query's end_blocknum
3449 if i == events.len() - 1 {
3450 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
3453 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
3459 fn handling_query_short_channel_ids() {
3460 let network_graph = create_network_graph();
3461 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3462 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3463 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
3465 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3467 let result = gossip_sync.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
3469 short_channel_ids: vec![0x0003e8_000000_0000],
3471 assert!(result.is_err());
3475 fn displays_node_alias() {
3476 let format_str_alias = |alias: &str| {
3477 let mut bytes = [0u8; 32];
3478 bytes[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
3479 format!("{}", NodeAlias(bytes))
3482 assert_eq!(format_str_alias("I\u{1F496}LDK! \u{26A1}"), "I\u{1F496}LDK! \u{26A1}");
3483 assert_eq!(format_str_alias("I\u{1F496}LDK!\0\u{26A1}"), "I\u{1F496}LDK!");
3484 assert_eq!(format_str_alias("I\u{1F496}LDK!\t\u{26A1}"), "I\u{1F496}LDK!\u{FFFD}\u{26A1}");
3486 let format_bytes_alias = |alias: &[u8]| {
3487 let mut bytes = [0u8; 32];
3488 bytes[..alias.len()].copy_from_slice(alias);
3489 format!("{}", NodeAlias(bytes))
3492 assert_eq!(format_bytes_alias(b"\xFFI <heart> LDK!"), "\u{FFFD}I <heart> LDK!");
3493 assert_eq!(format_bytes_alias(b"\xFFI <heart>\0LDK!"), "\u{FFFD}I <heart>");
3494 assert_eq!(format_bytes_alias(b"\xFFI <heart>\tLDK!"), "\u{FFFD}I <heart>\u{FFFD}LDK!");
3498 fn channel_info_is_readable() {
3499 let chanmon_cfgs = crate::ln::functional_test_utils::create_chanmon_cfgs(2);
3500 let node_cfgs = crate::ln::functional_test_utils::create_node_cfgs(2, &chanmon_cfgs);
3501 let node_chanmgrs = crate::ln::functional_test_utils::create_node_chanmgrs(2, &node_cfgs, &[None, None, None, None]);
3502 let nodes = crate::ln::functional_test_utils::create_network(2, &node_cfgs, &node_chanmgrs);
3503 let config = crate::ln::functional_test_utils::test_default_channel_config();
3505 // 1. Test encoding/decoding of ChannelUpdateInfo
3506 let chan_update_info = ChannelUpdateInfo {
3509 cltv_expiry_delta: 42,
3510 htlc_minimum_msat: 1234,
3511 htlc_maximum_msat: 5678,
3512 fees: RoutingFees { base_msat: 9, proportional_millionths: 10 },
3513 last_update_message: None,
3516 let mut encoded_chan_update_info: Vec<u8> = Vec::new();
3517 assert!(chan_update_info.write(&mut encoded_chan_update_info).is_ok());
3519 // First make sure we can read ChannelUpdateInfos we just wrote
3520 let read_chan_update_info: ChannelUpdateInfo = crate::util::ser::Readable::read(&mut encoded_chan_update_info.as_slice()).unwrap();
3521 assert_eq!(chan_update_info, read_chan_update_info);
3523 // Check the serialization hasn't changed.
3524 let legacy_chan_update_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c0100").unwrap();
3525 assert_eq!(encoded_chan_update_info, legacy_chan_update_info_with_some);
3527 // Check we fail if htlc_maximum_msat is not present in either the ChannelUpdateInfo itself
3528 // or the ChannelUpdate enclosed with `last_update_message`.
3529 let legacy_chan_update_info_with_some_and_fail_update: Vec<u8> = <Vec<u8>>::from_hex("b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f42400000271000000014").unwrap();
3530 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());
3531 assert!(read_chan_update_info_res.is_err());
3533 let legacy_chan_update_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100").unwrap();
3534 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());
3535 assert!(read_chan_update_info_res.is_err());
3537 // 2. Test encoding/decoding of ChannelInfo
3538 // Check we can encode/decode ChannelInfo without ChannelUpdateInfo fields present.
3539 let chan_info_none_updates = ChannelInfo {
3540 features: channelmanager::provided_channel_features(&config),
3541 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3543 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3545 capacity_sats: None,
3546 announcement_message: None,
3547 announcement_received_time: 87654,
3550 let mut encoded_chan_info: Vec<u8> = Vec::new();
3551 assert!(chan_info_none_updates.write(&mut encoded_chan_info).is_ok());
3553 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3554 assert_eq!(chan_info_none_updates, read_chan_info);
3556 // Check we can encode/decode ChannelInfo with ChannelUpdateInfo fields present.
3557 let chan_info_some_updates = ChannelInfo {
3558 features: channelmanager::provided_channel_features(&config),
3559 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3560 one_to_two: Some(chan_update_info.clone()),
3561 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3562 two_to_one: Some(chan_update_info.clone()),
3563 capacity_sats: None,
3564 announcement_message: None,
3565 announcement_received_time: 87654,
3568 let mut encoded_chan_info: Vec<u8> = Vec::new();
3569 assert!(chan_info_some_updates.write(&mut encoded_chan_info).is_ok());
3571 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3572 assert_eq!(chan_info_some_updates, read_chan_info);
3574 // Check the serialization hasn't changed.
3575 let legacy_chan_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88043636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23083636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3576 assert_eq!(encoded_chan_info, legacy_chan_info_with_some);
3578 // Check we can decode legacy ChannelInfo, even if the `two_to_one` / `one_to_two` /
3579 // `last_update_message` fields fail to decode due to missing htlc_maximum_msat.
3580 let legacy_chan_info_with_some_and_fail_update = <Vec<u8>>::from_hex("fd01ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce8804b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f4240000027100000001406210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2308b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f424000002710000000140a01000c0100").unwrap();
3581 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_some_and_fail_update.as_slice()).unwrap();
3582 assert_eq!(read_chan_info.announcement_received_time, 87654);
3583 assert_eq!(read_chan_info.one_to_two, None);
3584 assert_eq!(read_chan_info.two_to_one, None);
3586 let legacy_chan_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("ba00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88042e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23082e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3587 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_none.as_slice()).unwrap();
3588 assert_eq!(read_chan_info.announcement_received_time, 87654);
3589 assert_eq!(read_chan_info.one_to_two, None);
3590 assert_eq!(read_chan_info.two_to_one, None);
3594 fn node_info_is_readable() {
3595 // 1. Check we can read a valid NodeAnnouncementInfo and fail on an invalid one
3596 let announcement_message = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000122013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010000701fffefdfc2607").unwrap();
3597 let announcement_message = NodeAnnouncement::read(&mut announcement_message.as_slice()).unwrap();
3598 let valid_node_ann_info = NodeAnnouncementInfo::Relayed(announcement_message);
3600 let mut encoded_valid_node_ann_info = Vec::new();
3601 assert!(valid_node_ann_info.write(&mut encoded_valid_node_ann_info).is_ok());
3602 let read_valid_node_ann_info = NodeAnnouncementInfo::read(&mut encoded_valid_node_ann_info.as_slice()).unwrap();
3603 assert_eq!(read_valid_node_ann_info, valid_node_ann_info);
3604 assert_eq!(read_valid_node_ann_info.addresses().len(), 1);
3606 let encoded_invalid_node_ann_info = <Vec<u8>>::from_hex("3f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d2").unwrap();
3607 let read_invalid_node_ann_info_res = NodeAnnouncementInfo::read(&mut encoded_invalid_node_ann_info.as_slice());
3608 assert!(read_invalid_node_ann_info_res.is_err());
3610 // 2. Check we can read a NodeInfo anyways, but set the NodeAnnouncementInfo to None if invalid
3611 let valid_node_info = NodeInfo {
3612 channels: Vec::new(),
3613 announcement_info: Some(valid_node_ann_info),
3616 let mut encoded_valid_node_info = Vec::new();
3617 assert!(valid_node_info.write(&mut encoded_valid_node_info).is_ok());
3618 let read_valid_node_info = NodeInfo::read(&mut encoded_valid_node_info.as_slice()).unwrap();
3619 assert_eq!(read_valid_node_info, valid_node_info);
3621 let encoded_invalid_node_info_hex = <Vec<u8>>::from_hex("4402403f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d20400").unwrap();
3622 let read_invalid_node_info = NodeInfo::read(&mut encoded_invalid_node_info_hex.as_slice()).unwrap();
3623 assert_eq!(read_invalid_node_info.announcement_info, None);
3627 fn test_node_info_keeps_compatibility() {
3628 let old_ann_info_with_addresses = <Vec<u8>>::from_hex("3f0009000708a000080a51220204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014104d2").unwrap();
3629 let ann_info_with_addresses = NodeAnnouncementInfo::read(&mut old_ann_info_with_addresses.as_slice())
3630 .expect("to be able to read an old NodeAnnouncementInfo with addresses");
3631 // This serialized info has no announcement_message but its address field should still be considered
3632 assert!(!ann_info_with_addresses.addresses().is_empty());
3636 fn test_node_id_display() {
3637 let node_id = NodeId([42; 33]);
3638 assert_eq!(format!("{}", &node_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
3642 fn is_tor_only_node() {
3643 let network_graph = create_network_graph();
3644 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3646 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3647 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3648 let node_1_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
3650 let announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3651 gossip_sync.handle_channel_announcement(&announcement).unwrap();
3653 let tcp_ip_v4 = SocketAddress::TcpIpV4 {
3654 addr: [255, 254, 253, 252],
3657 let tcp_ip_v6 = SocketAddress::TcpIpV6 {
3658 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
3661 let onion_v2 = SocketAddress::OnionV2([255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]);
3662 let onion_v3 = SocketAddress::OnionV3 {
3663 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],
3668 let hostname = SocketAddress::Hostname {
3669 hostname: Hostname::try_from(String::from("host")).unwrap(),
3673 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3675 let announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3676 gossip_sync.handle_node_announcement(&announcement).unwrap();
3677 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3679 let announcement = get_signed_node_announcement(
3681 announcement.addresses = vec![
3682 tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone(),
3685 announcement.timestamp += 1000;
3687 node_1_privkey, &secp_ctx
3689 gossip_sync.handle_node_announcement(&announcement).unwrap();
3690 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3692 let announcement = get_signed_node_announcement(
3694 announcement.addresses = vec![
3695 tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3697 announcement.timestamp += 2000;
3699 node_1_privkey, &secp_ctx
3701 gossip_sync.handle_node_announcement(&announcement).unwrap();
3702 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3704 let announcement = get_signed_node_announcement(
3706 announcement.addresses = vec![
3707 tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3709 announcement.timestamp += 3000;
3711 node_1_privkey, &secp_ctx
3713 gossip_sync.handle_node_announcement(&announcement).unwrap();
3714 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3716 let announcement = get_signed_node_announcement(
3718 announcement.addresses = vec![onion_v2.clone(), onion_v3.clone()];
3719 announcement.timestamp += 4000;
3721 node_1_privkey, &secp_ctx
3723 gossip_sync.handle_node_announcement(&announcement).unwrap();
3724 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3726 let announcement = get_signed_node_announcement(
3728 announcement.addresses = vec![onion_v2.clone()];
3729 announcement.timestamp += 5000;
3731 node_1_privkey, &secp_ctx
3733 gossip_sync.handle_node_announcement(&announcement).unwrap();
3734 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3736 let announcement = get_signed_node_announcement(
3738 announcement.addresses = vec![tcp_ip_v4.clone()];
3739 announcement.timestamp += 6000;
3741 node_1_privkey, &secp_ctx
3743 gossip_sync.handle_node_announcement(&announcement).unwrap();
3744 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3752 use criterion::{black_box, Criterion};
3754 pub fn read_network_graph(bench: &mut Criterion) {
3755 let logger = crate::util::test_utils::TestLogger::new();
3756 let (mut d, _) = crate::routing::router::bench_utils::get_graph_scorer_file().unwrap();
3757 let mut v = Vec::new();
3758 d.read_to_end(&mut v).unwrap();
3759 bench.bench_function("read_network_graph", |b| b.iter(||
3760 NetworkGraph::read(&mut std::io::Cursor::new(black_box(&v)), &logger).unwrap()
3764 pub fn write_network_graph(bench: &mut Criterion) {
3765 let logger = crate::util::test_utils::TestLogger::new();
3766 let (mut d, _) = crate::routing::router::bench_utils::get_graph_scorer_file().unwrap();
3767 let net_graph = NetworkGraph::read(&mut d, &logger).unwrap();
3768 bench.bench_function("write_network_graph", |b| b.iter(||
3769 black_box(&net_graph).encode()