1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The [`NetworkGraph`] stores the network gossip and [`P2PGossipSync`] fetches it from peers
12 use bitcoin::blockdata::constants::ChainHash;
14 use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
15 use bitcoin::secp256k1::{PublicKey, Verification};
16 use bitcoin::secp256k1::Secp256k1;
17 use bitcoin::secp256k1;
19 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
20 use bitcoin::hashes::Hash;
21 use bitcoin::hashes::hex::FromHex;
23 use bitcoin::network::constants::Network;
25 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
26 use crate::ln::ChannelId;
27 use crate::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
28 use crate::ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, SocketAddress, MAX_VALUE_MSAT};
29 use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, GossipTimestampFilter};
30 use crate::ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
32 use crate::routing::utxo::{self, UtxoLookup, UtxoResolver};
33 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, MaybeReadable};
34 use crate::util::logger::{Logger, Level};
35 use crate::util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
36 use crate::util::string::PrintableString;
37 use crate::util::indexed_map::{IndexedMap, Entry as IndexedMapEntry};
40 use crate::io_extras::{copy, sink};
41 use crate::prelude::*;
43 use core::convert::TryFrom;
44 use crate::sync::{RwLock, RwLockReadGuard, LockTestExt};
45 #[cfg(feature = "std")]
46 use core::sync::atomic::{AtomicUsize, Ordering};
47 use crate::sync::Mutex;
48 use core::ops::{Bound, Deref};
49 use core::str::FromStr;
51 #[cfg(feature = "std")]
52 use std::time::{SystemTime, UNIX_EPOCH};
54 /// We remove stale channel directional info two weeks after the last update, per BOLT 7's
56 const STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14;
58 /// We stop tracking the removal of permanently failed nodes and channels one week after removal
59 const REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 7;
61 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
62 /// refuse to relay the message.
63 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
65 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
66 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
67 const MAX_SCIDS_PER_REPLY: usize = 8000;
69 /// Represents the compressed public key of a node
70 #[derive(Clone, Copy)]
71 pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
74 /// Create a new NodeId from a public key
75 pub fn from_pubkey(pubkey: &PublicKey) -> Self {
76 NodeId(pubkey.serialize())
79 /// Get the public key slice from this NodeId
80 pub fn as_slice(&self) -> &[u8] {
84 /// Get the public key from this NodeId
85 pub fn as_pubkey(&self) -> Result<PublicKey, secp256k1::Error> {
86 PublicKey::from_slice(&self.0)
90 impl fmt::Debug for NodeId {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 write!(f, "NodeId({})", crate::util::logger::DebugBytes(&self.0))
95 impl fmt::Display for NodeId {
96 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97 crate::util::logger::DebugBytes(&self.0).fmt(f)
101 impl core::hash::Hash for NodeId {
102 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
107 impl Eq for NodeId {}
109 impl PartialEq for NodeId {
110 fn eq(&self, other: &Self) -> bool {
111 self.0[..] == other.0[..]
115 impl cmp::PartialOrd for NodeId {
116 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
117 Some(self.cmp(other))
121 impl Ord for NodeId {
122 fn cmp(&self, other: &Self) -> cmp::Ordering {
123 self.0[..].cmp(&other.0[..])
127 impl Writeable for NodeId {
128 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
129 writer.write_all(&self.0)?;
134 impl Readable for NodeId {
135 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
136 let mut buf = [0; PUBLIC_KEY_SIZE];
137 reader.read_exact(&mut buf)?;
142 impl From<PublicKey> for NodeId {
143 fn from(pubkey: PublicKey) -> Self {
144 Self::from_pubkey(&pubkey)
148 impl TryFrom<NodeId> for PublicKey {
149 type Error = secp256k1::Error;
151 fn try_from(node_id: NodeId) -> Result<Self, Self::Error> {
156 impl FromStr for NodeId {
157 type Err = bitcoin::hashes::hex::Error;
159 fn from_str(s: &str) -> Result<Self, Self::Err> {
160 let data: [u8; PUBLIC_KEY_SIZE] = FromHex::from_hex(s)?;
165 /// Represents the network as nodes and channels between them
166 pub struct NetworkGraph<L: Deref> where L::Target: Logger {
167 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
168 last_rapid_gossip_sync_timestamp: Mutex<Option<u32>>,
169 chain_hash: ChainHash,
171 // Lock order: channels -> nodes
172 channels: RwLock<IndexedMap<u64, ChannelInfo>>,
173 nodes: RwLock<IndexedMap<NodeId, NodeInfo>>,
174 // Lock order: removed_channels -> removed_nodes
176 // NOTE: In the following `removed_*` maps, we use seconds since UNIX epoch to track time instead
177 // of `std::time::Instant`s for a few reasons:
178 // * We want it to be possible to do tracking in no-std environments where we can compare
179 // a provided current UNIX timestamp with the time at which we started tracking.
180 // * In the future, if we decide to persist these maps, they will already be serializable.
181 // * Although we lose out on the platform's monotonic clock, the system clock in a std
182 // environment should be practical over the time period we are considering (on the order of a
185 /// Keeps track of short channel IDs for channels we have explicitly removed due to permanent
186 /// failure so that we don't resync them from gossip. Each SCID is mapped to the time (in seconds)
187 /// it was removed so that once some time passes, we can potentially resync it from gossip again.
188 removed_channels: Mutex<HashMap<u64, Option<u64>>>,
189 /// Keeps track of `NodeId`s we have explicitly removed due to permanent failure so that we don't
190 /// resync them from gossip. Each `NodeId` is mapped to the time (in seconds) it was removed so
191 /// that once some time passes, we can potentially resync it from gossip again.
192 removed_nodes: Mutex<HashMap<NodeId, Option<u64>>>,
193 /// Announcement messages which are awaiting an on-chain lookup to be processed.
194 pub(super) pending_checks: utxo::PendingChecks,
197 /// A read-only view of [`NetworkGraph`].
198 pub struct ReadOnlyNetworkGraph<'a> {
199 channels: RwLockReadGuard<'a, IndexedMap<u64, ChannelInfo>>,
200 nodes: RwLockReadGuard<'a, IndexedMap<NodeId, NodeInfo>>,
203 /// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
204 /// return packet by a node along the route. See [BOLT #4] for details.
206 /// [BOLT #4]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md
207 #[derive(Clone, Debug, PartialEq, Eq)]
208 pub enum NetworkUpdate {
209 /// An error indicating a `channel_update` messages should be applied via
210 /// [`NetworkGraph::update_channel`].
211 ChannelUpdateMessage {
212 /// The update to apply via [`NetworkGraph::update_channel`].
215 /// An error indicating that a channel failed to route a payment, which should be applied via
216 /// [`NetworkGraph::channel_failed_permanent`] if permanent.
218 /// The short channel id of the closed channel.
219 short_channel_id: u64,
220 /// Whether the channel should be permanently removed or temporarily disabled until a new
221 /// `channel_update` message is received.
224 /// An error indicating that a node failed to route a payment, which should be applied via
225 /// [`NetworkGraph::node_failed_permanent`] if permanent.
227 /// The node id of the failed node.
229 /// Whether the node should be permanently removed from consideration or can be restored
230 /// when a new `channel_update` message is received.
235 impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
236 (0, ChannelUpdateMessage) => {
239 (2, ChannelFailure) => {
240 (0, short_channel_id, required),
241 (2, is_permanent, required),
243 (4, NodeFailure) => {
244 (0, node_id, required),
245 (2, is_permanent, required),
249 /// Receives and validates network updates from peers,
250 /// stores authentic and relevant data as a network graph.
251 /// This network graph is then used for routing payments.
252 /// Provides interface to help with initial routing sync by
253 /// serving historical announcements.
254 pub struct P2PGossipSync<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref>
255 where U::Target: UtxoLookup, L::Target: Logger
258 utxo_lookup: RwLock<Option<U>>,
259 #[cfg(feature = "std")]
260 full_syncs_requested: AtomicUsize,
261 pending_events: Mutex<Vec<MessageSendEvent>>,
265 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> P2PGossipSync<G, U, L>
266 where U::Target: UtxoLookup, L::Target: Logger
268 /// Creates a new tracker of the actual state of the network of channels and nodes,
269 /// assuming an existing [`NetworkGraph`].
270 /// UTXO lookup is used to make sure announced channels exist on-chain, channel data is
271 /// correct, and the announcement is signed with channel owners' keys.
272 pub fn new(network_graph: G, utxo_lookup: Option<U>, logger: L) -> Self {
275 #[cfg(feature = "std")]
276 full_syncs_requested: AtomicUsize::new(0),
277 utxo_lookup: RwLock::new(utxo_lookup),
278 pending_events: Mutex::new(vec![]),
283 /// Adds a provider used to check new announcements. Does not affect
284 /// existing announcements unless they are updated.
285 /// Add, update or remove the provider would replace the current one.
286 pub fn add_utxo_lookup(&self, utxo_lookup: Option<U>) {
287 *self.utxo_lookup.write().unwrap() = utxo_lookup;
290 /// Gets a reference to the underlying [`NetworkGraph`] which was provided in
291 /// [`P2PGossipSync::new`].
293 /// This is not exported to bindings users as bindings don't support a reference-to-a-reference yet
294 pub fn network_graph(&self) -> &G {
298 #[cfg(feature = "std")]
299 /// Returns true when a full routing table sync should be performed with a peer.
300 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
301 //TODO: Determine whether to request a full sync based on the network map.
302 const FULL_SYNCS_TO_REQUEST: usize = 5;
303 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
304 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
311 /// Used to broadcast forward gossip messages which were validated async.
313 /// Note that this will ignore events other than `Broadcast*` or messages with too much excess
315 pub(super) fn forward_gossip_msg(&self, mut ev: MessageSendEvent) {
317 MessageSendEvent::BroadcastChannelAnnouncement { msg, ref mut update_msg } => {
318 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
319 if update_msg.as_ref()
320 .map(|msg| msg.contents.excess_data.len()).unwrap_or(0) > MAX_EXCESS_BYTES_FOR_RELAY
325 MessageSendEvent::BroadcastChannelUpdate { msg } => {
326 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
328 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
329 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY ||
330 msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY ||
331 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY
338 self.pending_events.lock().unwrap().push(ev);
342 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
343 /// Handles any network updates originating from [`Event`]s.
345 /// [`Event`]: crate::events::Event
346 pub fn handle_network_update(&self, network_update: &NetworkUpdate) {
347 match *network_update {
348 NetworkUpdate::ChannelUpdateMessage { ref msg } => {
349 let short_channel_id = msg.contents.short_channel_id;
350 let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
351 let status = if is_enabled { "enabled" } else { "disabled" };
352 log_debug!(self.logger, "Updating channel with channel_update from a payment failure. Channel {} is {}.", short_channel_id, status);
353 let _ = self.update_channel(msg);
355 NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } => {
357 log_debug!(self.logger, "Removing channel graph entry for {} due to a payment failure.", short_channel_id);
358 self.channel_failed_permanent(short_channel_id);
361 NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
363 log_debug!(self.logger,
364 "Removed node graph entry for {} due to a payment failure.", log_pubkey!(node_id));
365 self.node_failed_permanent(node_id);
371 /// Gets the chain hash for this network graph.
372 pub fn get_chain_hash(&self) -> ChainHash {
377 macro_rules! secp_verify_sig {
378 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr, $msg_type: expr ) => {
379 match $secp_ctx.verify_ecdsa($msg, $sig, $pubkey) {
382 return Err(LightningError {
383 err: format!("Invalid signature on {} message", $msg_type),
384 action: ErrorAction::SendWarningMessage {
385 msg: msgs::WarningMessage {
386 channel_id: ChannelId::new_zero(),
387 data: format!("Invalid signature on {} message", $msg_type),
389 log_level: Level::Trace,
397 macro_rules! get_pubkey_from_node_id {
398 ( $node_id: expr, $msg_type: expr ) => {
399 PublicKey::from_slice($node_id.as_slice())
400 .map_err(|_| LightningError {
401 err: format!("Invalid public key on {} message", $msg_type),
402 action: ErrorAction::SendWarningMessage {
403 msg: msgs::WarningMessage {
404 channel_id: ChannelId::new_zero(),
405 data: format!("Invalid public key on {} message", $msg_type),
407 log_level: Level::Trace
413 /// Verifies the signature of a [`NodeAnnouncement`].
415 /// Returns an error if it is invalid.
416 pub fn verify_node_announcement<C: Verification>(msg: &NodeAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
417 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
418 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &get_pubkey_from_node_id!(msg.contents.node_id, "node_announcement"), "node_announcement");
423 /// Verifies all signatures included in a [`ChannelAnnouncement`].
425 /// Returns an error if one of the signatures is invalid.
426 pub fn verify_channel_announcement<C: Verification>(msg: &ChannelAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
427 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
428 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");
429 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");
430 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");
431 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");
436 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> RoutingMessageHandler for P2PGossipSync<G, U, L>
437 where U::Target: UtxoLookup, L::Target: Logger
439 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
440 self.network_graph.update_node_from_announcement(msg)?;
441 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
442 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
443 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
446 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
447 self.network_graph.update_channel_from_announcement(msg, &*self.utxo_lookup.read().unwrap())?;
448 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
451 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
452 self.network_graph.update_channel(msg)?;
453 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
456 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
457 let mut channels = self.network_graph.channels.write().unwrap();
458 for (_, ref chan) in channels.range(starting_point..) {
459 if chan.announcement_message.is_some() {
460 let chan_announcement = chan.announcement_message.clone().unwrap();
461 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
462 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
463 if let Some(one_to_two) = chan.one_to_two.as_ref() {
464 one_to_two_announcement = one_to_two.last_update_message.clone();
466 if let Some(two_to_one) = chan.two_to_one.as_ref() {
467 two_to_one_announcement = two_to_one.last_update_message.clone();
469 return Some((chan_announcement, one_to_two_announcement, two_to_one_announcement));
471 // TODO: We may end up sending un-announced channel_updates if we are sending
472 // initial sync data while receiving announce/updates for this channel.
478 fn get_next_node_announcement(&self, starting_point: Option<&NodeId>) -> Option<NodeAnnouncement> {
479 let mut nodes = self.network_graph.nodes.write().unwrap();
480 let iter = if let Some(node_id) = starting_point {
481 nodes.range((Bound::Excluded(node_id), Bound::Unbounded))
485 for (_, ref node) in iter {
486 if let Some(node_info) = node.announcement_info.as_ref() {
487 if let Some(msg) = node_info.announcement_message.clone() {
495 /// Initiates a stateless sync of routing gossip information with a peer
496 /// using [`gossip_queries`]. The default strategy used by this implementation
497 /// is to sync the full block range with several peers.
499 /// We should expect one or more [`reply_channel_range`] messages in response
500 /// to our [`query_channel_range`]. Each reply will enqueue a [`query_scid`] message
501 /// to request gossip messages for each channel. The sync is considered complete
502 /// when the final [`reply_scids_end`] message is received, though we are not
503 /// tracking this directly.
505 /// [`gossip_queries`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#query-messages
506 /// [`reply_channel_range`]: msgs::ReplyChannelRange
507 /// [`query_channel_range`]: msgs::QueryChannelRange
508 /// [`query_scid`]: msgs::QueryShortChannelIds
509 /// [`reply_scids_end`]: msgs::ReplyShortChannelIdsEnd
510 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &Init, _inbound: bool) -> Result<(), ()> {
511 // We will only perform a sync with peers that support gossip_queries.
512 if !init_msg.features.supports_gossip_queries() {
513 // Don't disconnect peers for not supporting gossip queries. We may wish to have
514 // channels with peers even without being able to exchange gossip.
518 // The lightning network's gossip sync system is completely broken in numerous ways.
520 // Given no broadly-available set-reconciliation protocol, the only reasonable approach is
521 // to do a full sync from the first few peers we connect to, and then receive gossip
522 // updates from all our peers normally.
524 // Originally, we could simply tell a peer to dump us the entire gossip table on startup,
525 // wasting lots of bandwidth but ensuring we have the full network graph. After the initial
526 // dump peers would always send gossip and we'd stay up-to-date with whatever our peer has
529 // In order to reduce the bandwidth waste, "gossip queries" were introduced, allowing you
530 // to ask for the SCIDs of all channels in your peer's routing graph, and then only request
531 // channel data which you are missing. Except there was no way at all to identify which
532 // `channel_update`s you were missing, so you still had to request everything, just in a
533 // very complicated way with some queries instead of just getting the dump.
535 // Later, an option was added to fetch the latest timestamps of the `channel_update`s to
536 // make efficient sync possible, however it has yet to be implemented in lnd, which makes
537 // relying on it useless.
539 // After gossip queries were introduced, support for receiving a full gossip table dump on
540 // connection was removed from several nodes, making it impossible to get a full sync
541 // without using the "gossip queries" messages.
543 // Once you opt into "gossip queries" the only way to receive any gossip updates that a
544 // peer receives after you connect, you must send a `gossip_timestamp_filter` message. This
545 // message, as the name implies, tells the peer to not forward any gossip messages with a
546 // timestamp older than a given value (not the time the peer received the filter, but the
547 // timestamp in the update message, which is often hours behind when the peer received the
550 // Obnoxiously, `gossip_timestamp_filter` isn't *just* a filter, but its also a request for
551 // your peer to send you the full routing graph (subject to the filter). Thus, in order to
552 // tell a peer to send you any updates as it sees them, you have to also ask for the full
553 // routing graph to be synced. If you set a timestamp filter near the current time, peers
554 // will simply not forward any new updates they see to you which were generated some time
555 // ago (which is not uncommon). If you instead set a timestamp filter near 0 (or two weeks
556 // ago), you will always get the full routing graph from all your peers.
558 // Most lightning nodes today opt to simply turn off receiving gossip data which only
559 // propagated some time after it was generated, and, worse, often disable gossiping with
560 // several peers after their first connection. The second behavior can cause gossip to not
561 // propagate fully if there are cuts in the gossiping subgraph.
563 // In an attempt to cut a middle ground between always fetching the full graph from all of
564 // our peers and never receiving gossip from peers at all, we send all of our peers a
565 // `gossip_timestamp_filter`, with the filter time set either two weeks ago or an hour ago.
567 // For no-std builds, we bury our head in the sand and do a full sync on each connection.
568 #[allow(unused_mut, unused_assignments)]
569 let mut gossip_start_time = 0;
570 #[cfg(feature = "std")]
572 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
573 if self.should_request_full_sync(&their_node_id) {
574 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
576 gossip_start_time -= 60 * 60; // an hour ago
580 let mut pending_events = self.pending_events.lock().unwrap();
581 pending_events.push(MessageSendEvent::SendGossipTimestampFilter {
582 node_id: their_node_id.clone(),
583 msg: GossipTimestampFilter {
584 chain_hash: self.network_graph.chain_hash,
585 first_timestamp: gossip_start_time as u32, // 2106 issue!
586 timestamp_range: u32::max_value(),
592 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: ReplyChannelRange) -> Result<(), LightningError> {
593 // We don't make queries, so should never receive replies. If, in the future, the set
594 // reconciliation extensions to gossip queries become broadly supported, we should revert
595 // this code to its state pre-0.0.106.
599 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
600 // We don't make queries, so should never receive replies. If, in the future, the set
601 // reconciliation extensions to gossip queries become broadly supported, we should revert
602 // this code to its state pre-0.0.106.
606 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
607 /// are in the specified block range. Due to message size limits, large range
608 /// queries may result in several reply messages. This implementation enqueues
609 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
610 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
611 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
612 /// memory constrained systems.
613 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
614 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);
616 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
618 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
619 // If so, we manually cap the ending block to avoid this overflow.
620 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
622 // Per spec, we must reply to a query. Send an empty message when things are invalid.
623 if msg.chain_hash != self.network_graph.chain_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
624 let mut pending_events = self.pending_events.lock().unwrap();
625 pending_events.push(MessageSendEvent::SendReplyChannelRange {
626 node_id: their_node_id.clone(),
627 msg: ReplyChannelRange {
628 chain_hash: msg.chain_hash.clone(),
629 first_blocknum: msg.first_blocknum,
630 number_of_blocks: msg.number_of_blocks,
632 short_channel_ids: vec![],
635 return Err(LightningError {
636 err: String::from("query_channel_range could not be processed"),
637 action: ErrorAction::IgnoreError,
641 // Creates channel batches. We are not checking if the channel is routable
642 // (has at least one update). A peer may still want to know the channel
643 // exists even if its not yet routable.
644 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
645 let mut channels = self.network_graph.channels.write().unwrap();
646 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
647 if let Some(chan_announcement) = &chan.announcement_message {
648 // Construct a new batch if last one is full
649 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
650 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
653 let batch = batches.last_mut().unwrap();
654 batch.push(chan_announcement.contents.short_channel_id);
659 let mut pending_events = self.pending_events.lock().unwrap();
660 let batch_count = batches.len();
661 let mut prev_batch_endblock = msg.first_blocknum;
662 for (batch_index, batch) in batches.into_iter().enumerate() {
663 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
664 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
666 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
667 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
668 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
669 // significant diversion from the requirements set by the spec, and, in case of blocks
670 // with no channel opens (e.g. empty blocks), requires that we use the previous value
671 // and *not* derive the first_blocknum from the actual first block of the reply.
672 let first_blocknum = prev_batch_endblock;
674 // Each message carries the number of blocks (from the `first_blocknum`) its contents
675 // fit in. Though there is no requirement that we use exactly the number of blocks its
676 // contents are from, except for the bogus requirements c-lightning enforces, above.
678 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
679 // >= the query's end block. Thus, for the last reply, we calculate the difference
680 // between the query's end block and the start of the reply.
682 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
683 // first_blocknum will be either msg.first_blocknum or a higher block height.
684 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
685 (true, msg.end_blocknum() - first_blocknum)
687 // Prior replies should use the number of blocks that fit into the reply. Overflow
688 // safe since first_blocknum is always <= last SCID's block.
690 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
693 prev_batch_endblock = first_blocknum + number_of_blocks;
695 pending_events.push(MessageSendEvent::SendReplyChannelRange {
696 node_id: their_node_id.clone(),
697 msg: ReplyChannelRange {
698 chain_hash: msg.chain_hash.clone(),
702 short_channel_ids: batch,
710 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
713 err: String::from("Not implemented"),
714 action: ErrorAction::IgnoreError,
718 fn provided_node_features(&self) -> NodeFeatures {
719 let mut features = NodeFeatures::empty();
720 features.set_gossip_queries_optional();
724 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
725 let mut features = InitFeatures::empty();
726 features.set_gossip_queries_optional();
730 fn processing_queue_high(&self) -> bool {
731 self.network_graph.pending_checks.too_many_checks_pending()
735 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> MessageSendEventsProvider for P2PGossipSync<G, U, L>
737 U::Target: UtxoLookup,
740 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
741 let mut ret = Vec::new();
742 let mut pending_events = self.pending_events.lock().unwrap();
743 core::mem::swap(&mut ret, &mut pending_events);
748 #[derive(Clone, Debug, PartialEq, Eq)]
749 /// Details about one direction of a channel as received within a [`ChannelUpdate`].
750 pub struct ChannelUpdateInfo {
751 /// When the last update to the channel direction was issued.
752 /// Value is opaque, as set in the announcement.
753 pub last_update: u32,
754 /// Whether the channel can be currently used for payments (in this one direction).
756 /// The difference in CLTV values that you must have when routing through this channel.
757 pub cltv_expiry_delta: u16,
758 /// The minimum value, which must be relayed to the next hop via the channel
759 pub htlc_minimum_msat: u64,
760 /// The maximum value which may be relayed to the next hop via the channel.
761 pub htlc_maximum_msat: u64,
762 /// Fees charged when the channel is used for routing
763 pub fees: RoutingFees,
764 /// Most recent update for the channel received from the network
765 /// Mostly redundant with the data we store in fields explicitly.
766 /// Everything else is useful only for sending out for initial routing sync.
767 /// Not stored if contains excess data to prevent DoS.
768 pub last_update_message: Option<ChannelUpdate>,
771 impl fmt::Display for ChannelUpdateInfo {
772 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
773 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)?;
778 impl Writeable for ChannelUpdateInfo {
779 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
780 write_tlv_fields!(writer, {
781 (0, self.last_update, required),
782 (2, self.enabled, required),
783 (4, self.cltv_expiry_delta, required),
784 (6, self.htlc_minimum_msat, required),
785 // Writing htlc_maximum_msat as an Option<u64> is required to maintain backwards
786 // compatibility with LDK versions prior to v0.0.110.
787 (8, Some(self.htlc_maximum_msat), required),
788 (10, self.fees, required),
789 (12, self.last_update_message, required),
795 impl Readable for ChannelUpdateInfo {
796 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
797 _init_tlv_field_var!(last_update, required);
798 _init_tlv_field_var!(enabled, required);
799 _init_tlv_field_var!(cltv_expiry_delta, required);
800 _init_tlv_field_var!(htlc_minimum_msat, required);
801 _init_tlv_field_var!(htlc_maximum_msat, option);
802 _init_tlv_field_var!(fees, required);
803 _init_tlv_field_var!(last_update_message, required);
805 read_tlv_fields!(reader, {
806 (0, last_update, required),
807 (2, enabled, required),
808 (4, cltv_expiry_delta, required),
809 (6, htlc_minimum_msat, required),
810 (8, htlc_maximum_msat, required),
811 (10, fees, required),
812 (12, last_update_message, required)
815 if let Some(htlc_maximum_msat) = htlc_maximum_msat {
816 Ok(ChannelUpdateInfo {
817 last_update: _init_tlv_based_struct_field!(last_update, required),
818 enabled: _init_tlv_based_struct_field!(enabled, required),
819 cltv_expiry_delta: _init_tlv_based_struct_field!(cltv_expiry_delta, required),
820 htlc_minimum_msat: _init_tlv_based_struct_field!(htlc_minimum_msat, required),
822 fees: _init_tlv_based_struct_field!(fees, required),
823 last_update_message: _init_tlv_based_struct_field!(last_update_message, required),
826 Err(DecodeError::InvalidValue)
831 #[derive(Clone, Debug, PartialEq, Eq)]
832 /// Details about a channel (both directions).
833 /// Received within a channel announcement.
834 pub struct ChannelInfo {
835 /// Protocol features of a channel communicated during its announcement
836 pub features: ChannelFeatures,
837 /// Source node of the first direction of a channel
838 pub node_one: NodeId,
839 /// Details about the first direction of a channel
840 pub one_to_two: Option<ChannelUpdateInfo>,
841 /// Source node of the second direction of a channel
842 pub node_two: NodeId,
843 /// Details about the second direction of a channel
844 pub two_to_one: Option<ChannelUpdateInfo>,
845 /// The channel capacity as seen on-chain, if chain lookup is available.
846 pub capacity_sats: Option<u64>,
847 /// An initial announcement of the channel
848 /// Mostly redundant with the data we store in fields explicitly.
849 /// Everything else is useful only for sending out for initial routing sync.
850 /// Not stored if contains excess data to prevent DoS.
851 pub announcement_message: Option<ChannelAnnouncement>,
852 /// The timestamp when we received the announcement, if we are running with feature = "std"
853 /// (which we can probably assume we are - no-std environments probably won't have a full
854 /// network graph in memory!).
855 announcement_received_time: u64,
859 /// Returns a [`DirectedChannelInfo`] for the channel directed to the given `target` from a
860 /// returned `source`, or `None` if `target` is not one of the channel's counterparties.
861 pub fn as_directed_to(&self, target: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
862 let (direction, source) = {
863 if target == &self.node_one {
864 (self.two_to_one.as_ref(), &self.node_two)
865 } else if target == &self.node_two {
866 (self.one_to_two.as_ref(), &self.node_one)
871 direction.map(|dir| (DirectedChannelInfo::new(self, dir), source))
874 /// Returns a [`DirectedChannelInfo`] for the channel directed from the given `source` to a
875 /// returned `target`, or `None` if `source` is not one of the channel's counterparties.
876 pub fn as_directed_from(&self, source: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
877 let (direction, target) = {
878 if source == &self.node_one {
879 (self.one_to_two.as_ref(), &self.node_two)
880 } else if source == &self.node_two {
881 (self.two_to_one.as_ref(), &self.node_one)
886 direction.map(|dir| (DirectedChannelInfo::new(self, dir), target))
889 /// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag.
890 pub fn get_directional_info(&self, channel_flags: u8) -> Option<&ChannelUpdateInfo> {
891 let direction = channel_flags & 1u8;
893 self.one_to_two.as_ref()
895 self.two_to_one.as_ref()
900 impl fmt::Display for ChannelInfo {
901 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
902 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
903 log_bytes!(self.features.encode()), &self.node_one, self.one_to_two, &self.node_two, self.two_to_one)?;
908 impl Writeable for ChannelInfo {
909 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
910 write_tlv_fields!(writer, {
911 (0, self.features, required),
912 (1, self.announcement_received_time, (default_value, 0)),
913 (2, self.node_one, required),
914 (4, self.one_to_two, required),
915 (6, self.node_two, required),
916 (8, self.two_to_one, required),
917 (10, self.capacity_sats, required),
918 (12, self.announcement_message, required),
924 // A wrapper allowing for the optional deseralization of ChannelUpdateInfo. Utilizing this is
925 // necessary to maintain backwards compatibility with previous serializations of `ChannelUpdateInfo`
926 // that may have no `htlc_maximum_msat` field set. In case the field is absent, we simply ignore
927 // the error and continue reading the `ChannelInfo`. Hopefully, we'll then eventually receive newer
928 // channel updates via the gossip network.
929 struct ChannelUpdateInfoDeserWrapper(Option<ChannelUpdateInfo>);
931 impl MaybeReadable for ChannelUpdateInfoDeserWrapper {
932 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
933 match crate::util::ser::Readable::read(reader) {
934 Ok(channel_update_option) => Ok(Some(Self(channel_update_option))),
935 Err(DecodeError::ShortRead) => Ok(None),
936 Err(DecodeError::InvalidValue) => Ok(None),
937 Err(err) => Err(err),
942 impl Readable for ChannelInfo {
943 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
944 _init_tlv_field_var!(features, required);
945 _init_tlv_field_var!(announcement_received_time, (default_value, 0));
946 _init_tlv_field_var!(node_one, required);
947 let mut one_to_two_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
948 _init_tlv_field_var!(node_two, required);
949 let mut two_to_one_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
950 _init_tlv_field_var!(capacity_sats, required);
951 _init_tlv_field_var!(announcement_message, required);
952 read_tlv_fields!(reader, {
953 (0, features, required),
954 (1, announcement_received_time, (default_value, 0)),
955 (2, node_one, required),
956 (4, one_to_two_wrap, upgradable_option),
957 (6, node_two, required),
958 (8, two_to_one_wrap, upgradable_option),
959 (10, capacity_sats, required),
960 (12, announcement_message, required),
964 features: _init_tlv_based_struct_field!(features, required),
965 node_one: _init_tlv_based_struct_field!(node_one, required),
966 one_to_two: one_to_two_wrap.map(|w| w.0).unwrap_or(None),
967 node_two: _init_tlv_based_struct_field!(node_two, required),
968 two_to_one: two_to_one_wrap.map(|w| w.0).unwrap_or(None),
969 capacity_sats: _init_tlv_based_struct_field!(capacity_sats, required),
970 announcement_message: _init_tlv_based_struct_field!(announcement_message, required),
971 announcement_received_time: _init_tlv_based_struct_field!(announcement_received_time, (default_value, 0)),
976 /// A wrapper around [`ChannelInfo`] representing information about the channel as directed from a
977 /// source node to a target node.
979 pub struct DirectedChannelInfo<'a> {
980 channel: &'a ChannelInfo,
981 direction: &'a ChannelUpdateInfo,
982 htlc_maximum_msat: u64,
983 effective_capacity: EffectiveCapacity,
986 impl<'a> DirectedChannelInfo<'a> {
988 fn new(channel: &'a ChannelInfo, direction: &'a ChannelUpdateInfo) -> Self {
989 let mut htlc_maximum_msat = direction.htlc_maximum_msat;
990 let capacity_msat = channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000);
992 let effective_capacity = match capacity_msat {
993 Some(capacity_msat) => {
994 htlc_maximum_msat = cmp::min(htlc_maximum_msat, capacity_msat);
995 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat: htlc_maximum_msat }
997 None => EffectiveCapacity::AdvertisedMaxHTLC { amount_msat: htlc_maximum_msat },
1001 channel, direction, htlc_maximum_msat, effective_capacity
1005 /// Returns information for the channel.
1007 pub fn channel(&self) -> &'a ChannelInfo { self.channel }
1009 /// Returns the maximum HTLC amount allowed over the channel in the direction.
1011 pub fn htlc_maximum_msat(&self) -> u64 {
1012 self.htlc_maximum_msat
1015 /// Returns the [`EffectiveCapacity`] of the channel in the direction.
1017 /// This is either the total capacity from the funding transaction, if known, or the
1018 /// `htlc_maximum_msat` for the direction as advertised by the gossip network, if known,
1020 pub fn effective_capacity(&self) -> EffectiveCapacity {
1021 self.effective_capacity
1024 /// Returns information for the direction.
1026 pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.direction }
1029 impl<'a> fmt::Debug for DirectedChannelInfo<'a> {
1030 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1031 f.debug_struct("DirectedChannelInfo")
1032 .field("channel", &self.channel)
1037 /// The effective capacity of a channel for routing purposes.
1039 /// While this may be smaller than the actual channel capacity, amounts greater than
1040 /// [`Self::as_msat`] should not be routed through the channel.
1041 #[derive(Clone, Copy, Debug, PartialEq)]
1042 pub enum EffectiveCapacity {
1043 /// The available liquidity in the channel known from being a channel counterparty, and thus a
1046 /// Either the inbound or outbound liquidity depending on the direction, denominated in
1048 liquidity_msat: u64,
1050 /// The maximum HTLC amount in one direction as advertised on the gossip network.
1052 /// The maximum HTLC amount denominated in millisatoshi.
1055 /// The total capacity of the channel as determined by the funding transaction.
1057 /// The funding amount denominated in millisatoshi.
1059 /// The maximum HTLC amount denominated in millisatoshi.
1060 htlc_maximum_msat: u64
1062 /// A capacity sufficient to route any payment, typically used for private channels provided by
1065 /// The maximum HTLC amount as provided by an invoice route hint.
1067 /// The maximum HTLC amount denominated in millisatoshi.
1070 /// A capacity that is unknown possibly because either the chain state is unavailable to know
1071 /// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
1075 /// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
1076 /// use when making routing decisions.
1077 pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
1079 impl EffectiveCapacity {
1080 /// Returns the effective capacity denominated in millisatoshi.
1081 pub fn as_msat(&self) -> u64 {
1083 EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
1084 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } => *amount_msat,
1085 EffectiveCapacity::Total { capacity_msat, .. } => *capacity_msat,
1086 EffectiveCapacity::HintMaxHTLC { amount_msat } => *amount_msat,
1087 EffectiveCapacity::Infinite => u64::max_value(),
1088 EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
1093 /// Fees for routing via a given channel or a node
1094 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash, Ord, PartialOrd)]
1095 pub struct RoutingFees {
1096 /// Flat routing fee in millisatoshis.
1098 /// Liquidity-based routing fee in millionths of a routed amount.
1099 /// In other words, 10000 is 1%.
1100 pub proportional_millionths: u32,
1103 impl_writeable_tlv_based!(RoutingFees, {
1104 (0, base_msat, required),
1105 (2, proportional_millionths, required)
1108 #[derive(Clone, Debug, PartialEq, Eq)]
1109 /// Information received in the latest node_announcement from this node.
1110 pub struct NodeAnnouncementInfo {
1111 /// Protocol features the node announced support for
1112 pub features: NodeFeatures,
1113 /// When the last known update to the node state was issued.
1114 /// Value is opaque, as set in the announcement.
1115 pub last_update: u32,
1116 /// Color assigned to the node
1118 /// Moniker assigned to the node.
1119 /// May be invalid or malicious (eg control chars),
1120 /// should not be exposed to the user.
1121 pub alias: NodeAlias,
1122 /// An initial announcement of the node
1123 /// Mostly redundant with the data we store in fields explicitly.
1124 /// Everything else is useful only for sending out for initial routing sync.
1125 /// Not stored if contains excess data to prevent DoS.
1126 pub announcement_message: Option<NodeAnnouncement>
1129 impl NodeAnnouncementInfo {
1130 /// Internet-level addresses via which one can connect to the node
1131 pub fn addresses(&self) -> &[SocketAddress] {
1132 self.announcement_message.as_ref()
1133 .map(|msg| msg.contents.addresses.as_slice())
1134 .unwrap_or_default()
1138 impl Writeable for NodeAnnouncementInfo {
1139 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1140 let empty_addresses = Vec::<SocketAddress>::new();
1141 write_tlv_fields!(writer, {
1142 (0, self.features, required),
1143 (2, self.last_update, required),
1144 (4, self.rgb, required),
1145 (6, self.alias, required),
1146 (8, self.announcement_message, option),
1147 (10, empty_addresses, required_vec), // Versions prior to 0.0.115 require this field
1153 impl Readable for NodeAnnouncementInfo {
1154 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1155 _init_and_read_len_prefixed_tlv_fields!(reader, {
1156 (0, features, required),
1157 (2, last_update, required),
1159 (6, alias, required),
1160 (8, announcement_message, option),
1161 (10, _addresses, optional_vec), // deprecated, not used anymore
1163 let _: Option<Vec<SocketAddress>> = _addresses;
1164 Ok(Self { features: features.0.unwrap(), last_update: last_update.0.unwrap(), rgb: rgb.0.unwrap(),
1165 alias: alias.0.unwrap(), announcement_message })
1169 /// A user-defined name for a node, which may be used when displaying the node in a graph.
1171 /// Since node aliases are provided by third parties, they are a potential avenue for injection
1172 /// attacks. Care must be taken when processing.
1173 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1174 pub struct NodeAlias(pub [u8; 32]);
1176 impl fmt::Display for NodeAlias {
1177 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1178 let first_null = self.0.iter().position(|b| *b == 0).unwrap_or(self.0.len());
1179 let bytes = self.0.split_at(first_null).0;
1180 match core::str::from_utf8(bytes) {
1181 Ok(alias) => PrintableString(alias).fmt(f)?,
1183 use core::fmt::Write;
1184 for c in bytes.iter().map(|b| *b as char) {
1185 // Display printable ASCII characters
1186 let control_symbol = core::char::REPLACEMENT_CHARACTER;
1187 let c = if c >= '\x20' && c <= '\x7e' { c } else { control_symbol };
1196 impl Writeable for NodeAlias {
1197 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1202 impl Readable for NodeAlias {
1203 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
1204 Ok(NodeAlias(Readable::read(r)?))
1208 #[derive(Clone, Debug, PartialEq, Eq)]
1209 /// Details about a node in the network, known from the network announcement.
1210 pub struct NodeInfo {
1211 /// All valid channels a node has announced
1212 pub channels: Vec<u64>,
1213 /// More information about a node from node_announcement.
1214 /// Optional because we store a Node entry after learning about it from
1215 /// a channel announcement, but before receiving a node announcement.
1216 pub announcement_info: Option<NodeAnnouncementInfo>
1219 impl fmt::Display for NodeInfo {
1220 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1221 write!(f, " channels: {:?}, announcement_info: {:?}",
1222 &self.channels[..], self.announcement_info)?;
1227 impl Writeable for NodeInfo {
1228 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1229 write_tlv_fields!(writer, {
1230 // Note that older versions of LDK wrote the lowest inbound fees here at type 0
1231 (2, self.announcement_info, option),
1232 (4, self.channels, required_vec),
1238 // A wrapper allowing for the optional deserialization of `NodeAnnouncementInfo`. Utilizing this is
1239 // necessary to maintain compatibility with previous serializations of `SocketAddress` that have an
1240 // invalid hostname set. We ignore and eat all errors until we are either able to read a
1241 // `NodeAnnouncementInfo` or hit a `ShortRead`, i.e., read the TLV field to the end.
1242 struct NodeAnnouncementInfoDeserWrapper(NodeAnnouncementInfo);
1244 impl MaybeReadable for NodeAnnouncementInfoDeserWrapper {
1245 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
1246 match crate::util::ser::Readable::read(reader) {
1247 Ok(node_announcement_info) => return Ok(Some(Self(node_announcement_info))),
1249 copy(reader, &mut sink()).unwrap();
1256 impl Readable for NodeInfo {
1257 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1258 // Historically, we tracked the lowest inbound fees for any node in order to use it as an
1259 // A* heuristic when routing. Sadly, these days many, many nodes have at least one channel
1260 // with zero inbound fees, causing that heuristic to provide little gain. Worse, because it
1261 // requires additional complexity and lookups during routing, it ends up being a
1262 // performance loss. Thus, we simply ignore the old field here and no longer track it.
1263 _init_and_read_len_prefixed_tlv_fields!(reader, {
1264 (0, _lowest_inbound_channel_fees, option),
1265 (2, announcement_info_wrap, upgradable_option),
1266 (4, channels, required_vec),
1268 let _: Option<RoutingFees> = _lowest_inbound_channel_fees;
1269 let announcement_info_wrap: Option<NodeAnnouncementInfoDeserWrapper> = announcement_info_wrap;
1272 announcement_info: announcement_info_wrap.map(|w| w.0),
1278 const SERIALIZATION_VERSION: u8 = 1;
1279 const MIN_SERIALIZATION_VERSION: u8 = 1;
1281 impl<L: Deref> Writeable for NetworkGraph<L> where L::Target: Logger {
1282 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1283 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1285 self.chain_hash.write(writer)?;
1286 let channels = self.channels.read().unwrap();
1287 (channels.len() as u64).write(writer)?;
1288 for (ref chan_id, ref chan_info) in channels.unordered_iter() {
1289 (*chan_id).write(writer)?;
1290 chan_info.write(writer)?;
1292 let nodes = self.nodes.read().unwrap();
1293 (nodes.len() as u64).write(writer)?;
1294 for (ref node_id, ref node_info) in nodes.unordered_iter() {
1295 node_id.write(writer)?;
1296 node_info.write(writer)?;
1299 let last_rapid_gossip_sync_timestamp = self.get_last_rapid_gossip_sync_timestamp();
1300 write_tlv_fields!(writer, {
1301 (1, last_rapid_gossip_sync_timestamp, option),
1307 impl<L: Deref> ReadableArgs<L> for NetworkGraph<L> where L::Target: Logger {
1308 fn read<R: io::Read>(reader: &mut R, logger: L) -> Result<NetworkGraph<L>, DecodeError> {
1309 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1311 let chain_hash: ChainHash = Readable::read(reader)?;
1312 let channels_count: u64 = Readable::read(reader)?;
1313 let mut channels = IndexedMap::new();
1314 for _ in 0..channels_count {
1315 let chan_id: u64 = Readable::read(reader)?;
1316 let chan_info = Readable::read(reader)?;
1317 channels.insert(chan_id, chan_info);
1319 let nodes_count: u64 = Readable::read(reader)?;
1320 let mut nodes = IndexedMap::new();
1321 for _ in 0..nodes_count {
1322 let node_id = Readable::read(reader)?;
1323 let node_info = Readable::read(reader)?;
1324 nodes.insert(node_id, node_info);
1327 let mut last_rapid_gossip_sync_timestamp: Option<u32> = None;
1328 read_tlv_fields!(reader, {
1329 (1, last_rapid_gossip_sync_timestamp, option),
1333 secp_ctx: Secp256k1::verification_only(),
1336 channels: RwLock::new(channels),
1337 nodes: RwLock::new(nodes),
1338 last_rapid_gossip_sync_timestamp: Mutex::new(last_rapid_gossip_sync_timestamp),
1339 removed_nodes: Mutex::new(HashMap::new()),
1340 removed_channels: Mutex::new(HashMap::new()),
1341 pending_checks: utxo::PendingChecks::new(),
1346 impl<L: Deref> fmt::Display for NetworkGraph<L> where L::Target: Logger {
1347 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1348 writeln!(f, "Network map\n[Channels]")?;
1349 for (key, val) in self.channels.read().unwrap().unordered_iter() {
1350 writeln!(f, " {}: {}", key, val)?;
1352 writeln!(f, "[Nodes]")?;
1353 for (&node_id, val) in self.nodes.read().unwrap().unordered_iter() {
1354 writeln!(f, " {}: {}", &node_id, val)?;
1360 impl<L: Deref> Eq for NetworkGraph<L> where L::Target: Logger {}
1361 impl<L: Deref> PartialEq for NetworkGraph<L> where L::Target: Logger {
1362 fn eq(&self, other: &Self) -> bool {
1363 // For a total lockorder, sort by position in memory and take the inner locks in that order.
1364 // (Assumes that we can't move within memory while a lock is held).
1365 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1366 let a = if ord { (&self.channels, &self.nodes) } else { (&other.channels, &other.nodes) };
1367 let b = if ord { (&other.channels, &other.nodes) } else { (&self.channels, &self.nodes) };
1368 let (channels_a, channels_b) = (a.0.unsafe_well_ordered_double_lock_self(), b.0.unsafe_well_ordered_double_lock_self());
1369 let (nodes_a, nodes_b) = (a.1.unsafe_well_ordered_double_lock_self(), b.1.unsafe_well_ordered_double_lock_self());
1370 self.chain_hash.eq(&other.chain_hash) && channels_a.eq(&channels_b) && nodes_a.eq(&nodes_b)
1374 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
1375 /// Creates a new, empty, network graph.
1376 pub fn new(network: Network, logger: L) -> NetworkGraph<L> {
1378 secp_ctx: Secp256k1::verification_only(),
1379 chain_hash: ChainHash::using_genesis_block(network),
1381 channels: RwLock::new(IndexedMap::new()),
1382 nodes: RwLock::new(IndexedMap::new()),
1383 last_rapid_gossip_sync_timestamp: Mutex::new(None),
1384 removed_channels: Mutex::new(HashMap::new()),
1385 removed_nodes: Mutex::new(HashMap::new()),
1386 pending_checks: utxo::PendingChecks::new(),
1390 /// Returns a read-only view of the network graph.
1391 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
1392 let channels = self.channels.read().unwrap();
1393 let nodes = self.nodes.read().unwrap();
1394 ReadOnlyNetworkGraph {
1400 /// The unix timestamp provided by the most recent rapid gossip sync.
1401 /// It will be set by the rapid sync process after every sync completion.
1402 pub fn get_last_rapid_gossip_sync_timestamp(&self) -> Option<u32> {
1403 self.last_rapid_gossip_sync_timestamp.lock().unwrap().clone()
1406 /// Update the unix timestamp provided by the most recent rapid gossip sync.
1407 /// This should be done automatically by the rapid sync process after every sync completion.
1408 pub fn set_last_rapid_gossip_sync_timestamp(&self, last_rapid_gossip_sync_timestamp: u32) {
1409 self.last_rapid_gossip_sync_timestamp.lock().unwrap().replace(last_rapid_gossip_sync_timestamp);
1412 /// Clears the `NodeAnnouncementInfo` field for all nodes in the `NetworkGraph` for testing
1415 pub fn clear_nodes_announcement_info(&self) {
1416 for node in self.nodes.write().unwrap().unordered_iter_mut() {
1417 node.1.announcement_info = None;
1421 /// For an already known node (from channel announcements), update its stored properties from a
1422 /// given node announcement.
1424 /// You probably don't want to call this directly, instead relying on a P2PGossipSync's
1425 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1426 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1427 pub fn update_node_from_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), LightningError> {
1428 verify_node_announcement(msg, &self.secp_ctx)?;
1429 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1432 /// For an already known node (from channel announcements), update its stored properties from a
1433 /// given node announcement without verifying the associated signatures. Because we aren't
1434 /// given the associated signatures here we cannot relay the node announcement to any of our
1436 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1437 self.update_node_from_announcement_intern(msg, None)
1440 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1441 let mut nodes = self.nodes.write().unwrap();
1442 match nodes.get_mut(&msg.node_id) {
1444 core::mem::drop(nodes);
1445 self.pending_checks.check_hold_pending_node_announcement(msg, full_msg)?;
1446 Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError})
1449 if let Some(node_info) = node.announcement_info.as_ref() {
1450 // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
1451 // updates to ensure you always have the latest one, only vaguely suggesting
1452 // that it be at least the current time.
1453 if node_info.last_update > msg.timestamp {
1454 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1455 } else if node_info.last_update == msg.timestamp {
1456 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1461 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1462 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1463 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1464 node.announcement_info = Some(NodeAnnouncementInfo {
1465 features: msg.features.clone(),
1466 last_update: msg.timestamp,
1469 announcement_message: if should_relay { full_msg.cloned() } else { None },
1477 /// Store or update channel info from a channel announcement.
1479 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1480 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1481 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1483 /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1484 /// the corresponding UTXO exists on chain and is correctly-formatted.
1485 pub fn update_channel_from_announcement<U: Deref>(
1486 &self, msg: &msgs::ChannelAnnouncement, utxo_lookup: &Option<U>,
1487 ) -> Result<(), LightningError>
1489 U::Target: UtxoLookup,
1491 verify_channel_announcement(msg, &self.secp_ctx)?;
1492 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), utxo_lookup)
1495 /// Store or update channel info from a channel announcement.
1497 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1498 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1499 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1501 /// This will skip verification of if the channel is actually on-chain.
1502 pub fn update_channel_from_announcement_no_lookup(
1503 &self, msg: &ChannelAnnouncement
1504 ) -> Result<(), LightningError> {
1505 self.update_channel_from_announcement::<&UtxoResolver>(msg, &None)
1508 /// Store or update channel info from a channel announcement without verifying the associated
1509 /// signatures. Because we aren't given the associated signatures here we cannot relay the
1510 /// channel announcement to any of our peers.
1512 /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1513 /// the corresponding UTXO exists on chain and is correctly-formatted.
1514 pub fn update_channel_from_unsigned_announcement<U: Deref>(
1515 &self, msg: &msgs::UnsignedChannelAnnouncement, utxo_lookup: &Option<U>
1516 ) -> Result<(), LightningError>
1518 U::Target: UtxoLookup,
1520 self.update_channel_from_unsigned_announcement_intern(msg, None, utxo_lookup)
1523 /// Update channel from partial announcement data received via rapid gossip sync
1525 /// `timestamp: u64`: Timestamp emulating the backdated original announcement receipt (by the
1526 /// rapid gossip sync server)
1528 /// All other parameters as used in [`msgs::UnsignedChannelAnnouncement`] fields.
1529 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> {
1530 if node_id_1 == node_id_2 {
1531 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1534 let node_1 = NodeId::from_pubkey(&node_id_1);
1535 let node_2 = NodeId::from_pubkey(&node_id_2);
1536 let channel_info = ChannelInfo {
1538 node_one: node_1.clone(),
1540 node_two: node_2.clone(),
1542 capacity_sats: None,
1543 announcement_message: None,
1544 announcement_received_time: timestamp,
1547 self.add_channel_between_nodes(short_channel_id, channel_info, None)
1550 fn add_channel_between_nodes(&self, short_channel_id: u64, channel_info: ChannelInfo, utxo_value: Option<u64>) -> Result<(), LightningError> {
1551 let mut channels = self.channels.write().unwrap();
1552 let mut nodes = self.nodes.write().unwrap();
1554 let node_id_a = channel_info.node_one.clone();
1555 let node_id_b = channel_info.node_two.clone();
1557 log_gossip!(self.logger, "Adding channel {} between nodes {} and {}", short_channel_id, node_id_a, node_id_b);
1559 match channels.entry(short_channel_id) {
1560 IndexedMapEntry::Occupied(mut entry) => {
1561 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1562 //in the blockchain API, we need to handle it smartly here, though it's unclear
1564 if utxo_value.is_some() {
1565 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1566 // only sometimes returns results. In any case remove the previous entry. Note
1567 // that the spec expects us to "blacklist" the node_ids involved, but we can't
1569 // a) we don't *require* a UTXO provider that always returns results.
1570 // b) we don't track UTXOs of channels we know about and remove them if they
1572 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1573 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), short_channel_id);
1574 *entry.get_mut() = channel_info;
1576 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1579 IndexedMapEntry::Vacant(entry) => {
1580 entry.insert(channel_info);
1584 for current_node_id in [node_id_a, node_id_b].iter() {
1585 match nodes.entry(current_node_id.clone()) {
1586 IndexedMapEntry::Occupied(node_entry) => {
1587 node_entry.into_mut().channels.push(short_channel_id);
1589 IndexedMapEntry::Vacant(node_entry) => {
1590 node_entry.insert(NodeInfo {
1591 channels: vec!(short_channel_id),
1592 announcement_info: None,
1601 fn update_channel_from_unsigned_announcement_intern<U: Deref>(
1602 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, utxo_lookup: &Option<U>
1603 ) -> Result<(), LightningError>
1605 U::Target: UtxoLookup,
1607 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1608 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1611 if msg.chain_hash != self.chain_hash {
1612 return Err(LightningError {
1613 err: "Channel announcement chain hash does not match genesis hash".to_owned(),
1614 action: ErrorAction::IgnoreAndLog(Level::Debug),
1619 let channels = self.channels.read().unwrap();
1621 if let Some(chan) = channels.get(&msg.short_channel_id) {
1622 if chan.capacity_sats.is_some() {
1623 // If we'd previously looked up the channel on-chain and checked the script
1624 // against what appears on-chain, ignore the duplicate announcement.
1626 // Because a reorg could replace one channel with another at the same SCID, if
1627 // the channel appears to be different, we re-validate. This doesn't expose us
1628 // to any more DoS risk than not, as a peer can always flood us with
1629 // randomly-generated SCID values anyway.
1631 // We use the Node IDs rather than the bitcoin_keys to check for "equivalence"
1632 // as we didn't (necessarily) store the bitcoin keys, and we only really care
1633 // if the peers on the channel changed anyway.
1634 if msg.node_id_1 == chan.node_one && msg.node_id_2 == chan.node_two {
1635 return Err(LightningError {
1636 err: "Already have chain-validated channel".to_owned(),
1637 action: ErrorAction::IgnoreDuplicateGossip
1640 } else if utxo_lookup.is_none() {
1641 // Similarly, if we can't check the chain right now anyway, ignore the
1642 // duplicate announcement without bothering to take the channels write lock.
1643 return Err(LightningError {
1644 err: "Already have non-chain-validated channel".to_owned(),
1645 action: ErrorAction::IgnoreDuplicateGossip
1652 let removed_channels = self.removed_channels.lock().unwrap();
1653 let removed_nodes = self.removed_nodes.lock().unwrap();
1654 if removed_channels.contains_key(&msg.short_channel_id) ||
1655 removed_nodes.contains_key(&msg.node_id_1) ||
1656 removed_nodes.contains_key(&msg.node_id_2) {
1657 return Err(LightningError{
1658 err: format!("Channel with SCID {} or one of its nodes was removed from our network graph recently", &msg.short_channel_id),
1659 action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1663 let utxo_value = self.pending_checks.check_channel_announcement(
1664 utxo_lookup, msg, full_msg)?;
1666 #[allow(unused_mut, unused_assignments)]
1667 let mut announcement_received_time = 0;
1668 #[cfg(feature = "std")]
1670 announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1673 let chan_info = ChannelInfo {
1674 features: msg.features.clone(),
1675 node_one: msg.node_id_1,
1677 node_two: msg.node_id_2,
1679 capacity_sats: utxo_value,
1680 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1681 { full_msg.cloned() } else { None },
1682 announcement_received_time,
1685 self.add_channel_between_nodes(msg.short_channel_id, chan_info, utxo_value)?;
1687 log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.short_channel_id, if !msg.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
1691 /// Marks a channel in the graph as failed permanently.
1693 /// The channel and any node for which this was their last channel are removed from the graph.
1694 pub fn channel_failed_permanent(&self, short_channel_id: u64) {
1695 #[cfg(feature = "std")]
1696 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1697 #[cfg(not(feature = "std"))]
1698 let current_time_unix = None;
1700 self.channel_failed_permanent_with_time(short_channel_id, current_time_unix)
1703 /// Marks a channel in the graph as failed permanently.
1705 /// The channel and any node for which this was their last channel are removed from the graph.
1706 fn channel_failed_permanent_with_time(&self, short_channel_id: u64, current_time_unix: Option<u64>) {
1707 let mut channels = self.channels.write().unwrap();
1708 if let Some(chan) = channels.remove(&short_channel_id) {
1709 let mut nodes = self.nodes.write().unwrap();
1710 self.removed_channels.lock().unwrap().insert(short_channel_id, current_time_unix);
1711 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1715 /// Marks a node in the graph as permanently failed, effectively removing it and its channels
1716 /// from local storage.
1717 pub fn node_failed_permanent(&self, node_id: &PublicKey) {
1718 #[cfg(feature = "std")]
1719 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1720 #[cfg(not(feature = "std"))]
1721 let current_time_unix = None;
1723 let node_id = NodeId::from_pubkey(node_id);
1724 let mut channels = self.channels.write().unwrap();
1725 let mut nodes = self.nodes.write().unwrap();
1726 let mut removed_channels = self.removed_channels.lock().unwrap();
1727 let mut removed_nodes = self.removed_nodes.lock().unwrap();
1729 if let Some(node) = nodes.remove(&node_id) {
1730 for scid in node.channels.iter() {
1731 if let Some(chan_info) = channels.remove(scid) {
1732 let other_node_id = if node_id == chan_info.node_one { chan_info.node_two } else { chan_info.node_one };
1733 if let IndexedMapEntry::Occupied(mut other_node_entry) = nodes.entry(other_node_id) {
1734 other_node_entry.get_mut().channels.retain(|chan_id| {
1737 if other_node_entry.get().channels.is_empty() {
1738 other_node_entry.remove_entry();
1741 removed_channels.insert(*scid, current_time_unix);
1744 removed_nodes.insert(node_id, current_time_unix);
1748 #[cfg(feature = "std")]
1749 /// Removes information about channels that we haven't heard any updates about in some time.
1750 /// This can be used regularly to prune the network graph of channels that likely no longer
1753 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1754 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1755 /// pruning occur for updates which are at least two weeks old, which we implement here.
1757 /// Note that for users of the `lightning-background-processor` crate this method may be
1758 /// automatically called regularly for you.
1760 /// This method will also cause us to stop tracking removed nodes and channels if they have been
1761 /// in the map for a while so that these can be resynced from gossip in the future.
1763 /// This method is only available with the `std` feature. See
1764 /// [`NetworkGraph::remove_stale_channels_and_tracking_with_time`] for `no-std` use.
1765 pub fn remove_stale_channels_and_tracking(&self) {
1766 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1767 self.remove_stale_channels_and_tracking_with_time(time);
1770 /// Removes information about channels that we haven't heard any updates about in some time.
1771 /// This can be used regularly to prune the network graph of channels that likely no longer
1774 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1775 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1776 /// pruning occur for updates which are at least two weeks old, which we implement here.
1778 /// This method will also cause us to stop tracking removed nodes and channels if they have been
1779 /// in the map for a while so that these can be resynced from gossip in the future.
1781 /// This function takes the current unix time as an argument. For users with the `std` feature
1782 /// enabled, [`NetworkGraph::remove_stale_channels_and_tracking`] may be preferable.
1783 pub fn remove_stale_channels_and_tracking_with_time(&self, current_time_unix: u64) {
1784 let mut channels = self.channels.write().unwrap();
1785 // Time out if we haven't received an update in at least 14 days.
1786 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1787 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1788 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1789 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1791 let mut scids_to_remove = Vec::new();
1792 for (scid, info) in channels.unordered_iter_mut() {
1793 if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1794 log_gossip!(self.logger, "Removing directional update one_to_two (0) for channel {} due to its timestamp {} being below {}",
1795 scid, info.one_to_two.as_ref().unwrap().last_update, min_time_unix);
1796 info.one_to_two = None;
1798 if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1799 log_gossip!(self.logger, "Removing directional update two_to_one (1) for channel {} due to its timestamp {} being below {}",
1800 scid, info.two_to_one.as_ref().unwrap().last_update, min_time_unix);
1801 info.two_to_one = None;
1803 if info.one_to_two.is_none() || info.two_to_one.is_none() {
1804 // We check the announcement_received_time here to ensure we don't drop
1805 // announcements that we just received and are just waiting for our peer to send a
1806 // channel_update for.
1807 let announcement_received_timestamp = info.announcement_received_time;
1808 if announcement_received_timestamp < min_time_unix as u64 {
1809 log_gossip!(self.logger, "Removing channel {} because both directional updates are missing and its announcement timestamp {} being below {}",
1810 scid, announcement_received_timestamp, min_time_unix);
1811 scids_to_remove.push(*scid);
1815 if !scids_to_remove.is_empty() {
1816 let mut nodes = self.nodes.write().unwrap();
1817 for scid in scids_to_remove {
1818 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1819 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
1820 self.removed_channels.lock().unwrap().insert(scid, Some(current_time_unix));
1824 let should_keep_tracking = |time: &mut Option<u64>| {
1825 if let Some(time) = time {
1826 current_time_unix.saturating_sub(*time) < REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS
1828 // NOTE: In the case of no-std, we won't have access to the current UNIX time at the time of removal,
1829 // so we'll just set the removal time here to the current UNIX time on the very next invocation
1830 // of this function.
1831 #[cfg(feature = "no-std")]
1833 let mut tracked_time = Some(current_time_unix);
1834 core::mem::swap(time, &mut tracked_time);
1837 #[allow(unreachable_code)]
1841 self.removed_channels.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1842 self.removed_nodes.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1845 /// For an already known (from announcement) channel, update info about one of the directions
1848 /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1849 /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1850 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1852 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1853 /// materially in the future will be rejected.
1854 pub fn update_channel(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
1855 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), false)
1858 /// For an already known (from announcement) channel, update info about one of the directions
1859 /// of the channel without verifying the associated signatures. Because we aren't given the
1860 /// associated signatures here we cannot relay the channel update to any of our peers.
1862 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1863 /// materially in the future will be rejected.
1864 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1865 self.update_channel_internal(msg, None, None, false)
1868 /// For an already known (from announcement) channel, verify the given [`ChannelUpdate`].
1870 /// This checks whether the update currently is applicable by [`Self::update_channel`].
1872 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1873 /// materially in the future will be rejected.
1874 pub fn verify_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
1875 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), true)
1878 fn update_channel_internal(&self, msg: &msgs::UnsignedChannelUpdate,
1879 full_msg: Option<&msgs::ChannelUpdate>, sig: Option<&secp256k1::ecdsa::Signature>,
1880 only_verify: bool) -> Result<(), LightningError>
1882 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
1884 if msg.chain_hash != self.chain_hash {
1885 return Err(LightningError {
1886 err: "Channel update chain hash does not match genesis hash".to_owned(),
1887 action: ErrorAction::IgnoreAndLog(Level::Debug),
1891 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
1893 // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
1894 // disable this check during tests!
1895 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1896 if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
1897 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1899 if msg.timestamp as u64 > time + 60 * 60 * 24 {
1900 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1904 log_gossip!(self.logger, "Updating channel {} in direction {} with timestamp {}", msg.short_channel_id, msg.flags & 1, msg.timestamp);
1906 let mut channels = self.channels.write().unwrap();
1907 match channels.get_mut(&msg.short_channel_id) {
1909 core::mem::drop(channels);
1910 self.pending_checks.check_hold_pending_channel_update(msg, full_msg)?;
1911 return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError});
1914 if msg.htlc_maximum_msat > MAX_VALUE_MSAT {
1915 return Err(LightningError{err:
1916 "htlc_maximum_msat is larger than maximum possible msats".to_owned(),
1917 action: ErrorAction::IgnoreError});
1920 if let Some(capacity_sats) = channel.capacity_sats {
1921 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1922 // Don't query UTXO set here to reduce DoS risks.
1923 if capacity_sats > MAX_VALUE_MSAT / 1000 || msg.htlc_maximum_msat > capacity_sats * 1000 {
1924 return Err(LightningError{err:
1925 "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(),
1926 action: ErrorAction::IgnoreError});
1929 macro_rules! check_update_latest {
1930 ($target: expr) => {
1931 if let Some(existing_chan_info) = $target.as_ref() {
1932 // The timestamp field is somewhat of a misnomer - the BOLTs use it to
1933 // order updates to ensure you always have the latest one, only
1934 // suggesting that it be at least the current time. For
1935 // channel_updates specifically, the BOLTs discuss the possibility of
1936 // pruning based on the timestamp field being more than two weeks old,
1937 // but only in the non-normative section.
1938 if existing_chan_info.last_update > msg.timestamp {
1939 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1940 } else if existing_chan_info.last_update == msg.timestamp {
1941 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1947 macro_rules! get_new_channel_info {
1949 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1950 { full_msg.cloned() } else { None };
1952 let updated_channel_update_info = ChannelUpdateInfo {
1953 enabled: chan_enabled,
1954 last_update: msg.timestamp,
1955 cltv_expiry_delta: msg.cltv_expiry_delta,
1956 htlc_minimum_msat: msg.htlc_minimum_msat,
1957 htlc_maximum_msat: msg.htlc_maximum_msat,
1959 base_msat: msg.fee_base_msat,
1960 proportional_millionths: msg.fee_proportional_millionths,
1964 Some(updated_channel_update_info)
1968 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1969 if msg.flags & 1 == 1 {
1970 check_update_latest!(channel.two_to_one);
1971 if let Some(sig) = sig {
1972 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
1973 err: "Couldn't parse source node pubkey".to_owned(),
1974 action: ErrorAction::IgnoreAndLog(Level::Debug)
1975 })?, "channel_update");
1978 channel.two_to_one = get_new_channel_info!();
1981 check_update_latest!(channel.one_to_two);
1982 if let Some(sig) = sig {
1983 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
1984 err: "Couldn't parse destination node pubkey".to_owned(),
1985 action: ErrorAction::IgnoreAndLog(Level::Debug)
1986 })?, "channel_update");
1989 channel.one_to_two = get_new_channel_info!();
1998 fn remove_channel_in_nodes(nodes: &mut IndexedMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1999 macro_rules! remove_from_node {
2000 ($node_id: expr) => {
2001 if let IndexedMapEntry::Occupied(mut entry) = nodes.entry($node_id) {
2002 entry.get_mut().channels.retain(|chan_id| {
2003 short_channel_id != *chan_id
2005 if entry.get().channels.is_empty() {
2006 entry.remove_entry();
2009 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
2014 remove_from_node!(chan.node_one);
2015 remove_from_node!(chan.node_two);
2019 impl ReadOnlyNetworkGraph<'_> {
2020 /// Returns all known valid channels' short ids along with announced channel info.
2022 /// This is not exported to bindings users because we don't want to return lifetime'd references
2023 pub fn channels(&self) -> &IndexedMap<u64, ChannelInfo> {
2027 /// Returns information on a channel with the given id.
2028 pub fn channel(&self, short_channel_id: u64) -> Option<&ChannelInfo> {
2029 self.channels.get(&short_channel_id)
2032 #[cfg(c_bindings)] // Non-bindings users should use `channels`
2033 /// Returns the list of channels in the graph
2034 pub fn list_channels(&self) -> Vec<u64> {
2035 self.channels.unordered_keys().map(|c| *c).collect()
2038 /// Returns all known nodes' public keys along with announced node info.
2040 /// This is not exported to bindings users because we don't want to return lifetime'd references
2041 pub fn nodes(&self) -> &IndexedMap<NodeId, NodeInfo> {
2045 /// Returns information on a node with the given id.
2046 pub fn node(&self, node_id: &NodeId) -> Option<&NodeInfo> {
2047 self.nodes.get(node_id)
2050 #[cfg(c_bindings)] // Non-bindings users should use `nodes`
2051 /// Returns the list of nodes in the graph
2052 pub fn list_nodes(&self) -> Vec<NodeId> {
2053 self.nodes.unordered_keys().map(|n| *n).collect()
2056 /// Get network addresses by node id.
2057 /// Returns None if the requested node is completely unknown,
2058 /// or if node announcement for the node was never received.
2059 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<SocketAddress>> {
2060 self.nodes.get(&NodeId::from_pubkey(&pubkey))
2061 .and_then(|node| node.announcement_info.as_ref().map(|ann| ann.addresses().to_vec()))
2066 pub(crate) mod tests {
2067 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
2068 use crate::ln::channelmanager;
2069 use crate::ln::chan_utils::make_funding_redeemscript;
2070 #[cfg(feature = "std")]
2071 use crate::ln::features::InitFeatures;
2072 use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, NodeAlias, MAX_EXCESS_BYTES_FOR_RELAY, NodeId, RoutingFees, ChannelUpdateInfo, ChannelInfo, NodeAnnouncementInfo, NodeInfo};
2073 use crate::routing::utxo::{UtxoLookupError, UtxoResult};
2074 use crate::ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
2075 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
2076 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
2077 use crate::util::config::UserConfig;
2078 use crate::util::test_utils;
2079 use crate::util::ser::{ReadableArgs, Readable, Writeable};
2080 use crate::util::scid_utils::scid_from_parts;
2082 use crate::routing::gossip::REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS;
2083 use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
2085 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
2086 use bitcoin::hashes::Hash;
2087 use bitcoin::network::constants::Network;
2088 use bitcoin::blockdata::constants::ChainHash;
2089 use bitcoin::blockdata::script::Script;
2090 use bitcoin::blockdata::transaction::TxOut;
2094 use bitcoin::secp256k1::{PublicKey, SecretKey};
2095 use bitcoin::secp256k1::{All, Secp256k1};
2098 use bitcoin::secp256k1;
2099 use crate::prelude::*;
2100 use crate::sync::Arc;
2102 fn create_network_graph() -> NetworkGraph<Arc<test_utils::TestLogger>> {
2103 let logger = Arc::new(test_utils::TestLogger::new());
2104 NetworkGraph::new(Network::Testnet, logger)
2107 fn create_gossip_sync(network_graph: &NetworkGraph<Arc<test_utils::TestLogger>>) -> (
2108 Secp256k1<All>, P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>,
2109 Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
2111 let secp_ctx = Secp256k1::new();
2112 let logger = Arc::new(test_utils::TestLogger::new());
2113 let gossip_sync = P2PGossipSync::new(network_graph, None, Arc::clone(&logger));
2114 (secp_ctx, gossip_sync)
2118 #[cfg(feature = "std")]
2119 fn request_full_sync_finite_times() {
2120 let network_graph = create_network_graph();
2121 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2122 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
2124 assert!(gossip_sync.should_request_full_sync(&node_id));
2125 assert!(gossip_sync.should_request_full_sync(&node_id));
2126 assert!(gossip_sync.should_request_full_sync(&node_id));
2127 assert!(gossip_sync.should_request_full_sync(&node_id));
2128 assert!(gossip_sync.should_request_full_sync(&node_id));
2129 assert!(!gossip_sync.should_request_full_sync(&node_id));
2132 pub(crate) fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
2133 let node_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_key));
2134 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2135 features: channelmanager::provided_node_features(&UserConfig::default()),
2139 alias: NodeAlias([0; 32]),
2140 addresses: Vec::new(),
2141 excess_address_data: Vec::new(),
2142 excess_data: Vec::new(),
2144 f(&mut unsigned_announcement);
2145 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2147 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2148 contents: unsigned_announcement
2152 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 {
2153 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
2154 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
2155 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2156 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2158 let mut unsigned_announcement = UnsignedChannelAnnouncement {
2159 features: channelmanager::provided_channel_features(&UserConfig::default()),
2160 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2161 short_channel_id: 0,
2162 node_id_1: NodeId::from_pubkey(&node_id_1),
2163 node_id_2: NodeId::from_pubkey(&node_id_2),
2164 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey)),
2165 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey)),
2166 excess_data: Vec::new(),
2168 f(&mut unsigned_announcement);
2169 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2170 ChannelAnnouncement {
2171 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_key),
2172 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_key),
2173 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_btckey),
2174 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_btckey),
2175 contents: unsigned_announcement,
2179 pub(crate) fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> Script {
2180 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
2181 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
2182 make_funding_redeemscript(&PublicKey::from_secret_key(secp_ctx, &node_1_btckey),
2183 &PublicKey::from_secret_key(secp_ctx, &node_2_btckey)).to_v0_p2wsh()
2186 pub(crate) fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
2187 let mut unsigned_channel_update = UnsignedChannelUpdate {
2188 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2189 short_channel_id: 0,
2192 cltv_expiry_delta: 144,
2193 htlc_minimum_msat: 1_000_000,
2194 htlc_maximum_msat: 1_000_000,
2195 fee_base_msat: 10_000,
2196 fee_proportional_millionths: 20,
2197 excess_data: Vec::new()
2199 f(&mut unsigned_channel_update);
2200 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2202 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2203 contents: unsigned_channel_update
2208 fn handling_node_announcements() {
2209 let network_graph = create_network_graph();
2210 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2212 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2213 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2214 let zero_hash = Sha256dHash::hash(&[0; 32]);
2216 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2217 match gossip_sync.handle_node_announcement(&valid_announcement) {
2219 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
2223 // Announce a channel to add a corresponding node.
2224 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2225 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2226 Ok(res) => assert!(res),
2231 match gossip_sync.handle_node_announcement(&valid_announcement) {
2232 Ok(res) => assert!(res),
2236 let fake_msghash = hash_to_message!(&zero_hash);
2237 match gossip_sync.handle_node_announcement(
2239 signature: secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey),
2240 contents: valid_announcement.contents.clone()
2243 Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
2246 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
2247 unsigned_announcement.timestamp += 1000;
2248 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2249 }, node_1_privkey, &secp_ctx);
2250 // Return false because contains excess data.
2251 match gossip_sync.handle_node_announcement(&announcement_with_data) {
2252 Ok(res) => assert!(!res),
2256 // Even though previous announcement was not relayed further, we still accepted it,
2257 // so we now won't accept announcements before the previous one.
2258 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
2259 unsigned_announcement.timestamp += 1000 - 10;
2260 }, node_1_privkey, &secp_ctx);
2261 match gossip_sync.handle_node_announcement(&outdated_announcement) {
2263 Err(e) => assert_eq!(e.err, "Update older than last processed update")
2268 fn handling_channel_announcements() {
2269 let secp_ctx = Secp256k1::new();
2270 let logger = test_utils::TestLogger::new();
2272 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2273 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2275 let good_script = get_channel_script(&secp_ctx);
2276 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2278 // Test if the UTXO lookups were not supported
2279 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2280 let mut gossip_sync = P2PGossipSync::new(&network_graph, None, &logger);
2281 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2282 Ok(res) => assert!(res),
2287 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2293 // If we receive announcement for the same channel (with UTXO lookups disabled),
2294 // drop new one on the floor, since we can't see any changes.
2295 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2297 Err(e) => assert_eq!(e.err, "Already have non-chain-validated channel")
2300 // Test if an associated transaction were not on-chain (or not confirmed).
2301 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2302 *chain_source.utxo_ret.lock().unwrap() = UtxoResult::Sync(Err(UtxoLookupError::UnknownTx));
2303 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2304 gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2306 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2307 unsigned_announcement.short_channel_id += 1;
2308 }, node_1_privkey, node_2_privkey, &secp_ctx);
2309 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2311 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2314 // Now test if the transaction is found in the UTXO set and the script is correct.
2315 *chain_source.utxo_ret.lock().unwrap() =
2316 UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script.clone() }));
2317 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2318 unsigned_announcement.short_channel_id += 2;
2319 }, node_1_privkey, node_2_privkey, &secp_ctx);
2320 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2321 Ok(res) => assert!(res),
2326 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2332 // If we receive announcement for the same channel, once we've validated it against the
2333 // chain, we simply ignore all new (duplicate) announcements.
2334 *chain_source.utxo_ret.lock().unwrap() =
2335 UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script }));
2336 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2338 Err(e) => assert_eq!(e.err, "Already have chain-validated channel")
2341 #[cfg(feature = "std")]
2343 use std::time::{SystemTime, UNIX_EPOCH};
2345 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2346 // Mark a node as permanently failed so it's tracked as removed.
2347 gossip_sync.network_graph().node_failed_permanent(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2349 // Return error and ignore valid channel announcement if one of the nodes has been tracked as removed.
2350 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2351 unsigned_announcement.short_channel_id += 3;
2352 }, node_1_privkey, node_2_privkey, &secp_ctx);
2353 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2355 Err(e) => assert_eq!(e.err, "Channel with SCID 3 or one of its nodes was removed from our network graph recently")
2358 gossip_sync.network_graph().remove_stale_channels_and_tracking_with_time(tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2360 // The above channel announcement should be handled as per normal now.
2361 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2362 Ok(res) => assert!(res),
2367 // Don't relay valid channels with excess data
2368 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2369 unsigned_announcement.short_channel_id += 4;
2370 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2371 }, node_1_privkey, node_2_privkey, &secp_ctx);
2372 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2373 Ok(res) => assert!(!res),
2377 let mut invalid_sig_announcement = valid_announcement.clone();
2378 invalid_sig_announcement.contents.excess_data = Vec::new();
2379 match gossip_sync.handle_channel_announcement(&invalid_sig_announcement) {
2381 Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
2384 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
2385 match gossip_sync.handle_channel_announcement(&channel_to_itself_announcement) {
2387 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2390 // Test that channel announcements with the wrong chain hash are ignored (network graph is testnet,
2391 // announcement is mainnet).
2392 let incorrect_chain_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2393 unsigned_announcement.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2394 }, node_1_privkey, node_2_privkey, &secp_ctx);
2395 match gossip_sync.handle_channel_announcement(&incorrect_chain_announcement) {
2397 Err(e) => assert_eq!(e.err, "Channel announcement chain hash does not match genesis hash")
2402 fn handling_channel_update() {
2403 let secp_ctx = Secp256k1::new();
2404 let logger = test_utils::TestLogger::new();
2405 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2406 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2407 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2409 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2410 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2412 let amount_sats = 1000_000;
2413 let short_channel_id;
2416 // Announce a channel we will update
2417 let good_script = get_channel_script(&secp_ctx);
2418 *chain_source.utxo_ret.lock().unwrap() =
2419 UtxoResult::Sync(Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() }));
2421 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2422 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2423 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2430 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2431 network_graph.verify_channel_update(&valid_channel_update).unwrap();
2432 match gossip_sync.handle_channel_update(&valid_channel_update) {
2433 Ok(res) => assert!(res),
2438 match network_graph.read_only().channels().get(&short_channel_id) {
2440 Some(channel_info) => {
2441 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
2442 assert!(channel_info.two_to_one.is_none());
2447 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2448 unsigned_channel_update.timestamp += 100;
2449 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2450 }, node_1_privkey, &secp_ctx);
2451 // Return false because contains excess data
2452 match gossip_sync.handle_channel_update(&valid_channel_update) {
2453 Ok(res) => assert!(!res),
2457 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2458 unsigned_channel_update.timestamp += 110;
2459 unsigned_channel_update.short_channel_id += 1;
2460 }, node_1_privkey, &secp_ctx);
2461 match gossip_sync.handle_channel_update(&valid_channel_update) {
2463 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2466 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2467 unsigned_channel_update.htlc_maximum_msat = MAX_VALUE_MSAT + 1;
2468 unsigned_channel_update.timestamp += 110;
2469 }, node_1_privkey, &secp_ctx);
2470 match gossip_sync.handle_channel_update(&valid_channel_update) {
2472 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
2475 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2476 unsigned_channel_update.htlc_maximum_msat = amount_sats * 1000 + 1;
2477 unsigned_channel_update.timestamp += 110;
2478 }, node_1_privkey, &secp_ctx);
2479 match gossip_sync.handle_channel_update(&valid_channel_update) {
2481 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
2484 // Even though previous update was not relayed further, we still accepted it,
2485 // so we now won't accept update before the previous one.
2486 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2487 unsigned_channel_update.timestamp += 100;
2488 }, node_1_privkey, &secp_ctx);
2489 match gossip_sync.handle_channel_update(&valid_channel_update) {
2491 Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
2494 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2495 unsigned_channel_update.timestamp += 500;
2496 }, node_1_privkey, &secp_ctx);
2497 let zero_hash = Sha256dHash::hash(&[0; 32]);
2498 let fake_msghash = hash_to_message!(&zero_hash);
2499 invalid_sig_channel_update.signature = secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey);
2500 match gossip_sync.handle_channel_update(&invalid_sig_channel_update) {
2502 Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
2505 // Test that channel updates with the wrong chain hash are ignored (network graph is testnet, channel
2506 // update is mainet).
2507 let incorrect_chain_update = get_signed_channel_update(|unsigned_channel_update| {
2508 unsigned_channel_update.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2509 }, node_1_privkey, &secp_ctx);
2511 match gossip_sync.handle_channel_update(&incorrect_chain_update) {
2513 Err(e) => assert_eq!(e.err, "Channel update chain hash does not match genesis hash")
2518 fn handling_network_update() {
2519 let logger = test_utils::TestLogger::new();
2520 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2521 let secp_ctx = Secp256k1::new();
2523 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2524 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2525 let node_2_id = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2528 // There is no nodes in the table at the beginning.
2529 assert_eq!(network_graph.read_only().nodes().len(), 0);
2532 let short_channel_id;
2534 // Announce a channel we will update
2535 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2536 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2537 let chain_source: Option<&test_utils::TestChainSource> = None;
2538 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2539 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2541 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2542 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2544 network_graph.handle_network_update(&NetworkUpdate::ChannelUpdateMessage {
2545 msg: valid_channel_update,
2548 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2551 // Non-permanent failure doesn't touch the channel at all
2553 match network_graph.read_only().channels().get(&short_channel_id) {
2555 Some(channel_info) => {
2556 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2560 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2562 is_permanent: false,
2565 match network_graph.read_only().channels().get(&short_channel_id) {
2567 Some(channel_info) => {
2568 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2573 // Permanent closing deletes a channel
2574 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2579 assert_eq!(network_graph.read_only().channels().len(), 0);
2580 // Nodes are also deleted because there are no associated channels anymore
2581 assert_eq!(network_graph.read_only().nodes().len(), 0);
2584 // Get a new network graph since we don't want to track removed nodes in this test with "std"
2585 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2587 // Announce a channel to test permanent node failure
2588 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2589 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2590 let chain_source: Option<&test_utils::TestChainSource> = None;
2591 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2592 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2594 // Non-permanent node failure does not delete any nodes or channels
2595 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2597 is_permanent: false,
2600 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2601 assert!(network_graph.read_only().nodes().get(&NodeId::from_pubkey(&node_2_id)).is_some());
2603 // Permanent node failure deletes node and its channels
2604 network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2609 assert_eq!(network_graph.read_only().nodes().len(), 0);
2610 // Channels are also deleted because the associated node has been deleted
2611 assert_eq!(network_graph.read_only().channels().len(), 0);
2616 fn test_channel_timeouts() {
2617 // Test the removal of channels with `remove_stale_channels_and_tracking`.
2618 let logger = test_utils::TestLogger::new();
2619 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2620 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2621 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2622 let secp_ctx = Secp256k1::new();
2624 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2625 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2627 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2628 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2629 let chain_source: Option<&test_utils::TestChainSource> = None;
2630 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2631 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2633 // Submit two channel updates for each channel direction (update.flags bit).
2634 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2635 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2636 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2638 let valid_channel_update_2 = get_signed_channel_update(|update| {update.flags |=1;}, node_2_privkey, &secp_ctx);
2639 gossip_sync.handle_channel_update(&valid_channel_update_2).unwrap();
2640 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().two_to_one.is_some());
2642 network_graph.remove_stale_channels_and_tracking_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2643 assert_eq!(network_graph.read_only().channels().len(), 1);
2644 assert_eq!(network_graph.read_only().nodes().len(), 2);
2646 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2647 #[cfg(not(feature = "std"))] {
2648 // Make sure removed channels are tracked.
2649 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2651 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2652 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2654 #[cfg(feature = "std")]
2656 // In std mode, a further check is performed before fully removing the channel -
2657 // the channel_announcement must have been received at least two weeks ago. We
2658 // fudge that here by indicating the time has jumped two weeks.
2659 assert_eq!(network_graph.read_only().channels().len(), 1);
2660 assert_eq!(network_graph.read_only().nodes().len(), 2);
2662 // Note that the directional channel information will have been removed already..
2663 // We want to check that this will work even if *one* of the channel updates is recent,
2664 // so we should add it with a recent timestamp.
2665 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2666 use std::time::{SystemTime, UNIX_EPOCH};
2667 let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2668 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2669 unsigned_channel_update.timestamp = (announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
2670 }, node_1_privkey, &secp_ctx);
2671 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2672 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2673 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2674 // Make sure removed channels are tracked.
2675 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2676 // Provide a later time so that sufficient time has passed
2677 network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2678 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2681 assert_eq!(network_graph.read_only().channels().len(), 0);
2682 assert_eq!(network_graph.read_only().nodes().len(), 0);
2683 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2685 #[cfg(feature = "std")]
2687 use std::time::{SystemTime, UNIX_EPOCH};
2689 let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2691 // Clear tracked nodes and channels for clean slate
2692 network_graph.removed_channels.lock().unwrap().clear();
2693 network_graph.removed_nodes.lock().unwrap().clear();
2695 // Add a channel and nodes from channel announcement. So our network graph will
2696 // now only consist of two nodes and one channel between them.
2697 assert!(network_graph.update_channel_from_announcement(
2698 &valid_channel_announcement, &chain_source).is_ok());
2700 // Mark the channel as permanently failed. This will also remove the two nodes
2701 // and all of the entries will be tracked as removed.
2702 network_graph.channel_failed_permanent_with_time(short_channel_id, Some(tracking_time));
2704 // Should not remove from tracking if insufficient time has passed
2705 network_graph.remove_stale_channels_and_tracking_with_time(
2706 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS - 1);
2707 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1, "Removed channel count ≠1 with tracking_time {}", tracking_time);
2709 // Provide a later time so that sufficient time has passed
2710 network_graph.remove_stale_channels_and_tracking_with_time(
2711 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2712 assert!(network_graph.removed_channels.lock().unwrap().is_empty(), "Unexpectedly removed channels with tracking_time {}", tracking_time);
2713 assert!(network_graph.removed_nodes.lock().unwrap().is_empty(), "Unexpectedly removed nodes with tracking_time {}", tracking_time);
2716 #[cfg(not(feature = "std"))]
2718 // When we don't have access to the system clock, the time we started tracking removal will only
2719 // be that provided by the first call to `remove_stale_channels_and_tracking_with_time`. Hence,
2720 // only if sufficient time has passed after that first call, will the next call remove it from
2722 let removal_time = 1664619654;
2724 // Clear removed nodes and channels for clean slate
2725 network_graph.removed_channels.lock().unwrap().clear();
2726 network_graph.removed_nodes.lock().unwrap().clear();
2728 // Add a channel and nodes from channel announcement. So our network graph will
2729 // now only consist of two nodes and one channel between them.
2730 assert!(network_graph.update_channel_from_announcement(
2731 &valid_channel_announcement, &chain_source).is_ok());
2733 // Mark the channel as permanently failed. This will also remove the two nodes
2734 // and all of the entries will be tracked as removed.
2735 network_graph.channel_failed_permanent(short_channel_id);
2737 // The first time we call the following, the channel will have a removal time assigned.
2738 network_graph.remove_stale_channels_and_tracking_with_time(removal_time);
2739 assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2741 // Provide a later time so that sufficient time has passed
2742 network_graph.remove_stale_channels_and_tracking_with_time(
2743 removal_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2744 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2745 assert!(network_graph.removed_nodes.lock().unwrap().is_empty());
2750 fn getting_next_channel_announcements() {
2751 let network_graph = create_network_graph();
2752 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2753 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2754 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2756 // Channels were not announced yet.
2757 let channels_with_announcements = gossip_sync.get_next_channel_announcement(0);
2758 assert!(channels_with_announcements.is_none());
2760 let short_channel_id;
2762 // Announce a channel we will update
2763 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2764 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2765 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2771 // Contains initial channel announcement now.
2772 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2773 if let Some(channel_announcements) = channels_with_announcements {
2774 let (_, ref update_1, ref update_2) = channel_announcements;
2775 assert_eq!(update_1, &None);
2776 assert_eq!(update_2, &None);
2782 // Valid channel update
2783 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2784 unsigned_channel_update.timestamp = 101;
2785 }, node_1_privkey, &secp_ctx);
2786 match gossip_sync.handle_channel_update(&valid_channel_update) {
2792 // Now contains an initial announcement and an update.
2793 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2794 if let Some(channel_announcements) = channels_with_announcements {
2795 let (_, ref update_1, ref update_2) = channel_announcements;
2796 assert_ne!(update_1, &None);
2797 assert_eq!(update_2, &None);
2803 // Channel update with excess data.
2804 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2805 unsigned_channel_update.timestamp = 102;
2806 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2807 }, node_1_privkey, &secp_ctx);
2808 match gossip_sync.handle_channel_update(&valid_channel_update) {
2814 // Test that announcements with excess data won't be returned
2815 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2816 if let Some(channel_announcements) = channels_with_announcements {
2817 let (_, ref update_1, ref update_2) = channel_announcements;
2818 assert_eq!(update_1, &None);
2819 assert_eq!(update_2, &None);
2824 // Further starting point have no channels after it
2825 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id + 1000);
2826 assert!(channels_with_announcements.is_none());
2830 fn getting_next_node_announcements() {
2831 let network_graph = create_network_graph();
2832 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2833 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2834 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2835 let node_id_1 = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2838 let next_announcements = gossip_sync.get_next_node_announcement(None);
2839 assert!(next_announcements.is_none());
2842 // Announce a channel to add 2 nodes
2843 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2844 match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2850 // Nodes were never announced
2851 let next_announcements = gossip_sync.get_next_node_announcement(None);
2852 assert!(next_announcements.is_none());
2855 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2856 match gossip_sync.handle_node_announcement(&valid_announcement) {
2861 let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
2862 match gossip_sync.handle_node_announcement(&valid_announcement) {
2868 let next_announcements = gossip_sync.get_next_node_announcement(None);
2869 assert!(next_announcements.is_some());
2871 // Skip the first node.
2872 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
2873 assert!(next_announcements.is_some());
2876 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2877 let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
2878 unsigned_announcement.timestamp += 10;
2879 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2880 }, node_2_privkey, &secp_ctx);
2881 match gossip_sync.handle_node_announcement(&valid_announcement) {
2882 Ok(res) => assert!(!res),
2887 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
2888 assert!(next_announcements.is_none());
2892 fn network_graph_serialization() {
2893 let network_graph = create_network_graph();
2894 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2896 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2897 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2899 // Announce a channel to add a corresponding node.
2900 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2901 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2902 Ok(res) => assert!(res),
2906 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2907 match gossip_sync.handle_node_announcement(&valid_announcement) {
2912 let mut w = test_utils::TestVecWriter(Vec::new());
2913 assert!(!network_graph.read_only().nodes().is_empty());
2914 assert!(!network_graph.read_only().channels().is_empty());
2915 network_graph.write(&mut w).unwrap();
2917 let logger = Arc::new(test_utils::TestLogger::new());
2918 assert!(<NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), logger).unwrap() == network_graph);
2922 fn network_graph_tlv_serialization() {
2923 let network_graph = create_network_graph();
2924 network_graph.set_last_rapid_gossip_sync_timestamp(42);
2926 let mut w = test_utils::TestVecWriter(Vec::new());
2927 network_graph.write(&mut w).unwrap();
2929 let logger = Arc::new(test_utils::TestLogger::new());
2930 let reassembled_network_graph: NetworkGraph<_> = ReadableArgs::read(&mut io::Cursor::new(&w.0), logger).unwrap();
2931 assert!(reassembled_network_graph == network_graph);
2932 assert_eq!(reassembled_network_graph.get_last_rapid_gossip_sync_timestamp().unwrap(), 42);
2936 #[cfg(feature = "std")]
2937 fn calling_sync_routing_table() {
2938 use std::time::{SystemTime, UNIX_EPOCH};
2939 use crate::ln::msgs::Init;
2941 let network_graph = create_network_graph();
2942 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2943 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2944 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2946 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
2948 // It should ignore if gossip_queries feature is not enabled
2950 let init_msg = Init { features: InitFeatures::empty(), networks: None, remote_network_address: None };
2951 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
2952 let events = gossip_sync.get_and_clear_pending_msg_events();
2953 assert_eq!(events.len(), 0);
2956 // It should send a gossip_timestamp_filter with the correct information
2958 let mut features = InitFeatures::empty();
2959 features.set_gossip_queries_optional();
2960 let init_msg = Init { features, networks: None, remote_network_address: None };
2961 gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
2962 let events = gossip_sync.get_and_clear_pending_msg_events();
2963 assert_eq!(events.len(), 1);
2965 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
2966 assert_eq!(node_id, &node_id_1);
2967 assert_eq!(msg.chain_hash, chain_hash);
2968 let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2969 assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
2970 assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
2971 assert_eq!(msg.timestamp_range, u32::max_value());
2973 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2979 fn handling_query_channel_range() {
2980 let network_graph = create_network_graph();
2981 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2983 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
2984 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2985 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2986 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2988 let mut scids: Vec<u64> = vec![
2989 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2990 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2993 // used for testing multipart reply across blocks
2994 for block in 100000..=108001 {
2995 scids.push(scid_from_parts(block, 0, 0).unwrap());
2998 // used for testing resumption on same block
2999 scids.push(scid_from_parts(108001, 1, 0).unwrap());
3002 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
3003 unsigned_announcement.short_channel_id = scid;
3004 }, node_1_privkey, node_2_privkey, &secp_ctx);
3005 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3011 // Error when number_of_blocks=0
3012 do_handling_query_channel_range(
3016 chain_hash: chain_hash.clone(),
3018 number_of_blocks: 0,
3021 vec![ReplyChannelRange {
3022 chain_hash: chain_hash.clone(),
3024 number_of_blocks: 0,
3025 sync_complete: true,
3026 short_channel_ids: vec![]
3030 // Error when wrong chain
3031 do_handling_query_channel_range(
3035 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3037 number_of_blocks: 0xffff_ffff,
3040 vec![ReplyChannelRange {
3041 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3043 number_of_blocks: 0xffff_ffff,
3044 sync_complete: true,
3045 short_channel_ids: vec![],
3049 // Error when first_blocknum > 0xffffff
3050 do_handling_query_channel_range(
3054 chain_hash: chain_hash.clone(),
3055 first_blocknum: 0x01000000,
3056 number_of_blocks: 0xffff_ffff,
3059 vec![ReplyChannelRange {
3060 chain_hash: chain_hash.clone(),
3061 first_blocknum: 0x01000000,
3062 number_of_blocks: 0xffff_ffff,
3063 sync_complete: true,
3064 short_channel_ids: vec![]
3068 // Empty reply when max valid SCID block num
3069 do_handling_query_channel_range(
3073 chain_hash: chain_hash.clone(),
3074 first_blocknum: 0xffffff,
3075 number_of_blocks: 1,
3080 chain_hash: chain_hash.clone(),
3081 first_blocknum: 0xffffff,
3082 number_of_blocks: 1,
3083 sync_complete: true,
3084 short_channel_ids: vec![]
3089 // No results in valid query range
3090 do_handling_query_channel_range(
3094 chain_hash: chain_hash.clone(),
3095 first_blocknum: 1000,
3096 number_of_blocks: 1000,
3101 chain_hash: chain_hash.clone(),
3102 first_blocknum: 1000,
3103 number_of_blocks: 1000,
3104 sync_complete: true,
3105 short_channel_ids: vec![],
3110 // Overflow first_blocknum + number_of_blocks
3111 do_handling_query_channel_range(
3115 chain_hash: chain_hash.clone(),
3116 first_blocknum: 0xfe0000,
3117 number_of_blocks: 0xffffffff,
3122 chain_hash: chain_hash.clone(),
3123 first_blocknum: 0xfe0000,
3124 number_of_blocks: 0xffffffff - 0xfe0000,
3125 sync_complete: true,
3126 short_channel_ids: vec![
3127 0xfffffe_ffffff_ffff, // max
3133 // Single block exactly full
3134 do_handling_query_channel_range(
3138 chain_hash: chain_hash.clone(),
3139 first_blocknum: 100000,
3140 number_of_blocks: 8000,
3145 chain_hash: chain_hash.clone(),
3146 first_blocknum: 100000,
3147 number_of_blocks: 8000,
3148 sync_complete: true,
3149 short_channel_ids: (100000..=107999)
3150 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3156 // Multiple split on new block
3157 do_handling_query_channel_range(
3161 chain_hash: chain_hash.clone(),
3162 first_blocknum: 100000,
3163 number_of_blocks: 8001,
3168 chain_hash: chain_hash.clone(),
3169 first_blocknum: 100000,
3170 number_of_blocks: 7999,
3171 sync_complete: false,
3172 short_channel_ids: (100000..=107999)
3173 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3177 chain_hash: chain_hash.clone(),
3178 first_blocknum: 107999,
3179 number_of_blocks: 2,
3180 sync_complete: true,
3181 short_channel_ids: vec![
3182 scid_from_parts(108000, 0, 0).unwrap(),
3188 // Multiple split on same block
3189 do_handling_query_channel_range(
3193 chain_hash: chain_hash.clone(),
3194 first_blocknum: 100002,
3195 number_of_blocks: 8000,
3200 chain_hash: chain_hash.clone(),
3201 first_blocknum: 100002,
3202 number_of_blocks: 7999,
3203 sync_complete: false,
3204 short_channel_ids: (100002..=108001)
3205 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3209 chain_hash: chain_hash.clone(),
3210 first_blocknum: 108001,
3211 number_of_blocks: 1,
3212 sync_complete: true,
3213 short_channel_ids: vec![
3214 scid_from_parts(108001, 1, 0).unwrap(),
3221 fn do_handling_query_channel_range(
3222 gossip_sync: &P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
3223 test_node_id: &PublicKey,
3224 msg: QueryChannelRange,
3226 expected_replies: Vec<ReplyChannelRange>
3228 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
3229 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
3230 let query_end_blocknum = msg.end_blocknum();
3231 let result = gossip_sync.handle_query_channel_range(test_node_id, msg);
3234 assert!(result.is_ok());
3236 assert!(result.is_err());
3239 let events = gossip_sync.get_and_clear_pending_msg_events();
3240 assert_eq!(events.len(), expected_replies.len());
3242 for i in 0..events.len() {
3243 let expected_reply = &expected_replies[i];
3245 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
3246 assert_eq!(node_id, test_node_id);
3247 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
3248 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
3249 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
3250 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
3251 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
3253 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
3254 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
3255 assert!(msg.first_blocknum >= max_firstblocknum);
3256 max_firstblocknum = msg.first_blocknum;
3257 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
3259 // Check that the last block count is >= the query's end_blocknum
3260 if i == events.len() - 1 {
3261 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
3264 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
3270 fn handling_query_short_channel_ids() {
3271 let network_graph = create_network_graph();
3272 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3273 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3274 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
3276 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3278 let result = gossip_sync.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
3280 short_channel_ids: vec![0x0003e8_000000_0000],
3282 assert!(result.is_err());
3286 fn displays_node_alias() {
3287 let format_str_alias = |alias: &str| {
3288 let mut bytes = [0u8; 32];
3289 bytes[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
3290 format!("{}", NodeAlias(bytes))
3293 assert_eq!(format_str_alias("I\u{1F496}LDK! \u{26A1}"), "I\u{1F496}LDK! \u{26A1}");
3294 assert_eq!(format_str_alias("I\u{1F496}LDK!\0\u{26A1}"), "I\u{1F496}LDK!");
3295 assert_eq!(format_str_alias("I\u{1F496}LDK!\t\u{26A1}"), "I\u{1F496}LDK!\u{FFFD}\u{26A1}");
3297 let format_bytes_alias = |alias: &[u8]| {
3298 let mut bytes = [0u8; 32];
3299 bytes[..alias.len()].copy_from_slice(alias);
3300 format!("{}", NodeAlias(bytes))
3303 assert_eq!(format_bytes_alias(b"\xFFI <heart> LDK!"), "\u{FFFD}I <heart> LDK!");
3304 assert_eq!(format_bytes_alias(b"\xFFI <heart>\0LDK!"), "\u{FFFD}I <heart>");
3305 assert_eq!(format_bytes_alias(b"\xFFI <heart>\tLDK!"), "\u{FFFD}I <heart>\u{FFFD}LDK!");
3309 fn channel_info_is_readable() {
3310 let chanmon_cfgs = crate::ln::functional_test_utils::create_chanmon_cfgs(2);
3311 let node_cfgs = crate::ln::functional_test_utils::create_node_cfgs(2, &chanmon_cfgs);
3312 let node_chanmgrs = crate::ln::functional_test_utils::create_node_chanmgrs(2, &node_cfgs, &[None, None, None, None]);
3313 let nodes = crate::ln::functional_test_utils::create_network(2, &node_cfgs, &node_chanmgrs);
3314 let config = crate::ln::functional_test_utils::test_default_channel_config();
3316 // 1. Test encoding/decoding of ChannelUpdateInfo
3317 let chan_update_info = ChannelUpdateInfo {
3320 cltv_expiry_delta: 42,
3321 htlc_minimum_msat: 1234,
3322 htlc_maximum_msat: 5678,
3323 fees: RoutingFees { base_msat: 9, proportional_millionths: 10 },
3324 last_update_message: None,
3327 let mut encoded_chan_update_info: Vec<u8> = Vec::new();
3328 assert!(chan_update_info.write(&mut encoded_chan_update_info).is_ok());
3330 // First make sure we can read ChannelUpdateInfos we just wrote
3331 let read_chan_update_info: ChannelUpdateInfo = crate::util::ser::Readable::read(&mut encoded_chan_update_info.as_slice()).unwrap();
3332 assert_eq!(chan_update_info, read_chan_update_info);
3334 // Check the serialization hasn't changed.
3335 let legacy_chan_update_info_with_some: Vec<u8> = hex::decode("340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c0100").unwrap();
3336 assert_eq!(encoded_chan_update_info, legacy_chan_update_info_with_some);
3338 // Check we fail if htlc_maximum_msat is not present in either the ChannelUpdateInfo itself
3339 // or the ChannelUpdate enclosed with `last_update_message`.
3340 let legacy_chan_update_info_with_some_and_fail_update: Vec<u8> = hex::decode("b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f42400000271000000014").unwrap();
3341 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());
3342 assert!(read_chan_update_info_res.is_err());
3344 let legacy_chan_update_info_with_none: Vec<u8> = hex::decode("2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100").unwrap();
3345 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());
3346 assert!(read_chan_update_info_res.is_err());
3348 // 2. Test encoding/decoding of ChannelInfo
3349 // Check we can encode/decode ChannelInfo without ChannelUpdateInfo fields present.
3350 let chan_info_none_updates = ChannelInfo {
3351 features: channelmanager::provided_channel_features(&config),
3352 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3354 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3356 capacity_sats: None,
3357 announcement_message: None,
3358 announcement_received_time: 87654,
3361 let mut encoded_chan_info: Vec<u8> = Vec::new();
3362 assert!(chan_info_none_updates.write(&mut encoded_chan_info).is_ok());
3364 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3365 assert_eq!(chan_info_none_updates, read_chan_info);
3367 // Check we can encode/decode ChannelInfo with ChannelUpdateInfo fields present.
3368 let chan_info_some_updates = ChannelInfo {
3369 features: channelmanager::provided_channel_features(&config),
3370 node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3371 one_to_two: Some(chan_update_info.clone()),
3372 node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3373 two_to_one: Some(chan_update_info.clone()),
3374 capacity_sats: None,
3375 announcement_message: None,
3376 announcement_received_time: 87654,
3379 let mut encoded_chan_info: Vec<u8> = Vec::new();
3380 assert!(chan_info_some_updates.write(&mut encoded_chan_info).is_ok());
3382 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3383 assert_eq!(chan_info_some_updates, read_chan_info);
3385 // Check the serialization hasn't changed.
3386 let legacy_chan_info_with_some: Vec<u8> = hex::decode("ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88043636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23083636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3387 assert_eq!(encoded_chan_info, legacy_chan_info_with_some);
3389 // Check we can decode legacy ChannelInfo, even if the `two_to_one` / `one_to_two` /
3390 // `last_update_message` fields fail to decode due to missing htlc_maximum_msat.
3391 let legacy_chan_info_with_some_and_fail_update = hex::decode("fd01ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce8804b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f4240000027100000001406210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2308b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f424000002710000000140a01000c0100").unwrap();
3392 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_some_and_fail_update.as_slice()).unwrap();
3393 assert_eq!(read_chan_info.announcement_received_time, 87654);
3394 assert_eq!(read_chan_info.one_to_two, None);
3395 assert_eq!(read_chan_info.two_to_one, None);
3397 let legacy_chan_info_with_none: Vec<u8> = hex::decode("ba00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88042e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23082e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3398 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_none.as_slice()).unwrap();
3399 assert_eq!(read_chan_info.announcement_received_time, 87654);
3400 assert_eq!(read_chan_info.one_to_two, None);
3401 assert_eq!(read_chan_info.two_to_one, None);
3405 fn node_info_is_readable() {
3406 // 1. Check we can read a valid NodeAnnouncementInfo and fail on an invalid one
3407 let announcement_message = hex::decode("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000122013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010000701fffefdfc2607").unwrap();
3408 let announcement_message = NodeAnnouncement::read(&mut announcement_message.as_slice()).unwrap();
3409 let valid_node_ann_info = NodeAnnouncementInfo {
3410 features: channelmanager::provided_node_features(&UserConfig::default()),
3413 alias: NodeAlias([0u8; 32]),
3414 announcement_message: Some(announcement_message)
3417 let mut encoded_valid_node_ann_info = Vec::new();
3418 assert!(valid_node_ann_info.write(&mut encoded_valid_node_ann_info).is_ok());
3419 let read_valid_node_ann_info = NodeAnnouncementInfo::read(&mut encoded_valid_node_ann_info.as_slice()).unwrap();
3420 assert_eq!(read_valid_node_ann_info, valid_node_ann_info);
3421 assert_eq!(read_valid_node_ann_info.addresses().len(), 1);
3423 let encoded_invalid_node_ann_info = hex::decode("3f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d2").unwrap();
3424 let read_invalid_node_ann_info_res = NodeAnnouncementInfo::read(&mut encoded_invalid_node_ann_info.as_slice());
3425 assert!(read_invalid_node_ann_info_res.is_err());
3427 // 2. Check we can read a NodeInfo anyways, but set the NodeAnnouncementInfo to None if invalid
3428 let valid_node_info = NodeInfo {
3429 channels: Vec::new(),
3430 announcement_info: Some(valid_node_ann_info),
3433 let mut encoded_valid_node_info = Vec::new();
3434 assert!(valid_node_info.write(&mut encoded_valid_node_info).is_ok());
3435 let read_valid_node_info = NodeInfo::read(&mut encoded_valid_node_info.as_slice()).unwrap();
3436 assert_eq!(read_valid_node_info, valid_node_info);
3438 let encoded_invalid_node_info_hex = hex::decode("4402403f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d20400").unwrap();
3439 let read_invalid_node_info = NodeInfo::read(&mut encoded_invalid_node_info_hex.as_slice()).unwrap();
3440 assert_eq!(read_invalid_node_info.announcement_info, None);
3444 fn test_node_info_keeps_compatibility() {
3445 let old_ann_info_with_addresses = hex::decode("3f0009000708a000080a51220204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014104d2").unwrap();
3446 let ann_info_with_addresses = NodeAnnouncementInfo::read(&mut old_ann_info_with_addresses.as_slice())
3447 .expect("to be able to read an old NodeAnnouncementInfo with addresses");
3448 // This serialized info has an address field but no announcement_message, therefore the addresses returned by our function will still be empty
3449 assert!(ann_info_with_addresses.addresses().is_empty());
3453 fn test_node_id_display() {
3454 let node_id = NodeId([42; 33]);
3455 assert_eq!(format!("{}", &node_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
3463 use criterion::{black_box, Criterion};
3465 pub fn read_network_graph(bench: &mut Criterion) {
3466 let logger = crate::util::test_utils::TestLogger::new();
3467 let mut d = crate::routing::router::bench_utils::get_route_file().unwrap();
3468 let mut v = Vec::new();
3469 d.read_to_end(&mut v).unwrap();
3470 bench.bench_function("read_network_graph", |b| b.iter(||
3471 NetworkGraph::read(&mut std::io::Cursor::new(black_box(&v)), &logger).unwrap()
3475 pub fn write_network_graph(bench: &mut Criterion) {
3476 let logger = crate::util::test_utils::TestLogger::new();
3477 let mut d = crate::routing::router::bench_utils::get_route_file().unwrap();
3478 let net_graph = NetworkGraph::read(&mut d, &logger).unwrap();
3479 bench.bench_function("write_network_graph", |b| b.iter(||
3480 black_box(&net_graph).encode()