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.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)});
2086 log_gossip!(self.logger, "Updating channel {} in direction {} with timestamp {}", msg.short_channel_id, msg.flags & 1, msg.timestamp);
2088 let mut channels = self.channels.write().unwrap();
2089 match channels.get_mut(&msg.short_channel_id) {
2091 core::mem::drop(channels);
2092 self.pending_checks.check_hold_pending_channel_update(msg, full_msg)?;
2093 return Err(LightningError {
2094 err: "Couldn't find channel for update".to_owned(),
2095 action: ErrorAction::IgnoreAndLog(Level::Gossip),
2099 if msg.htlc_maximum_msat > MAX_VALUE_MSAT {
2100 return Err(LightningError{err:
2101 "htlc_maximum_msat is larger than maximum possible msats".to_owned(),
2102 action: ErrorAction::IgnoreError});
2105 if let Some(capacity_sats) = channel.capacity_sats {
2106 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
2107 // Don't query UTXO set here to reduce DoS risks.
2108 if capacity_sats > MAX_VALUE_MSAT / 1000 || msg.htlc_maximum_msat > capacity_sats * 1000 {
2109 return Err(LightningError{err:
2110 "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(),
2111 action: ErrorAction::IgnoreError});
2114 macro_rules! check_update_latest {
2115 ($target: expr) => {
2116 if let Some(existing_chan_info) = $target.as_ref() {
2117 // The timestamp field is somewhat of a misnomer - the BOLTs use it to
2118 // order updates to ensure you always have the latest one, only
2119 // suggesting that it be at least the current time. For
2120 // channel_updates specifically, the BOLTs discuss the possibility of
2121 // pruning based on the timestamp field being more than two weeks old,
2122 // but only in the non-normative section.
2123 if existing_chan_info.last_update > msg.timestamp {
2124 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2125 } else if existing_chan_info.last_update == msg.timestamp {
2126 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2132 macro_rules! get_new_channel_info {
2134 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
2135 { full_msg.cloned() } else { None };
2137 let updated_channel_update_info = ChannelUpdateInfo {
2138 enabled: chan_enabled,
2139 last_update: msg.timestamp,
2140 cltv_expiry_delta: msg.cltv_expiry_delta,
2141 htlc_minimum_msat: msg.htlc_minimum_msat,
2142 htlc_maximum_msat: msg.htlc_maximum_msat,
2144 base_msat: msg.fee_base_msat,
2145 proportional_millionths: msg.fee_proportional_millionths,
2149 Some(updated_channel_update_info)
2153 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg)[..]);
2154 if msg.flags & 1 == 1 {
2155 check_update_latest!(channel.two_to_one);
2156 if let Some(sig) = sig {
2157 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
2158 err: "Couldn't parse source node pubkey".to_owned(),
2159 action: ErrorAction::IgnoreAndLog(Level::Debug)
2160 })?, "channel_update");
2163 channel.two_to_one = get_new_channel_info!();
2166 check_update_latest!(channel.one_to_two);
2167 if let Some(sig) = sig {
2168 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
2169 err: "Couldn't parse destination node pubkey".to_owned(),
2170 action: ErrorAction::IgnoreAndLog(Level::Debug)
2171 })?, "channel_update");
2174 channel.one_to_two = get_new_channel_info!();
2183 fn remove_channel_in_nodes(nodes: &mut IndexedMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
2184 macro_rules! remove_from_node {
2185 ($node_id: expr) => {
2186 if let IndexedMapEntry::Occupied(mut entry) = nodes.entry($node_id) {
2187 entry.get_mut().channels.retain(|chan_id| {
2188 short_channel_id != *chan_id
2190 if entry.get().channels.is_empty() {
2191 entry.remove_entry();
2194 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
2199 remove_from_node!(chan.node_one);
2200 remove_from_node!(chan.node_two);
2204 impl ReadOnlyNetworkGraph<'_> {
2205 /// Returns all known valid channels' short ids along with announced channel info.
2207 /// This is not exported to bindings users because we don't want to return lifetime'd references
2208 pub fn channels(&self) -> &IndexedMap<u64, ChannelInfo> {
2212 /// Returns information on a channel with the given id.
2213 pub fn channel(&self, short_channel_id: u64) -> Option<&ChannelInfo> {
2214 self.channels.get(&short_channel_id)
2217 #[cfg(c_bindings)] // Non-bindings users should use `channels`
2218 /// Returns the list of channels in the graph
2219 pub fn list_channels(&self) -> Vec<u64> {
2220 self.channels.unordered_keys().map(|c| *c).collect()
2223 /// Returns all known nodes' public keys along with announced node info.
2225 /// This is not exported to bindings users because we don't want to return lifetime'd references
2226 pub fn nodes(&self) -> &IndexedMap<NodeId, NodeInfo> {
2230 /// Returns information on a node with the given id.
2231 pub fn node(&self, node_id: &NodeId) -> Option<&NodeInfo> {
2232 self.nodes.get(node_id)
2235 #[cfg(c_bindings)] // Non-bindings users should use `nodes`
2236 /// Returns the list of nodes in the graph
2237 pub fn list_nodes(&self) -> Vec<NodeId> {
2238 self.nodes.unordered_keys().map(|n| *n).collect()
2241 /// Get network addresses by node id.
2242 /// Returns None if the requested node is completely unknown,
2243 /// or if node announcement for the node was never received.
2244 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<SocketAddress>> {
2245 self.nodes.get(&NodeId::from_pubkey(&pubkey))
2246 .and_then(|node| node.announcement_info.as_ref().map(|ann| ann.addresses().to_vec()))
2251 pub(crate) mod tests {
2252 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
2253 use crate::ln::channelmanager;
2254 use crate::ln::chan_utils::make_funding_redeemscript;
2255 #[cfg(feature = "std")]
2256 use crate::ln::features::InitFeatures;
2257 use crate::ln::msgs::SocketAddress;
2258 use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, NodeAlias, MAX_EXCESS_BYTES_FOR_RELAY, NodeId, RoutingFees, ChannelUpdateInfo, ChannelInfo, NodeAnnouncementInfo, NodeInfo};
2259 use crate::routing::utxo::{UtxoLookupError, UtxoResult};
2260 use crate::ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
2261 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
2262 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
2263 use crate::util::config::UserConfig;
2264 use crate::util::test_utils;
2265 use crate::util::ser::{Hostname, ReadableArgs, Readable, Writeable};
2266 use crate::util::scid_utils::scid_from_parts;
2268 use crate::routing::gossip::REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS;
2269 use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
2271 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
2272 use bitcoin::hashes::Hash;
2273 use bitcoin::hashes::hex::FromHex;
2274 use bitcoin::network::Network;
2275 use bitcoin::amount::Amount;
2276 use bitcoin::blockdata::constants::ChainHash;
2277 use bitcoin::blockdata::script::ScriptBuf;
2278 use bitcoin::blockdata::transaction::TxOut;
2279 use bitcoin::secp256k1::{PublicKey, SecretKey};
2280 use bitcoin::secp256k1::{All, Secp256k1};
2283 use bitcoin::secp256k1;
2284 use crate::prelude::*;
2285 use crate::sync::Arc;
2287 fn create_network_graph() -> NetworkGraph<Arc<test_utils::TestLogger>> {
2288 let logger = Arc::new(test_utils::TestLogger::new());
2289 NetworkGraph::new(Network::Testnet, logger)
2292 fn create_gossip_sync(network_graph: &NetworkGraph<Arc<test_utils::TestLogger>>) -> (
2293 Secp256k1<All>, P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>,
2294 Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
2296 let secp_ctx = Secp256k1::new();
2297 let logger = Arc::new(test_utils::TestLogger::new());
2298 let gossip_sync = P2PGossipSync::new(network_graph, None, Arc::clone(&logger));
2299 (secp_ctx, gossip_sync)
2303 #[cfg(feature = "std")]
2304 fn request_full_sync_finite_times() {
2305 let network_graph = create_network_graph();
2306 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2307 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
2309 assert!(gossip_sync.should_request_full_sync(&node_id));
2310 assert!(gossip_sync.should_request_full_sync(&node_id));
2311 assert!(gossip_sync.should_request_full_sync(&node_id));
2312 assert!(gossip_sync.should_request_full_sync(&node_id));
2313 assert!(gossip_sync.should_request_full_sync(&node_id));
2314 assert!(!gossip_sync.should_request_full_sync(&node_id));
2317 pub(crate) fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
2318 let node_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_key));
2319 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2320 features: channelmanager::provided_node_features(&UserConfig::default()),
2324 alias: NodeAlias([0; 32]),
2325 addresses: Vec::new(),
2326 excess_address_data: Vec::new(),
2327 excess_data: Vec::new(),
2329 f(&mut unsigned_announcement);
2330 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2332 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2333 contents: unsigned_announcement
2337 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 {
2338 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
2339 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
2340 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2341 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2343 let mut unsigned_announcement = UnsignedChannelAnnouncement {
2344 features: channelmanager::provided_channel_features(&UserConfig::default()),
2345 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2346 short_channel_id: 0,
2347 node_id_1: NodeId::from_pubkey(&node_id_1),
2348 node_id_2: NodeId::from_pubkey(&node_id_2),
2349 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey)),
2350 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey)),
2351 excess_data: Vec::new(),
2353 f(&mut unsigned_announcement);
2354 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2355 ChannelAnnouncement {
2356 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_key),
2357 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_key),
2358 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_btckey),
2359 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_btckey),
2360 contents: unsigned_announcement,
2364 pub(crate) fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> ScriptBuf {
2365 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
2366 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
2367 make_funding_redeemscript(&PublicKey::from_secret_key(secp_ctx, &node_1_btckey),
2368 &PublicKey::from_secret_key(secp_ctx, &node_2_btckey)).to_p2wsh()
2371 pub(crate) fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
2372 let mut unsigned_channel_update = UnsignedChannelUpdate {
2373 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2374 short_channel_id: 0,
2377 cltv_expiry_delta: 144,
2378 htlc_minimum_msat: 1_000_000,
2379 htlc_maximum_msat: 1_000_000,
2380 fee_base_msat: 10_000,
2381 fee_proportional_millionths: 20,
2382 excess_data: Vec::new()
2384 f(&mut unsigned_channel_update);
2385 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2387 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2388 contents: unsigned_channel_update
2393 fn handling_node_announcements() {
2394 let network_graph = create_network_graph();
2395 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2397 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2398 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2399 let zero_hash = Sha256dHash::hash(&[0; 32]);
2401 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2402 match gossip_sync.handle_node_announcement(&valid_announcement) {
2404 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
2408 // Announce a channel to add a corresponding node.
2409 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2410 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2411 Ok(res) => assert!(res),
2416 match gossip_sync.handle_node_announcement(&valid_announcement) {
2417 Ok(res) => assert!(res),
2421 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2422 match gossip_sync.handle_node_announcement(
2424 signature: secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey),
2425 contents: valid_announcement.contents.clone()
2428 Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
2431 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
2432 unsigned_announcement.timestamp += 1000;
2433 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2434 }, node_1_privkey, &secp_ctx);
2435 // Return false because contains excess data.
2436 match gossip_sync.handle_node_announcement(&announcement_with_data) {
2437 Ok(res) => assert!(!res),
2441 // Even though previous announcement was not relayed further, we still accepted it,
2442 // so we now won't accept announcements before the previous one.
2443 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
2444 unsigned_announcement.timestamp += 1000 - 10;
2445 }, node_1_privkey, &secp_ctx);
2446 match gossip_sync.handle_node_announcement(&outdated_announcement) {
2448 Err(e) => assert_eq!(e.err, "Update older than last processed update")
2453 fn handling_channel_announcements() {
2454 let secp_ctx = Secp256k1::new();
2455 let logger = test_utils::TestLogger::new();
2457 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2458 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2460 let good_script = get_channel_script(&secp_ctx);
2461 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2463 // Test if the UTXO lookups were not supported
2464 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2465 let mut gossip_sync = P2PGossipSync::new(&network_graph, None, &logger);
2466 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2467 Ok(res) => assert!(res),
2472 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2478 // If we receive announcement for the same channel (with UTXO lookups disabled),
2479 // drop new one on the floor, since we can't see any changes.
2480 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2482 Err(e) => assert_eq!(e.err, "Already have non-chain-validated channel")
2485 // Test if an associated transaction were not on-chain (or not confirmed).
2486 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2487 *chain_source.utxo_ret.lock().unwrap() = UtxoResult::Sync(Err(UtxoLookupError::UnknownTx));
2488 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2489 gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2491 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2492 unsigned_announcement.short_channel_id += 1;
2493 }, node_1_privkey, node_2_privkey, &secp_ctx);
2494 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2496 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2499 // Now test if the transaction is found in the UTXO set and the script is correct.
2500 *chain_source.utxo_ret.lock().unwrap() =
2501 UtxoResult::Sync(Ok(TxOut { value: Amount::ZERO, script_pubkey: good_script.clone() }));
2502 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2503 unsigned_announcement.short_channel_id += 2;
2504 }, node_1_privkey, node_2_privkey, &secp_ctx);
2505 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2506 Ok(res) => assert!(res),
2511 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2517 // If we receive announcement for the same channel, once we've validated it against the
2518 // chain, we simply ignore all new (duplicate) announcements.
2519 *chain_source.utxo_ret.lock().unwrap() =
2520 UtxoResult::Sync(Ok(TxOut { value: Amount::ZERO, script_pubkey: good_script }));
2521 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2523 Err(e) => assert_eq!(e.err, "Already have chain-validated channel")
2526 #[cfg(feature = "std")]
2528 use std::time::{SystemTime, UNIX_EPOCH};
2530 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2531 // Mark a node as permanently failed so it's tracked as removed.
2532 gossip_sync.network_graph().node_failed_permanent(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2534 // Return error and ignore valid channel announcement if one of the nodes has been tracked as removed.
2535 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2536 unsigned_announcement.short_channel_id += 3;
2537 }, node_1_privkey, node_2_privkey, &secp_ctx);
2538 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2540 Err(e) => assert_eq!(e.err, "Channel with SCID 3 or one of its nodes was removed from our network graph recently")
2543 gossip_sync.network_graph().remove_stale_channels_and_tracking_with_time(tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2545 // The above channel announcement should be handled as per normal now.
2546 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2547 Ok(res) => assert!(res),
2552 // Don't relay valid channels with excess data
2553 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2554 unsigned_announcement.short_channel_id += 4;
2555 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2556 }, node_1_privkey, node_2_privkey, &secp_ctx);
2557 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2558 Ok(res) => assert!(!res),
2562 let mut invalid_sig_announcement = valid_announcement.clone();
2563 invalid_sig_announcement.contents.excess_data = Vec::new();
2564 match gossip_sync.handle_channel_announcement(&invalid_sig_announcement) {
2566 Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
2569 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
2570 match gossip_sync.handle_channel_announcement(&channel_to_itself_announcement) {
2572 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2575 // Test that channel announcements with the wrong chain hash are ignored (network graph is testnet,
2576 // announcement is mainnet).
2577 let incorrect_chain_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2578 unsigned_announcement.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2579 }, node_1_privkey, node_2_privkey, &secp_ctx);
2580 match gossip_sync.handle_channel_announcement(&incorrect_chain_announcement) {
2582 Err(e) => assert_eq!(e.err, "Channel announcement chain hash does not match genesis hash")
2587 fn handling_channel_update() {
2588 let secp_ctx = Secp256k1::new();
2589 let logger = test_utils::TestLogger::new();
2590 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2591 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2592 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2594 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2595 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2597 let amount_sats = Amount::from_sat(1000_000);
2598 let short_channel_id;
2601 // Announce a channel we will update
2602 let good_script = get_channel_script(&secp_ctx);
2603 *chain_source.utxo_ret.lock().unwrap() =
2604 UtxoResult::Sync(Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() }));
2606 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2607 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2608 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2615 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2616 network_graph.verify_channel_update(&valid_channel_update).unwrap();
2617 match gossip_sync.handle_channel_update(&valid_channel_update) {
2618 Ok(res) => assert!(res),
2623 match network_graph.read_only().channels().get(&short_channel_id) {
2625 Some(channel_info) => {
2626 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
2627 assert!(channel_info.two_to_one.is_none());
2632 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2633 unsigned_channel_update.timestamp += 100;
2634 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2635 }, node_1_privkey, &secp_ctx);
2636 // Return false because contains excess data
2637 match gossip_sync.handle_channel_update(&valid_channel_update) {
2638 Ok(res) => assert!(!res),
2642 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2643 unsigned_channel_update.timestamp += 110;
2644 unsigned_channel_update.short_channel_id += 1;
2645 }, node_1_privkey, &secp_ctx);
2646 match gossip_sync.handle_channel_update(&valid_channel_update) {
2648 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2651 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2652 unsigned_channel_update.htlc_maximum_msat = MAX_VALUE_MSAT + 1;
2653 unsigned_channel_update.timestamp += 110;
2654 }, node_1_privkey, &secp_ctx);
2655 match gossip_sync.handle_channel_update(&valid_channel_update) {
2657 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
2660 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2661 unsigned_channel_update.htlc_maximum_msat = amount_sats.to_sat() * 1000 + 1;
2662 unsigned_channel_update.timestamp += 110;
2663 }, node_1_privkey, &secp_ctx);
2664 match gossip_sync.handle_channel_update(&valid_channel_update) {
2666 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
2669 // Even though previous update was not relayed further, we still accepted it,
2670 // so we now won't accept update before the previous one.
2671 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2672 unsigned_channel_update.timestamp += 100;
2673 }, node_1_privkey, &secp_ctx);
2674 match gossip_sync.handle_channel_update(&valid_channel_update) {
2676 Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
2679 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2680 unsigned_channel_update.timestamp += 500;
2681 }, node_1_privkey, &secp_ctx);
2682 let zero_hash = Sha256dHash::hash(&[0; 32]);
2683 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2684 invalid_sig_channel_update.signature = secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey);
2685 match gossip_sync.handle_channel_update(&invalid_sig_channel_update) {
2687 Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
2690 // Test that channel updates with the wrong chain hash are ignored (network graph is testnet, channel
2691 // update is mainet).
2692 let incorrect_chain_update = get_signed_channel_update(|unsigned_channel_update| {
2693 unsigned_channel_update.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2694 }, node_1_privkey, &secp_ctx);
2696 match gossip_sync.handle_channel_update(&incorrect_chain_update) {
2698 Err(e) => assert_eq!(e.err, "Channel update chain hash does not match genesis hash")
2703 fn handling_network_update() {
2704 let logger = test_utils::TestLogger::new();
2705 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2706 let secp_ctx = Secp256k1::new();
2708 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2709 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2710 let node_2_id = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2713 // There is no nodes in the table at the beginning.
2714 assert_eq!(network_graph.read_only().nodes().len(), 0);
2717 let short_channel_id;
2719 // Check that we can manually apply a channel update.
2720 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2721 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2722 let chain_source: Option<&test_utils::TestChainSource> = None;
2723 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2724 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2726 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2728 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2729 network_graph.update_channel(&valid_channel_update).unwrap();
2730 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2733 // Non-permanent failure doesn't touch the channel at all
2735 match network_graph.read_only().channels().get(&short_channel_id) {
2737 Some(channel_info) => {
2738 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2742 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2744 is_permanent: false,
2747 match network_graph.read_only().channels().get(&short_channel_id) {
2749 Some(channel_info) => {
2750 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2755 // Permanent closing deletes a channel
2756 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2761 assert_eq!(network_graph.read_only().channels().len(), 0);
2762 // Nodes are also deleted because there are no associated channels anymore
2763 assert_eq!(network_graph.read_only().nodes().len(), 0);
2766 // Get a new network graph since we don't want to track removed nodes in this test with "std"
2767 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2769 // Announce a channel to test permanent node failure
2770 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2771 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2772 let chain_source: Option<&test_utils::TestChainSource> = None;
2773 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2774 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2776 // Non-permanent node failure does not delete any nodes or channels
2777 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2779 is_permanent: false,
2782 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2783 assert!(network_graph.read_only().nodes().get(&NodeId::from_pubkey(&node_2_id)).is_some());
2785 // Permanent node failure deletes node and its channels
2786 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2791 assert_eq!(network_graph.read_only().nodes().len(), 0);
2792 // Channels are also deleted because the associated node has been deleted
2793 assert_eq!(network_graph.read_only().channels().len(), 0);
2798 fn test_channel_timeouts() {
2799 // Test the removal of channels with `remove_stale_channels_and_tracking`.
2800 let logger = test_utils::TestLogger::new();
2801 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2802 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2803 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2804 let secp_ctx = Secp256k1::new();
2806 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2807 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2809 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2810 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2811 let chain_source: Option<&test_utils::TestChainSource> = None;
2812 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2813 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2815 // Submit two channel updates for each channel direction (update.flags bit).
2816 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2817 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2818 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2820 let valid_channel_update_2 = get_signed_channel_update(|update| {update.flags |=1;}, node_2_privkey, &secp_ctx);
2821 gossip_sync.handle_channel_update(&valid_channel_update_2).unwrap();
2822 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().two_to_one.is_some());
2824 network_graph.remove_stale_channels_and_tracking_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2825 assert_eq!(network_graph.read_only().channels().len(), 1);
2826 assert_eq!(network_graph.read_only().nodes().len(), 2);
2828 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2829 #[cfg(not(feature = "std"))] {
2830 // Make sure removed channels are tracked.
2831 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2833 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2834 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2836 #[cfg(feature = "std")]
2838 // In std mode, a further check is performed before fully removing the channel -
2839 // the channel_announcement must have been received at least two weeks ago. We
2840 // fudge that here by indicating the time has jumped two weeks.
2841 assert_eq!(network_graph.read_only().channels().len(), 1);
2842 assert_eq!(network_graph.read_only().nodes().len(), 2);
2844 // Note that the directional channel information will have been removed already..
2845 // We want to check that this will work even if *one* of the channel updates is recent,
2846 // so we should add it with a recent timestamp.
2847 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2848 use std::time::{SystemTime, UNIX_EPOCH};
2849 let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2850 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2851 unsigned_channel_update.timestamp = (announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
2852 }, node_1_privkey, &secp_ctx);
2853 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2854 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2855 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2856 // Make sure removed channels are tracked.
2857 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2858 // Provide a later time so that sufficient time has passed
2859 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2860 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2863 assert_eq!(network_graph.read_only().channels().len(), 0);
2864 assert_eq!(network_graph.read_only().nodes().len(), 0);
2865 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2867 #[cfg(feature = "std")]
2869 use std::time::{SystemTime, UNIX_EPOCH};
2871 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2873 // Clear tracked nodes and channels for clean slate
2874 network_graph.removed_channels.lock().unwrap().clear();
2875 network_graph.removed_nodes.lock().unwrap().clear();
2877 // Add a channel and nodes from channel announcement. So our network graph will
2878 // now only consist of two nodes and one channel between them.
2879 assert!(network_graph.update_channel_from_announcement(
2880 &valid_channel_announcement, &chain_source).is_ok());
2882 // Mark the channel as permanently failed. This will also remove the two nodes
2883 // and all of the entries will be tracked as removed.
2884 network_graph.channel_failed_permanent_with_time(short_channel_id, Some(tracking_time));
2886 // Should not remove from tracking if insufficient time has passed
2887 network_graph.remove_stale_channels_and_tracking_with_time(
2888 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS - 1);
2889 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1, "Removed channel count ≠1 with tracking_time {}", tracking_time);
2891 // Provide a later time so that sufficient time has passed
2892 network_graph.remove_stale_channels_and_tracking_with_time(
2893 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2894 assert!(network_graph.removed_channels.lock().unwrap().is_empty(), "Unexpectedly removed channels with tracking_time {}", tracking_time);
2895 assert!(network_graph.removed_nodes.lock().unwrap().is_empty(), "Unexpectedly removed nodes with tracking_time {}", tracking_time);
2898 #[cfg(not(feature = "std"))]
2900 // When we don't have access to the system clock, the time we started tracking removal will only
2901 // be that provided by the first call to `remove_stale_channels_and_tracking_with_time`. Hence,
2902 // only if sufficient time has passed after that first call, will the next call remove it from
2904 let removal_time = 1664619654;
2906 // Clear removed nodes and channels for clean slate
2907 network_graph.removed_channels.lock().unwrap().clear();
2908 network_graph.removed_nodes.lock().unwrap().clear();
2910 // Add a channel and nodes from channel announcement. So our network graph will
2911 // now only consist of two nodes and one channel between them.
2912 assert!(network_graph.update_channel_from_announcement(
2913 &valid_channel_announcement, &chain_source).is_ok());
2915 // Mark the channel as permanently failed. This will also remove the two nodes
2916 // and all of the entries will be tracked as removed.
2917 network_graph.channel_failed_permanent(short_channel_id);
2919 // The first time we call the following, the channel will have a removal time assigned.
2920 network_graph.remove_stale_channels_and_tracking_with_time(removal_time);
2921 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2923 // Provide a later time so that sufficient time has passed
2924 network_graph.remove_stale_channels_and_tracking_with_time(
2925 removal_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2926 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2927 assert!(network_graph.removed_nodes.lock().unwrap().is_empty());
2932 fn getting_next_channel_announcements() {
2933 let network_graph = create_network_graph();
2934 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2935 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2936 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2938 // Channels were not announced yet.
2939 let channels_with_announcements = gossip_sync.get_next_channel_announcement(0);
2940 assert!(channels_with_announcements.is_none());
2942 let short_channel_id;
2944 // Announce a channel we will update
2945 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2946 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2947 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2953 // Contains initial channel announcement now.
2954 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2955 if let Some(channel_announcements) = channels_with_announcements {
2956 let (_, ref update_1, ref update_2) = channel_announcements;
2957 assert_eq!(update_1, &None);
2958 assert_eq!(update_2, &None);
2964 // Valid channel update
2965 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2966 unsigned_channel_update.timestamp = 101;
2967 }, node_1_privkey, &secp_ctx);
2968 match gossip_sync.handle_channel_update(&valid_channel_update) {
2974 // Now contains an initial announcement and an update.
2975 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2976 if let Some(channel_announcements) = channels_with_announcements {
2977 let (_, ref update_1, ref update_2) = channel_announcements;
2978 assert_ne!(update_1, &None);
2979 assert_eq!(update_2, &None);
2985 // Channel update with excess data.
2986 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2987 unsigned_channel_update.timestamp = 102;
2988 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2989 }, node_1_privkey, &secp_ctx);
2990 match gossip_sync.handle_channel_update(&valid_channel_update) {
2996 // Test that announcements with excess data won't be returned
2997 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2998 if let Some(channel_announcements) = channels_with_announcements {
2999 let (_, ref update_1, ref update_2) = channel_announcements;
3000 assert_eq!(update_1, &None);
3001 assert_eq!(update_2, &None);
3006 // Further starting point have no channels after it
3007 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id + 1000);
3008 assert!(channels_with_announcements.is_none());
3012 fn getting_next_node_announcements() {
3013 let network_graph = create_network_graph();
3014 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3015 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3016 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3017 let node_id_1 = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
3020 let next_announcements = gossip_sync.get_next_node_announcement(None);
3021 assert!(next_announcements.is_none());
3024 // Announce a channel to add 2 nodes
3025 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3026 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
3032 // Nodes were never announced
3033 let next_announcements = gossip_sync.get_next_node_announcement(None);
3034 assert!(next_announcements.is_none());
3037 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3038 match gossip_sync.handle_node_announcement(&valid_announcement) {
3043 let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
3044 match gossip_sync.handle_node_announcement(&valid_announcement) {
3050 let next_announcements = gossip_sync.get_next_node_announcement(None);
3051 assert!(next_announcements.is_some());
3053 // Skip the first node.
3054 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3055 assert!(next_announcements.is_some());
3058 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
3059 let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
3060 unsigned_announcement.timestamp += 10;
3061 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
3062 }, node_2_privkey, &secp_ctx);
3063 match gossip_sync.handle_node_announcement(&valid_announcement) {
3064 Ok(res) => assert!(!res),
3069 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3070 assert!(next_announcements.is_none());
3074 fn network_graph_serialization() {
3075 let network_graph = create_network_graph();
3076 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3078 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3079 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3081 // Announce a channel to add a corresponding node.
3082 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3083 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3084 Ok(res) => assert!(res),
3088 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3089 match gossip_sync.handle_node_announcement(&valid_announcement) {
3094 let mut w = test_utils::TestVecWriter(Vec::new());
3095 assert!(!network_graph.read_only().nodes().is_empty());
3096 assert!(!network_graph.read_only().channels().is_empty());
3097 network_graph.write(&mut w).unwrap();
3099 let logger = Arc::new(test_utils::TestLogger::new());
3100 assert!(<NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), logger).unwrap() == network_graph);
3104 fn network_graph_tlv_serialization() {
3105 let network_graph = create_network_graph();
3106 network_graph.set_last_rapid_gossip_sync_timestamp(42);
3108 let mut w = test_utils::TestVecWriter(Vec::new());
3109 network_graph.write(&mut w).unwrap();
3111 let logger = Arc::new(test_utils::TestLogger::new());
3112 let reassembled_network_graph: NetworkGraph<_> = ReadableArgs::read(&mut io::Cursor::new(&w.0), logger).unwrap();
3113 assert!(reassembled_network_graph == network_graph);
3114 assert_eq!(reassembled_network_graph.get_last_rapid_gossip_sync_timestamp().unwrap(), 42);
3118 #[cfg(feature = "std")]
3119 fn calling_sync_routing_table() {
3120 use std::time::{SystemTime, UNIX_EPOCH};
3121 use crate::ln::msgs::Init;
3123 let network_graph = create_network_graph();
3124 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3125 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
3126 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
3128 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3130 // It should ignore if gossip_queries feature is not enabled
3132 let init_msg = Init { features: InitFeatures::empty(), networks: None, remote_network_address: None };
3133 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3134 let events = gossip_sync.get_and_clear_pending_msg_events();
3135 assert_eq!(events.len(), 0);
3138 // It should send a gossip_timestamp_filter with the correct information
3140 let mut features = InitFeatures::empty();
3141 features.set_gossip_queries_optional();
3142 let init_msg = Init { features, networks: None, remote_network_address: None };
3143 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3144 let events = gossip_sync.get_and_clear_pending_msg_events();
3145 assert_eq!(events.len(), 1);
3147 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
3148 assert_eq!(node_id, &node_id_1);
3149 assert_eq!(msg.chain_hash, chain_hash);
3150 let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
3151 assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
3152 assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
3153 assert_eq!(msg.timestamp_range, u32::max_value());
3155 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
3161 fn handling_query_channel_range() {
3162 let network_graph = create_network_graph();
3163 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3165 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3166 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3167 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3168 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
3170 let mut scids: Vec<u64> = vec![
3171 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
3172 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
3175 // used for testing multipart reply across blocks
3176 for block in 100000..=108001 {
3177 scids.push(scid_from_parts(block, 0, 0).unwrap());
3180 // used for testing resumption on same block
3181 scids.push(scid_from_parts(108001, 1, 0).unwrap());
3184 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
3185 unsigned_announcement.short_channel_id = scid;
3186 }, node_1_privkey, node_2_privkey, &secp_ctx);
3187 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3193 // Error when number_of_blocks=0
3194 do_handling_query_channel_range(
3198 chain_hash: chain_hash.clone(),
3200 number_of_blocks: 0,
3203 vec![ReplyChannelRange {
3204 chain_hash: chain_hash.clone(),
3206 number_of_blocks: 0,
3207 sync_complete: true,
3208 short_channel_ids: vec![]
3212 // Error when wrong chain
3213 do_handling_query_channel_range(
3217 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3219 number_of_blocks: 0xffff_ffff,
3222 vec![ReplyChannelRange {
3223 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3225 number_of_blocks: 0xffff_ffff,
3226 sync_complete: true,
3227 short_channel_ids: vec![],
3231 // Error when first_blocknum > 0xffffff
3232 do_handling_query_channel_range(
3236 chain_hash: chain_hash.clone(),
3237 first_blocknum: 0x01000000,
3238 number_of_blocks: 0xffff_ffff,
3241 vec![ReplyChannelRange {
3242 chain_hash: chain_hash.clone(),
3243 first_blocknum: 0x01000000,
3244 number_of_blocks: 0xffff_ffff,
3245 sync_complete: true,
3246 short_channel_ids: vec![]
3250 // Empty reply when max valid SCID block num
3251 do_handling_query_channel_range(
3255 chain_hash: chain_hash.clone(),
3256 first_blocknum: 0xffffff,
3257 number_of_blocks: 1,
3262 chain_hash: chain_hash.clone(),
3263 first_blocknum: 0xffffff,
3264 number_of_blocks: 1,
3265 sync_complete: true,
3266 short_channel_ids: vec![]
3271 // No results in valid query range
3272 do_handling_query_channel_range(
3276 chain_hash: chain_hash.clone(),
3277 first_blocknum: 1000,
3278 number_of_blocks: 1000,
3283 chain_hash: chain_hash.clone(),
3284 first_blocknum: 1000,
3285 number_of_blocks: 1000,
3286 sync_complete: true,
3287 short_channel_ids: vec![],
3292 // Overflow first_blocknum + number_of_blocks
3293 do_handling_query_channel_range(
3297 chain_hash: chain_hash.clone(),
3298 first_blocknum: 0xfe0000,
3299 number_of_blocks: 0xffffffff,
3304 chain_hash: chain_hash.clone(),
3305 first_blocknum: 0xfe0000,
3306 number_of_blocks: 0xffffffff - 0xfe0000,
3307 sync_complete: true,
3308 short_channel_ids: vec![
3309 0xfffffe_ffffff_ffff, // max
3315 // Single block exactly full
3316 do_handling_query_channel_range(
3320 chain_hash: chain_hash.clone(),
3321 first_blocknum: 100000,
3322 number_of_blocks: 8000,
3327 chain_hash: chain_hash.clone(),
3328 first_blocknum: 100000,
3329 number_of_blocks: 8000,
3330 sync_complete: true,
3331 short_channel_ids: (100000..=107999)
3332 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3338 // Multiple split on new block
3339 do_handling_query_channel_range(
3343 chain_hash: chain_hash.clone(),
3344 first_blocknum: 100000,
3345 number_of_blocks: 8001,
3350 chain_hash: chain_hash.clone(),
3351 first_blocknum: 100000,
3352 number_of_blocks: 7999,
3353 sync_complete: false,
3354 short_channel_ids: (100000..=107999)
3355 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3359 chain_hash: chain_hash.clone(),
3360 first_blocknum: 107999,
3361 number_of_blocks: 2,
3362 sync_complete: true,
3363 short_channel_ids: vec![
3364 scid_from_parts(108000, 0, 0).unwrap(),
3370 // Multiple split on same block
3371 do_handling_query_channel_range(
3375 chain_hash: chain_hash.clone(),
3376 first_blocknum: 100002,
3377 number_of_blocks: 8000,
3382 chain_hash: chain_hash.clone(),
3383 first_blocknum: 100002,
3384 number_of_blocks: 7999,
3385 sync_complete: false,
3386 short_channel_ids: (100002..=108001)
3387 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3391 chain_hash: chain_hash.clone(),
3392 first_blocknum: 108001,
3393 number_of_blocks: 1,
3394 sync_complete: true,
3395 short_channel_ids: vec![
3396 scid_from_parts(108001, 1, 0).unwrap(),
3403 fn do_handling_query_channel_range(
3404 gossip_sync: &P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
3405 test_node_id: &PublicKey,
3406 msg: QueryChannelRange,
3408 expected_replies: Vec<ReplyChannelRange>
3410 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
3411 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
3412 let query_end_blocknum = msg.end_blocknum();
3413 let result = gossip_sync.handle_query_channel_range(test_node_id, msg);
3416 assert!(result.is_ok());
3418 assert!(result.is_err());
3421 let events = gossip_sync.get_and_clear_pending_msg_events();
3422 assert_eq!(events.len(), expected_replies.len());
3424 for i in 0..events.len() {
3425 let expected_reply = &expected_replies[i];
3427 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
3428 assert_eq!(node_id, test_node_id);
3429 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
3430 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
3431 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
3432 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
3433 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
3435 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
3436 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
3437 assert!(msg.first_blocknum >= max_firstblocknum);
3438 max_firstblocknum = msg.first_blocknum;
3439 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
3441 // Check that the last block count is >= the query's end_blocknum
3442 if i == events.len() - 1 {
3443 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
3446 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
3452 fn handling_query_short_channel_ids() {
3453 let network_graph = create_network_graph();
3454 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3455 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3456 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
3458 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3460 let result = gossip_sync.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
3462 short_channel_ids: vec![0x0003e8_000000_0000],
3464 assert!(result.is_err());
3468 fn displays_node_alias() {
3469 let format_str_alias = |alias: &str| {
3470 let mut bytes = [0u8; 32];
3471 bytes[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
3472 format!("{}", NodeAlias(bytes))
3475 assert_eq!(format_str_alias("I\u{1F496}LDK! \u{26A1}"), "I\u{1F496}LDK! \u{26A1}");
3476 assert_eq!(format_str_alias("I\u{1F496}LDK!\0\u{26A1}"), "I\u{1F496}LDK!");
3477 assert_eq!(format_str_alias("I\u{1F496}LDK!\t\u{26A1}"), "I\u{1F496}LDK!\u{FFFD}\u{26A1}");
3479 let format_bytes_alias = |alias: &[u8]| {
3480 let mut bytes = [0u8; 32];
3481 bytes[..alias.len()].copy_from_slice(alias);
3482 format!("{}", NodeAlias(bytes))
3485 assert_eq!(format_bytes_alias(b"\xFFI <heart> LDK!"), "\u{FFFD}I <heart> LDK!");
3486 assert_eq!(format_bytes_alias(b"\xFFI <heart>\0LDK!"), "\u{FFFD}I <heart>");
3487 assert_eq!(format_bytes_alias(b"\xFFI <heart>\tLDK!"), "\u{FFFD}I <heart>\u{FFFD}LDK!");
3491 fn channel_info_is_readable() {
3492 let chanmon_cfgs = crate::ln::functional_test_utils::create_chanmon_cfgs(2);
3493 let node_cfgs = crate::ln::functional_test_utils::create_node_cfgs(2, &chanmon_cfgs);
3494 let node_chanmgrs = crate::ln::functional_test_utils::create_node_chanmgrs(2, &node_cfgs, &[None, None, None, None]);
3495 let nodes = crate::ln::functional_test_utils::create_network(2, &node_cfgs, &node_chanmgrs);
3496 let config = crate::ln::functional_test_utils::test_default_channel_config();
3498 // 1. Test encoding/decoding of ChannelUpdateInfo
3499 let chan_update_info = ChannelUpdateInfo {
3502 cltv_expiry_delta: 42,
3503 htlc_minimum_msat: 1234,
3504 htlc_maximum_msat: 5678,
3505 fees: RoutingFees { base_msat: 9, proportional_millionths: 10 },
3506 last_update_message: None,
3509 let mut encoded_chan_update_info: Vec<u8> = Vec::new();
3510 assert!(chan_update_info.write(&mut encoded_chan_update_info).is_ok());
3512 // First make sure we can read ChannelUpdateInfos we just wrote
3513 let read_chan_update_info: ChannelUpdateInfo = crate::util::ser::Readable::read(&mut encoded_chan_update_info.as_slice()).unwrap();
3514 assert_eq!(chan_update_info, read_chan_update_info);
3516 // Check the serialization hasn't changed.
3517 let legacy_chan_update_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c0100").unwrap();
3518 assert_eq!(encoded_chan_update_info, legacy_chan_update_info_with_some);
3520 // Check we fail if htlc_maximum_msat is not present in either the ChannelUpdateInfo itself
3521 // or the ChannelUpdate enclosed with `last_update_message`.
3522 let legacy_chan_update_info_with_some_and_fail_update: Vec<u8> = <Vec<u8>>::from_hex("b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f42400000271000000014").unwrap();
3523 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());
3524 assert!(read_chan_update_info_res.is_err());
3526 let legacy_chan_update_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100").unwrap();
3527 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());
3528 assert!(read_chan_update_info_res.is_err());
3530 // 2. Test encoding/decoding of ChannelInfo
3531 // Check we can encode/decode ChannelInfo without ChannelUpdateInfo fields present.
3532 let chan_info_none_updates = ChannelInfo {
3533 features: channelmanager::provided_channel_features(&config),
3534 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3536 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3538 capacity_sats: None,
3539 announcement_message: None,
3540 announcement_received_time: 87654,
3543 let mut encoded_chan_info: Vec<u8> = Vec::new();
3544 assert!(chan_info_none_updates.write(&mut encoded_chan_info).is_ok());
3546 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3547 assert_eq!(chan_info_none_updates, read_chan_info);
3549 // Check we can encode/decode ChannelInfo with ChannelUpdateInfo fields present.
3550 let chan_info_some_updates = ChannelInfo {
3551 features: channelmanager::provided_channel_features(&config),
3552 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3553 one_to_two: Some(chan_update_info.clone()),
3554 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3555 two_to_one: Some(chan_update_info.clone()),
3556 capacity_sats: None,
3557 announcement_message: None,
3558 announcement_received_time: 87654,
3561 let mut encoded_chan_info: Vec<u8> = Vec::new();
3562 assert!(chan_info_some_updates.write(&mut encoded_chan_info).is_ok());
3564 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3565 assert_eq!(chan_info_some_updates, read_chan_info);
3567 // Check the serialization hasn't changed.
3568 let legacy_chan_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88043636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23083636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3569 assert_eq!(encoded_chan_info, legacy_chan_info_with_some);
3571 // Check we can decode legacy ChannelInfo, even if the `two_to_one` / `one_to_two` /
3572 // `last_update_message` fields fail to decode due to missing htlc_maximum_msat.
3573 let legacy_chan_info_with_some_and_fail_update = <Vec<u8>>::from_hex("fd01ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce8804b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f4240000027100000001406210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2308b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f424000002710000000140a01000c0100").unwrap();
3574 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_some_and_fail_update.as_slice()).unwrap();
3575 assert_eq!(read_chan_info.announcement_received_time, 87654);
3576 assert_eq!(read_chan_info.one_to_two, None);
3577 assert_eq!(read_chan_info.two_to_one, None);
3579 let legacy_chan_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("ba00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88042e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23082e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3580 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_none.as_slice()).unwrap();
3581 assert_eq!(read_chan_info.announcement_received_time, 87654);
3582 assert_eq!(read_chan_info.one_to_two, None);
3583 assert_eq!(read_chan_info.two_to_one, None);
3587 fn node_info_is_readable() {
3588 // 1. Check we can read a valid NodeAnnouncementInfo and fail on an invalid one
3589 let announcement_message = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000122013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010000701fffefdfc2607").unwrap();
3590 let announcement_message = NodeAnnouncement::read(&mut announcement_message.as_slice()).unwrap();
3591 let valid_node_ann_info = NodeAnnouncementInfo::Relayed(announcement_message);
3593 let mut encoded_valid_node_ann_info = Vec::new();
3594 assert!(valid_node_ann_info.write(&mut encoded_valid_node_ann_info).is_ok());
3595 let read_valid_node_ann_info = NodeAnnouncementInfo::read(&mut encoded_valid_node_ann_info.as_slice()).unwrap();
3596 assert_eq!(read_valid_node_ann_info, valid_node_ann_info);
3597 assert_eq!(read_valid_node_ann_info.addresses().len(), 1);
3599 let encoded_invalid_node_ann_info = <Vec<u8>>::from_hex("3f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d2").unwrap();
3600 let read_invalid_node_ann_info_res = NodeAnnouncementInfo::read(&mut encoded_invalid_node_ann_info.as_slice());
3601 assert!(read_invalid_node_ann_info_res.is_err());
3603 // 2. Check we can read a NodeInfo anyways, but set the NodeAnnouncementInfo to None if invalid
3604 let valid_node_info = NodeInfo {
3605 channels: Vec::new(),
3606 announcement_info: Some(valid_node_ann_info),
3609 let mut encoded_valid_node_info = Vec::new();
3610 assert!(valid_node_info.write(&mut encoded_valid_node_info).is_ok());
3611 let read_valid_node_info = NodeInfo::read(&mut encoded_valid_node_info.as_slice()).unwrap();
3612 assert_eq!(read_valid_node_info, valid_node_info);
3614 let encoded_invalid_node_info_hex = <Vec<u8>>::from_hex("4402403f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d20400").unwrap();
3615 let read_invalid_node_info = NodeInfo::read(&mut encoded_invalid_node_info_hex.as_slice()).unwrap();
3616 assert_eq!(read_invalid_node_info.announcement_info, None);
3620 fn test_node_info_keeps_compatibility() {
3621 let old_ann_info_with_addresses = <Vec<u8>>::from_hex("3f0009000708a000080a51220204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014104d2").unwrap();
3622 let ann_info_with_addresses = NodeAnnouncementInfo::read(&mut old_ann_info_with_addresses.as_slice())
3623 .expect("to be able to read an old NodeAnnouncementInfo with addresses");
3624 // This serialized info has no announcement_message but its address field should still be considered
3625 assert!(!ann_info_with_addresses.addresses().is_empty());
3629 fn test_node_id_display() {
3630 let node_id = NodeId([42; 33]);
3631 assert_eq!(format!("{}", &node_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
3635 fn is_tor_only_node() {
3636 let network_graph = create_network_graph();
3637 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3639 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3640 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3641 let node_1_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
3643 let announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3644 gossip_sync.handle_channel_announcement(&announcement).unwrap();
3646 let tcp_ip_v4 = SocketAddress::TcpIpV4 {
3647 addr: [255, 254, 253, 252],
3650 let tcp_ip_v6 = SocketAddress::TcpIpV6 {
3651 addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
3654 let onion_v2 = SocketAddress::OnionV2([255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]);
3655 let onion_v3 = SocketAddress::OnionV3 {
3656 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],
3661 let hostname = SocketAddress::Hostname {
3662 hostname: Hostname::try_from(String::from("host")).unwrap(),
3666 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3668 let announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3669 gossip_sync.handle_node_announcement(&announcement).unwrap();
3670 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3672 let announcement = get_signed_node_announcement(
3674 announcement.addresses = vec![
3675 tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone(),
3678 announcement.timestamp += 1000;
3680 node_1_privkey, &secp_ctx
3682 gossip_sync.handle_node_announcement(&announcement).unwrap();
3683 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3685 let announcement = get_signed_node_announcement(
3687 announcement.addresses = vec![
3688 tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3690 announcement.timestamp += 2000;
3692 node_1_privkey, &secp_ctx
3694 gossip_sync.handle_node_announcement(&announcement).unwrap();
3695 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3697 let announcement = get_signed_node_announcement(
3699 announcement.addresses = vec![
3700 tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3702 announcement.timestamp += 3000;
3704 node_1_privkey, &secp_ctx
3706 gossip_sync.handle_node_announcement(&announcement).unwrap();
3707 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3709 let announcement = get_signed_node_announcement(
3711 announcement.addresses = vec![onion_v2.clone(), onion_v3.clone()];
3712 announcement.timestamp += 4000;
3714 node_1_privkey, &secp_ctx
3716 gossip_sync.handle_node_announcement(&announcement).unwrap();
3717 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3719 let announcement = get_signed_node_announcement(
3721 announcement.addresses = vec![onion_v2.clone()];
3722 announcement.timestamp += 5000;
3724 node_1_privkey, &secp_ctx
3726 gossip_sync.handle_node_announcement(&announcement).unwrap();
3727 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3729 let announcement = get_signed_node_announcement(
3731 announcement.addresses = vec![tcp_ip_v4.clone()];
3732 announcement.timestamp += 6000;
3734 node_1_privkey, &secp_ctx
3736 gossip_sync.handle_node_announcement(&announcement).unwrap();
3737 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3745 use criterion::{black_box, Criterion};
3747 pub fn read_network_graph(bench: &mut Criterion) {
3748 let logger = crate::util::test_utils::TestLogger::new();
3749 let (mut d, _) = crate::routing::router::bench_utils::get_graph_scorer_file().unwrap();
3750 let mut v = Vec::new();
3751 d.read_to_end(&mut v).unwrap();
3752 bench.bench_function("read_network_graph", |b| b.iter(||
3753 NetworkGraph::read(&mut std::io::Cursor::new(black_box(&v)), &logger).unwrap()
3757 pub fn write_network_graph(bench: &mut Criterion) {
3758 let logger = crate::util::test_utils::TestLogger::new();
3759 let (mut d, _) = crate::routing::router::bench_utils::get_graph_scorer_file().unwrap();
3760 let net_graph = NetworkGraph::read(&mut d, &logger).unwrap();
3761 bench.bench_function("write_network_graph", |b| b.iter(||
3762 black_box(&net_graph).encode()