Drop the `dist` `HashMap` in routing, replacing it with a `Vec`.
[rust-lightning] / lightning / src / routing / gossip.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! The [`NetworkGraph`] stores the network gossip and [`P2PGossipSync`] fetches it from peers
11
12 use bitcoin::blockdata::constants::ChainHash;
13
14 use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
15 use bitcoin::secp256k1::{PublicKey, Verification};
16 use bitcoin::secp256k1::Secp256k1;
17 use bitcoin::secp256k1;
18
19 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
20 use bitcoin::hashes::Hash;
21 use bitcoin::network::constants::Network;
22
23 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
24 use crate::ln::ChannelId;
25 use crate::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
26 use crate::ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, SocketAddress, MAX_VALUE_MSAT};
27 use crate::ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, GossipTimestampFilter};
28 use crate::ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
29 use crate::ln::msgs;
30 use crate::routing::utxo::{self, UtxoLookup, UtxoResolver};
31 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, MaybeReadable};
32 use crate::util::logger::{Logger, Level};
33 use crate::util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
34 use crate::util::string::PrintableString;
35 use crate::util::indexed_map::{IndexedMap, Entry as IndexedMapEntry};
36
37 use crate::io;
38 use crate::io_extras::{copy, sink};
39 use crate::prelude::*;
40 use core::{cmp, fmt};
41 use core::convert::TryFrom;
42 use crate::sync::{RwLock, RwLockReadGuard, LockTestExt};
43 use core::sync::atomic::{AtomicUsize, Ordering};
44 use crate::sync::Mutex;
45 use core::ops::{Bound, Deref};
46 use core::str::FromStr;
47
48 #[cfg(feature = "std")]
49 use std::time::{SystemTime, UNIX_EPOCH};
50
51 /// We remove stale channel directional info two weeks after the last update, per BOLT 7's
52 /// suggestion.
53 const STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14;
54
55 /// We stop tracking the removal of permanently failed nodes and channels one week after removal
56 const REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 7;
57
58 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
59 /// refuse to relay the message.
60 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
61
62 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
63 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
64 const MAX_SCIDS_PER_REPLY: usize = 8000;
65
66 /// Represents the compressed public key of a node
67 #[derive(Clone, Copy, PartialEq, Eq)]
68 pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
69
70 impl NodeId {
71         /// Create a new NodeId from a public key
72         pub fn from_pubkey(pubkey: &PublicKey) -> Self {
73                 NodeId(pubkey.serialize())
74         }
75
76         /// Create a new NodeId from a slice of bytes
77         pub fn from_slice(bytes: &[u8]) -> Result<Self, DecodeError> {
78                 if bytes.len() != PUBLIC_KEY_SIZE {
79                         return Err(DecodeError::InvalidValue);
80                 }
81                 let mut data = [0; PUBLIC_KEY_SIZE];
82                 data.copy_from_slice(bytes);
83                 Ok(NodeId(data))
84         }
85
86         /// Get the public key slice from this NodeId
87         pub fn as_slice(&self) -> &[u8] {
88                 &self.0
89         }
90
91         /// Get the public key as an array from this NodeId
92         pub fn as_array(&self) -> &[u8; PUBLIC_KEY_SIZE] {
93                 &self.0
94         }
95
96         /// Get the public key from this NodeId
97         pub fn as_pubkey(&self) -> Result<PublicKey, secp256k1::Error> {
98                 PublicKey::from_slice(&self.0)
99         }
100 }
101
102 impl fmt::Debug for NodeId {
103         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104                 write!(f, "NodeId({})", crate::util::logger::DebugBytes(&self.0))
105         }
106 }
107 impl fmt::Display for NodeId {
108         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109                 crate::util::logger::DebugBytes(&self.0).fmt(f)
110         }
111 }
112
113 impl core::hash::Hash for NodeId {
114         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
115                 self.0.hash(hasher);
116         }
117 }
118
119 impl cmp::PartialOrd for NodeId {
120         fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
121                 Some(self.cmp(other))
122         }
123 }
124
125 impl Ord for NodeId {
126         fn cmp(&self, other: &Self) -> cmp::Ordering {
127                 self.0[..].cmp(&other.0[..])
128         }
129 }
130
131 impl Writeable for NodeId {
132         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
133                 writer.write_all(&self.0)?;
134                 Ok(())
135         }
136 }
137
138 impl Readable for NodeId {
139         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
140                 let mut buf = [0; PUBLIC_KEY_SIZE];
141                 reader.read_exact(&mut buf)?;
142                 Ok(Self(buf))
143         }
144 }
145
146 impl From<PublicKey> for NodeId {
147         fn from(pubkey: PublicKey) -> Self {
148                 Self::from_pubkey(&pubkey)
149         }
150 }
151
152 impl TryFrom<NodeId> for PublicKey {
153         type Error = secp256k1::Error;
154
155         fn try_from(node_id: NodeId) -> Result<Self, Self::Error> {
156                 node_id.as_pubkey()
157         }
158 }
159
160 impl FromStr for NodeId {
161         type Err = hex::parse::HexToArrayError;
162
163         fn from_str(s: &str) -> Result<Self, Self::Err> {
164                 let data: [u8; PUBLIC_KEY_SIZE] = hex::FromHex::from_hex(s)?;
165                 Ok(NodeId(data))
166         }
167 }
168
169 /// Represents the network as nodes and channels between them
170 pub struct NetworkGraph<L: Deref> where L::Target: Logger {
171         secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
172         last_rapid_gossip_sync_timestamp: Mutex<Option<u32>>,
173         chain_hash: ChainHash,
174         logger: L,
175         // Lock order: channels -> nodes
176         channels: RwLock<IndexedMap<u64, ChannelInfo>>,
177         nodes: RwLock<IndexedMap<NodeId, NodeInfo>>,
178         removed_node_counters: Mutex<Vec<u32>>,
179         next_node_counter: AtomicUsize,
180         // Lock order: removed_channels -> removed_nodes
181         //
182         // NOTE: In the following `removed_*` maps, we use seconds since UNIX epoch to track time instead
183         // of `std::time::Instant`s for a few reasons:
184         //   * We want it to be possible to do tracking in no-std environments where we can compare
185         //     a provided current UNIX timestamp with the time at which we started tracking.
186         //   * In the future, if we decide to persist these maps, they will already be serializable.
187         //   * Although we lose out on the platform's monotonic clock, the system clock in a std
188         //     environment should be practical over the time period we are considering (on the order of a
189         //     week).
190         //
191         /// Keeps track of short channel IDs for channels we have explicitly removed due to permanent
192         /// failure so that we don't resync them from gossip. Each SCID is mapped to the time (in seconds)
193         /// it was removed so that once some time passes, we can potentially resync it from gossip again.
194         removed_channels: Mutex<HashMap<u64, Option<u64>>>,
195         /// Keeps track of `NodeId`s we have explicitly removed due to permanent failure so that we don't
196         /// resync them from gossip. Each `NodeId` is mapped to the time (in seconds) it was removed so
197         /// that once some time passes, we can potentially resync it from gossip again.
198         removed_nodes: Mutex<HashMap<NodeId, Option<u64>>>,
199         /// Announcement messages which are awaiting an on-chain lookup to be processed.
200         pub(super) pending_checks: utxo::PendingChecks,
201 }
202
203 /// A read-only view of [`NetworkGraph`].
204 pub struct ReadOnlyNetworkGraph<'a> {
205         channels: RwLockReadGuard<'a, IndexedMap<u64, ChannelInfo>>,
206         nodes: RwLockReadGuard<'a, IndexedMap<NodeId, NodeInfo>>,
207         max_node_counter: u32,
208 }
209
210 /// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
211 /// return packet by a node along the route. See [BOLT #4] for details.
212 ///
213 /// [BOLT #4]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md
214 #[derive(Clone, Debug, PartialEq, Eq)]
215 pub enum NetworkUpdate {
216         /// An error indicating a `channel_update` messages should be applied via
217         /// [`NetworkGraph::update_channel`].
218         ChannelUpdateMessage {
219                 /// The update to apply via [`NetworkGraph::update_channel`].
220                 msg: ChannelUpdate,
221         },
222         /// An error indicating that a channel failed to route a payment, which should be applied via
223         /// [`NetworkGraph::channel_failed_permanent`] if permanent.
224         ChannelFailure {
225                 /// The short channel id of the closed channel.
226                 short_channel_id: u64,
227                 /// Whether the channel should be permanently removed or temporarily disabled until a new
228                 /// `channel_update` message is received.
229                 is_permanent: bool,
230         },
231         /// An error indicating that a node failed to route a payment, which should be applied via
232         /// [`NetworkGraph::node_failed_permanent`] if permanent.
233         NodeFailure {
234                 /// The node id of the failed node.
235                 node_id: PublicKey,
236                 /// Whether the node should be permanently removed from consideration or can be restored
237                 /// when a new `channel_update` message is received.
238                 is_permanent: bool,
239         }
240 }
241
242 impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
243         (0, ChannelUpdateMessage) => {
244                 (0, msg, required),
245         },
246         (2, ChannelFailure) => {
247                 (0, short_channel_id, required),
248                 (2, is_permanent, required),
249         },
250         (4, NodeFailure) => {
251                 (0, node_id, required),
252                 (2, is_permanent, required),
253         },
254 );
255
256 /// Receives and validates network updates from peers,
257 /// stores authentic and relevant data as a network graph.
258 /// This network graph is then used for routing payments.
259 /// Provides interface to help with initial routing sync by
260 /// serving historical announcements.
261 pub struct P2PGossipSync<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref>
262 where U::Target: UtxoLookup, L::Target: Logger
263 {
264         network_graph: G,
265         utxo_lookup: RwLock<Option<U>>,
266         #[cfg(feature = "std")]
267         full_syncs_requested: AtomicUsize,
268         pending_events: Mutex<Vec<MessageSendEvent>>,
269         logger: L,
270 }
271
272 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> P2PGossipSync<G, U, L>
273 where U::Target: UtxoLookup, L::Target: Logger
274 {
275         /// Creates a new tracker of the actual state of the network of channels and nodes,
276         /// assuming an existing [`NetworkGraph`].
277         /// UTXO lookup is used to make sure announced channels exist on-chain, channel data is
278         /// correct, and the announcement is signed with channel owners' keys.
279         pub fn new(network_graph: G, utxo_lookup: Option<U>, logger: L) -> Self {
280                 P2PGossipSync {
281                         network_graph,
282                         #[cfg(feature = "std")]
283                         full_syncs_requested: AtomicUsize::new(0),
284                         utxo_lookup: RwLock::new(utxo_lookup),
285                         pending_events: Mutex::new(vec![]),
286                         logger,
287                 }
288         }
289
290         /// Adds a provider used to check new announcements. Does not affect
291         /// existing announcements unless they are updated.
292         /// Add, update or remove the provider would replace the current one.
293         pub fn add_utxo_lookup(&self, utxo_lookup: Option<U>) {
294                 *self.utxo_lookup.write().unwrap() = utxo_lookup;
295         }
296
297         /// Gets a reference to the underlying [`NetworkGraph`] which was provided in
298         /// [`P2PGossipSync::new`].
299         ///
300         /// This is not exported to bindings users as bindings don't support a reference-to-a-reference yet
301         pub fn network_graph(&self) -> &G {
302                 &self.network_graph
303         }
304
305         #[cfg(feature = "std")]
306         /// Returns true when a full routing table sync should be performed with a peer.
307         fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
308                 //TODO: Determine whether to request a full sync based on the network map.
309                 const FULL_SYNCS_TO_REQUEST: usize = 5;
310                 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
311                         self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
312                         true
313                 } else {
314                         false
315                 }
316         }
317
318         /// Used to broadcast forward gossip messages which were validated async.
319         ///
320         /// Note that this will ignore events other than `Broadcast*` or messages with too much excess
321         /// data.
322         pub(super) fn forward_gossip_msg(&self, mut ev: MessageSendEvent) {
323                 match &mut ev {
324                         MessageSendEvent::BroadcastChannelAnnouncement { msg, ref mut update_msg } => {
325                                 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
326                                 if update_msg.as_ref()
327                                         .map(|msg| msg.contents.excess_data.len()).unwrap_or(0) > MAX_EXCESS_BYTES_FOR_RELAY
328                                 {
329                                         *update_msg = None;
330                                 }
331                         },
332                         MessageSendEvent::BroadcastChannelUpdate { msg } => {
333                                 if msg.contents.excess_data.len() > MAX_EXCESS_BYTES_FOR_RELAY { return; }
334                         },
335                         MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
336                                 if msg.contents.excess_data.len() >  MAX_EXCESS_BYTES_FOR_RELAY ||
337                                    msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY ||
338                                    msg.contents.excess_data.len() + msg.contents.excess_address_data.len() > MAX_EXCESS_BYTES_FOR_RELAY
339                                 {
340                                         return;
341                                 }
342                         },
343                         _ => return,
344                 }
345                 self.pending_events.lock().unwrap().push(ev);
346         }
347 }
348
349 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
350         /// Handles any network updates originating from [`Event`]s.
351         //
352         /// Note that this will skip applying any [`NetworkUpdate::ChannelUpdateMessage`] to avoid
353         /// leaking possibly identifying information of the sender to the public network.
354         ///
355         /// [`Event`]: crate::events::Event
356         pub fn handle_network_update(&self, network_update: &NetworkUpdate) {
357                 match *network_update {
358                         NetworkUpdate::ChannelUpdateMessage { ref msg } => {
359                                 let short_channel_id = msg.contents.short_channel_id;
360                                 let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
361                                 let status = if is_enabled { "enabled" } else { "disabled" };
362                                 log_debug!(self.logger, "Skipping application of a channel update from a payment failure. Channel {} is {}.", short_channel_id, status);
363                         },
364                         NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } => {
365                                 if is_permanent {
366                                         log_debug!(self.logger, "Removing channel graph entry for {} due to a payment failure.", short_channel_id);
367                                         self.channel_failed_permanent(short_channel_id);
368                                 }
369                         },
370                         NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
371                                 if is_permanent {
372                                         log_debug!(self.logger,
373                                                 "Removed node graph entry for {} due to a payment failure.", log_pubkey!(node_id));
374                                         self.node_failed_permanent(node_id);
375                                 };
376                         },
377                 }
378         }
379
380         /// Gets the chain hash for this network graph.
381         pub fn get_chain_hash(&self) -> ChainHash {
382                 self.chain_hash
383         }
384 }
385
386 macro_rules! secp_verify_sig {
387         ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr, $msg_type: expr ) => {
388                 match $secp_ctx.verify_ecdsa($msg, $sig, $pubkey) {
389                         Ok(_) => {},
390                         Err(_) => {
391                                 return Err(LightningError {
392                                         err: format!("Invalid signature on {} message", $msg_type),
393                                         action: ErrorAction::SendWarningMessage {
394                                                 msg: msgs::WarningMessage {
395                                                         channel_id: ChannelId::new_zero(),
396                                                         data: format!("Invalid signature on {} message", $msg_type),
397                                                 },
398                                                 log_level: Level::Trace,
399                                         },
400                                 });
401                         },
402                 }
403         };
404 }
405
406 macro_rules! get_pubkey_from_node_id {
407         ( $node_id: expr, $msg_type: expr ) => {
408                 PublicKey::from_slice($node_id.as_slice())
409                         .map_err(|_| LightningError {
410                                 err: format!("Invalid public key on {} message", $msg_type),
411                                 action: ErrorAction::SendWarningMessage {
412                                         msg: msgs::WarningMessage {
413                                                 channel_id: ChannelId::new_zero(),
414                                                 data: format!("Invalid public key on {} message", $msg_type),
415                                         },
416                                         log_level: Level::Trace
417                                 }
418                         })?
419         }
420 }
421
422 fn message_sha256d_hash<M: Writeable>(msg: &M) -> Sha256dHash {
423         let mut engine = Sha256dHash::engine();
424         msg.write(&mut engine).expect("In-memory structs should not fail to serialize");
425         Sha256dHash::from_engine(engine)
426 }
427
428 /// Verifies the signature of a [`NodeAnnouncement`].
429 ///
430 /// Returns an error if it is invalid.
431 pub fn verify_node_announcement<C: Verification>(msg: &NodeAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
432         let msg_hash = hash_to_message!(&message_sha256d_hash(&msg.contents)[..]);
433         secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &get_pubkey_from_node_id!(msg.contents.node_id, "node_announcement"), "node_announcement");
434
435         Ok(())
436 }
437
438 /// Verifies all signatures included in a [`ChannelAnnouncement`].
439 ///
440 /// Returns an error if one of the signatures is invalid.
441 pub fn verify_channel_announcement<C: Verification>(msg: &ChannelAnnouncement, secp_ctx: &Secp256k1<C>) -> Result<(), LightningError> {
442         let msg_hash = hash_to_message!(&message_sha256d_hash(&msg.contents)[..]);
443         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");
444         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");
445         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");
446         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");
447
448         Ok(())
449 }
450
451 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> RoutingMessageHandler for P2PGossipSync<G, U, L>
452 where U::Target: UtxoLookup, L::Target: Logger
453 {
454         fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
455                 self.network_graph.update_node_from_announcement(msg)?;
456                 Ok(msg.contents.excess_data.len() <=  MAX_EXCESS_BYTES_FOR_RELAY &&
457                    msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
458                    msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
459         }
460
461         fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
462                 self.network_graph.update_channel_from_announcement(msg, &*self.utxo_lookup.read().unwrap())?;
463                 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
464         }
465
466         fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
467                 self.network_graph.update_channel(msg)?;
468                 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
469         }
470
471         fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
472                 let mut channels = self.network_graph.channels.write().unwrap();
473                 for (_, ref chan) in channels.range(starting_point..) {
474                         if chan.announcement_message.is_some() {
475                                 let chan_announcement = chan.announcement_message.clone().unwrap();
476                                 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
477                                 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
478                                 if let Some(one_to_two) = chan.one_to_two.as_ref() {
479                                         one_to_two_announcement = one_to_two.last_update_message.clone();
480                                 }
481                                 if let Some(two_to_one) = chan.two_to_one.as_ref() {
482                                         two_to_one_announcement = two_to_one.last_update_message.clone();
483                                 }
484                                 return Some((chan_announcement, one_to_two_announcement, two_to_one_announcement));
485                         } else {
486                                 // TODO: We may end up sending un-announced channel_updates if we are sending
487                                 // initial sync data while receiving announce/updates for this channel.
488                         }
489                 }
490                 None
491         }
492
493         fn get_next_node_announcement(&self, starting_point: Option<&NodeId>) -> Option<NodeAnnouncement> {
494                 let mut nodes = self.network_graph.nodes.write().unwrap();
495                 let iter = if let Some(node_id) = starting_point {
496                                 nodes.range((Bound::Excluded(node_id), Bound::Unbounded))
497                         } else {
498                                 nodes.range(..)
499                         };
500                 for (_, ref node) in iter {
501                         if let Some(node_info) = node.announcement_info.as_ref() {
502                                 if let Some(msg) = node_info.announcement_message.clone() {
503                                         return Some(msg);
504                                 }
505                         }
506                 }
507                 None
508         }
509
510         /// Initiates a stateless sync of routing gossip information with a peer
511         /// using [`gossip_queries`]. The default strategy used by this implementation
512         /// is to sync the full block range with several peers.
513         ///
514         /// We should expect one or more [`reply_channel_range`] messages in response
515         /// to our [`query_channel_range`]. Each reply will enqueue a [`query_scid`] message
516         /// to request gossip messages for each channel. The sync is considered complete
517         /// when the final [`reply_scids_end`] message is received, though we are not
518         /// tracking this directly.
519         ///
520         /// [`gossip_queries`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#query-messages
521         /// [`reply_channel_range`]: msgs::ReplyChannelRange
522         /// [`query_channel_range`]: msgs::QueryChannelRange
523         /// [`query_scid`]: msgs::QueryShortChannelIds
524         /// [`reply_scids_end`]: msgs::ReplyShortChannelIdsEnd
525         fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &Init, _inbound: bool) -> Result<(), ()> {
526                 // We will only perform a sync with peers that support gossip_queries.
527                 if !init_msg.features.supports_gossip_queries() {
528                         // Don't disconnect peers for not supporting gossip queries. We may wish to have
529                         // channels with peers even without being able to exchange gossip.
530                         return Ok(());
531                 }
532
533                 // The lightning network's gossip sync system is completely broken in numerous ways.
534                 //
535                 // Given no broadly-available set-reconciliation protocol, the only reasonable approach is
536                 // to do a full sync from the first few peers we connect to, and then receive gossip
537                 // updates from all our peers normally.
538                 //
539                 // Originally, we could simply tell a peer to dump us the entire gossip table on startup,
540                 // wasting lots of bandwidth but ensuring we have the full network graph. After the initial
541                 // dump peers would always send gossip and we'd stay up-to-date with whatever our peer has
542                 // seen.
543                 //
544                 // In order to reduce the bandwidth waste, "gossip queries" were introduced, allowing you
545                 // to ask for the SCIDs of all channels in your peer's routing graph, and then only request
546                 // channel data which you are missing. Except there was no way at all to identify which
547                 // `channel_update`s you were missing, so you still had to request everything, just in a
548                 // very complicated way with some queries instead of just getting the dump.
549                 //
550                 // Later, an option was added to fetch the latest timestamps of the `channel_update`s to
551                 // make efficient sync possible, however it has yet to be implemented in lnd, which makes
552                 // relying on it useless.
553                 //
554                 // After gossip queries were introduced, support for receiving a full gossip table dump on
555                 // connection was removed from several nodes, making it impossible to get a full sync
556                 // without using the "gossip queries" messages.
557                 //
558                 // Once you opt into "gossip queries" the only way to receive any gossip updates that a
559                 // peer receives after you connect, you must send a `gossip_timestamp_filter` message. This
560                 // message, as the name implies, tells the peer to not forward any gossip messages with a
561                 // timestamp older than a given value (not the time the peer received the filter, but the
562                 // timestamp in the update message, which is often hours behind when the peer received the
563                 // message).
564                 //
565                 // Obnoxiously, `gossip_timestamp_filter` isn't *just* a filter, but its also a request for
566                 // your peer to send you the full routing graph (subject to the filter). Thus, in order to
567                 // tell a peer to send you any updates as it sees them, you have to also ask for the full
568                 // routing graph to be synced. If you set a timestamp filter near the current time, peers
569                 // will simply not forward any new updates they see to you which were generated some time
570                 // ago (which is not uncommon). If you instead set a timestamp filter near 0 (or two weeks
571                 // ago), you will always get the full routing graph from all your peers.
572                 //
573                 // Most lightning nodes today opt to simply turn off receiving gossip data which only
574                 // propagated some time after it was generated, and, worse, often disable gossiping with
575                 // several peers after their first connection. The second behavior can cause gossip to not
576                 // propagate fully if there are cuts in the gossiping subgraph.
577                 //
578                 // In an attempt to cut a middle ground between always fetching the full graph from all of
579                 // our peers and never receiving gossip from peers at all, we send all of our peers a
580                 // `gossip_timestamp_filter`, with the filter time set either two weeks ago or an hour ago.
581                 //
582                 // For no-std builds, we bury our head in the sand and do a full sync on each connection.
583                 #[allow(unused_mut, unused_assignments)]
584                 let mut gossip_start_time = 0;
585                 #[cfg(feature = "std")]
586                 {
587                         gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
588                         if self.should_request_full_sync(&their_node_id) {
589                                 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
590                         } else {
591                                 gossip_start_time -= 60 * 60; // an hour ago
592                         }
593                 }
594
595                 let mut pending_events = self.pending_events.lock().unwrap();
596                 pending_events.push(MessageSendEvent::SendGossipTimestampFilter {
597                         node_id: their_node_id.clone(),
598                         msg: GossipTimestampFilter {
599                                 chain_hash: self.network_graph.chain_hash,
600                                 first_timestamp: gossip_start_time as u32, // 2106 issue!
601                                 timestamp_range: u32::max_value(),
602                         },
603                 });
604                 Ok(())
605         }
606
607         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: ReplyChannelRange) -> Result<(), LightningError> {
608                 // We don't make queries, so should never receive replies. If, in the future, the set
609                 // reconciliation extensions to gossip queries become broadly supported, we should revert
610                 // this code to its state pre-0.0.106.
611                 Ok(())
612         }
613
614         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
615                 // We don't make queries, so should never receive replies. If, in the future, the set
616                 // reconciliation extensions to gossip queries become broadly supported, we should revert
617                 // this code to its state pre-0.0.106.
618                 Ok(())
619         }
620
621         /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
622         /// are in the specified block range. Due to message size limits, large range
623         /// queries may result in several reply messages. This implementation enqueues
624         /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
625         /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
626         /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
627         /// memory constrained systems.
628         fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
629                 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);
630
631                 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
632
633                 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
634                 // If so, we manually cap the ending block to avoid this overflow.
635                 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
636
637                 // Per spec, we must reply to a query. Send an empty message when things are invalid.
638                 if msg.chain_hash != self.network_graph.chain_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
639                         let mut pending_events = self.pending_events.lock().unwrap();
640                         pending_events.push(MessageSendEvent::SendReplyChannelRange {
641                                 node_id: their_node_id.clone(),
642                                 msg: ReplyChannelRange {
643                                         chain_hash: msg.chain_hash.clone(),
644                                         first_blocknum: msg.first_blocknum,
645                                         number_of_blocks: msg.number_of_blocks,
646                                         sync_complete: true,
647                                         short_channel_ids: vec![],
648                                 }
649                         });
650                         return Err(LightningError {
651                                 err: String::from("query_channel_range could not be processed"),
652                                 action: ErrorAction::IgnoreError,
653                         });
654                 }
655
656                 // Creates channel batches. We are not checking if the channel is routable
657                 // (has at least one update). A peer may still want to know the channel
658                 // exists even if its not yet routable.
659                 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
660                 let mut channels = self.network_graph.channels.write().unwrap();
661                 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
662                         if let Some(chan_announcement) = &chan.announcement_message {
663                                 // Construct a new batch if last one is full
664                                 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
665                                         batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
666                                 }
667
668                                 let batch = batches.last_mut().unwrap();
669                                 batch.push(chan_announcement.contents.short_channel_id);
670                         }
671                 }
672                 drop(channels);
673
674                 let mut pending_events = self.pending_events.lock().unwrap();
675                 let batch_count = batches.len();
676                 let mut prev_batch_endblock = msg.first_blocknum;
677                 for (batch_index, batch) in batches.into_iter().enumerate() {
678                         // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
679                         // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
680                         //
681                         // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
682                         // reply is >= the previous reply's `first_blocknum` and either exactly the previous
683                         // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
684                         // significant diversion from the requirements set by the spec, and, in case of blocks
685                         // with no channel opens (e.g. empty blocks), requires that we use the previous value
686                         // and *not* derive the first_blocknum from the actual first block of the reply.
687                         let first_blocknum = prev_batch_endblock;
688
689                         // Each message carries the number of blocks (from the `first_blocknum`) its contents
690                         // fit in. Though there is no requirement that we use exactly the number of blocks its
691                         // contents are from, except for the bogus requirements c-lightning enforces, above.
692                         //
693                         // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
694                         // >= the query's end block. Thus, for the last reply, we calculate the difference
695                         // between the query's end block and the start of the reply.
696                         //
697                         // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
698                         // first_blocknum will be either msg.first_blocknum or a higher block height.
699                         let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
700                                 (true, msg.end_blocknum() - first_blocknum)
701                         }
702                         // Prior replies should use the number of blocks that fit into the reply. Overflow
703                         // safe since first_blocknum is always <= last SCID's block.
704                         else {
705                                 (false, block_from_scid(*batch.last().unwrap()) - first_blocknum)
706                         };
707
708                         prev_batch_endblock = first_blocknum + number_of_blocks;
709
710                         pending_events.push(MessageSendEvent::SendReplyChannelRange {
711                                 node_id: their_node_id.clone(),
712                                 msg: ReplyChannelRange {
713                                         chain_hash: msg.chain_hash.clone(),
714                                         first_blocknum,
715                                         number_of_blocks,
716                                         sync_complete,
717                                         short_channel_ids: batch,
718                                 }
719                         });
720                 }
721
722                 Ok(())
723         }
724
725         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
726                 // TODO
727                 Err(LightningError {
728                         err: String::from("Not implemented"),
729                         action: ErrorAction::IgnoreError,
730                 })
731         }
732
733         fn provided_node_features(&self) -> NodeFeatures {
734                 let mut features = NodeFeatures::empty();
735                 features.set_gossip_queries_optional();
736                 features
737         }
738
739         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
740                 let mut features = InitFeatures::empty();
741                 features.set_gossip_queries_optional();
742                 features
743         }
744
745         fn processing_queue_high(&self) -> bool {
746                 self.network_graph.pending_checks.too_many_checks_pending()
747         }
748 }
749
750 impl<G: Deref<Target=NetworkGraph<L>>, U: Deref, L: Deref> MessageSendEventsProvider for P2PGossipSync<G, U, L>
751 where
752         U::Target: UtxoLookup,
753         L::Target: Logger,
754 {
755         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
756                 let mut ret = Vec::new();
757                 let mut pending_events = self.pending_events.lock().unwrap();
758                 core::mem::swap(&mut ret, &mut pending_events);
759                 ret
760         }
761 }
762
763 #[derive(Clone, Debug, PartialEq, Eq)]
764 /// Details about one direction of a channel as received within a [`ChannelUpdate`].
765 pub struct ChannelUpdateInfo {
766         /// When the last update to the channel direction was issued.
767         /// Value is opaque, as set in the announcement.
768         pub last_update: u32,
769         /// Whether the channel can be currently used for payments (in this one direction).
770         pub enabled: bool,
771         /// The difference in CLTV values that you must have when routing through this channel.
772         pub cltv_expiry_delta: u16,
773         /// The minimum value, which must be relayed to the next hop via the channel
774         pub htlc_minimum_msat: u64,
775         /// The maximum value which may be relayed to the next hop via the channel.
776         pub htlc_maximum_msat: u64,
777         /// Fees charged when the channel is used for routing
778         pub fees: RoutingFees,
779         /// Most recent update for the channel received from the network
780         /// Mostly redundant with the data we store in fields explicitly.
781         /// Everything else is useful only for sending out for initial routing sync.
782         /// Not stored if contains excess data to prevent DoS.
783         pub last_update_message: Option<ChannelUpdate>,
784 }
785
786 impl fmt::Display for ChannelUpdateInfo {
787         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
788                 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)?;
789                 Ok(())
790         }
791 }
792
793 impl Writeable for ChannelUpdateInfo {
794         fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
795                 write_tlv_fields!(writer, {
796                         (0, self.last_update, required),
797                         (2, self.enabled, required),
798                         (4, self.cltv_expiry_delta, required),
799                         (6, self.htlc_minimum_msat, required),
800                         // Writing htlc_maximum_msat as an Option<u64> is required to maintain backwards
801                         // compatibility with LDK versions prior to v0.0.110.
802                         (8, Some(self.htlc_maximum_msat), required),
803                         (10, self.fees, required),
804                         (12, self.last_update_message, required),
805                 });
806                 Ok(())
807         }
808 }
809
810 impl Readable for ChannelUpdateInfo {
811         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
812                 _init_tlv_field_var!(last_update, required);
813                 _init_tlv_field_var!(enabled, required);
814                 _init_tlv_field_var!(cltv_expiry_delta, required);
815                 _init_tlv_field_var!(htlc_minimum_msat, required);
816                 _init_tlv_field_var!(htlc_maximum_msat, option);
817                 _init_tlv_field_var!(fees, required);
818                 _init_tlv_field_var!(last_update_message, required);
819
820                 read_tlv_fields!(reader, {
821                         (0, last_update, required),
822                         (2, enabled, required),
823                         (4, cltv_expiry_delta, required),
824                         (6, htlc_minimum_msat, required),
825                         (8, htlc_maximum_msat, required),
826                         (10, fees, required),
827                         (12, last_update_message, required)
828                 });
829
830                 if let Some(htlc_maximum_msat) = htlc_maximum_msat {
831                         Ok(ChannelUpdateInfo {
832                                 last_update: _init_tlv_based_struct_field!(last_update, required),
833                                 enabled: _init_tlv_based_struct_field!(enabled, required),
834                                 cltv_expiry_delta: _init_tlv_based_struct_field!(cltv_expiry_delta, required),
835                                 htlc_minimum_msat: _init_tlv_based_struct_field!(htlc_minimum_msat, required),
836                                 htlc_maximum_msat,
837                                 fees: _init_tlv_based_struct_field!(fees, required),
838                                 last_update_message: _init_tlv_based_struct_field!(last_update_message, required),
839                         })
840                 } else {
841                         Err(DecodeError::InvalidValue)
842                 }
843         }
844 }
845
846 #[derive(Clone, Debug, Eq)]
847 /// Details about a channel (both directions).
848 /// Received within a channel announcement.
849 pub struct ChannelInfo {
850         /// Protocol features of a channel communicated during its announcement
851         pub features: ChannelFeatures,
852         /// Source node of the first direction of a channel
853         pub node_one: NodeId,
854         /// Details about the first direction of a channel
855         pub one_to_two: Option<ChannelUpdateInfo>,
856         /// Source node of the second direction of a channel
857         pub node_two: NodeId,
858         /// Details about the second direction of a channel
859         pub two_to_one: Option<ChannelUpdateInfo>,
860         /// The channel capacity as seen on-chain, if chain lookup is available.
861         pub capacity_sats: Option<u64>,
862         /// An initial announcement of the channel
863         /// Mostly redundant with the data we store in fields explicitly.
864         /// Everything else is useful only for sending out for initial routing sync.
865         /// Not stored if contains excess data to prevent DoS.
866         pub announcement_message: Option<ChannelAnnouncement>,
867         /// The timestamp when we received the announcement, if we are running with feature = "std"
868         /// (which we can probably assume we are - no-std environments probably won't have a full
869         /// network graph in memory!).
870         announcement_received_time: u64,
871
872         /// The [`NodeInfo::node_counter`] of the node pointed to by [`Self::node_one`].
873         pub(crate) node_one_counter: u32,
874         /// The [`NodeInfo::node_counter`] of the node pointed to by [`Self::node_two`].
875         pub(crate) node_two_counter: u32,
876 }
877
878 impl PartialEq for ChannelInfo {
879         fn eq(&self, o: &ChannelInfo) -> bool {
880                 self.features == o.features &&
881                         self.node_one == o.node_one &&
882                         self.one_to_two == o.one_to_two &&
883                         self.node_two == o.node_two &&
884                         self.two_to_one == o.two_to_one &&
885                         self.capacity_sats == o.capacity_sats &&
886                         self.announcement_message == o.announcement_message &&
887                         self.announcement_received_time == o.announcement_received_time
888         }
889 }
890
891 impl ChannelInfo {
892         /// Returns a [`DirectedChannelInfo`] for the channel directed to the given `target` from a
893         /// returned `source`, or `None` if `target` is not one of the channel's counterparties.
894         pub fn as_directed_to(&self, target: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
895                 let (direction, source, outbound) = {
896                         if target == &self.node_one {
897                                 (self.two_to_one.as_ref(), &self.node_two, false)
898                         } else if target == &self.node_two {
899                                 (self.one_to_two.as_ref(), &self.node_one, true)
900                         } else {
901                                 return None;
902                         }
903                 };
904                 direction.map(|dir| (DirectedChannelInfo::new(self, dir, outbound), source))
905         }
906
907         /// Returns a [`DirectedChannelInfo`] for the channel directed from the given `source` to a
908         /// returned `target`, or `None` if `source` is not one of the channel's counterparties.
909         pub fn as_directed_from(&self, source: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
910                 let (direction, target, outbound) = {
911                         if source == &self.node_one {
912                                 (self.one_to_two.as_ref(), &self.node_two, true)
913                         } else if source == &self.node_two {
914                                 (self.two_to_one.as_ref(), &self.node_one, false)
915                         } else {
916                                 return None;
917                         }
918                 };
919                 direction.map(|dir| (DirectedChannelInfo::new(self, dir, outbound), target))
920         }
921
922         /// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag.
923         pub fn get_directional_info(&self, channel_flags: u8) -> Option<&ChannelUpdateInfo> {
924                 let direction = channel_flags & 1u8;
925                 if direction == 0 {
926                         self.one_to_two.as_ref()
927                 } else {
928                         self.two_to_one.as_ref()
929                 }
930         }
931 }
932
933 impl fmt::Display for ChannelInfo {
934         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
935                 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
936                    log_bytes!(self.features.encode()), &self.node_one, self.one_to_two, &self.node_two, self.two_to_one)?;
937                 Ok(())
938         }
939 }
940
941 impl Writeable for ChannelInfo {
942         fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
943                 write_tlv_fields!(writer, {
944                         (0, self.features, required),
945                         (1, self.announcement_received_time, (default_value, 0)),
946                         (2, self.node_one, required),
947                         (4, self.one_to_two, required),
948                         (6, self.node_two, required),
949                         (8, self.two_to_one, required),
950                         (10, self.capacity_sats, required),
951                         (12, self.announcement_message, required),
952                 });
953                 Ok(())
954         }
955 }
956
957 // A wrapper allowing for the optional deseralization of ChannelUpdateInfo. Utilizing this is
958 // necessary to maintain backwards compatibility with previous serializations of `ChannelUpdateInfo`
959 // that may have no `htlc_maximum_msat` field set. In case the field is absent, we simply ignore
960 // the error and continue reading the `ChannelInfo`. Hopefully, we'll then eventually receive newer
961 // channel updates via the gossip network.
962 struct ChannelUpdateInfoDeserWrapper(Option<ChannelUpdateInfo>);
963
964 impl MaybeReadable for ChannelUpdateInfoDeserWrapper {
965         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
966                 match crate::util::ser::Readable::read(reader) {
967                         Ok(channel_update_option) => Ok(Some(Self(channel_update_option))),
968                         Err(DecodeError::ShortRead) => Ok(None),
969                         Err(DecodeError::InvalidValue) => Ok(None),
970                         Err(err) => Err(err),
971                 }
972         }
973 }
974
975 impl Readable for ChannelInfo {
976         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
977                 _init_tlv_field_var!(features, required);
978                 _init_tlv_field_var!(announcement_received_time, (default_value, 0));
979                 _init_tlv_field_var!(node_one, required);
980                 let mut one_to_two_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
981                 _init_tlv_field_var!(node_two, required);
982                 let mut two_to_one_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
983                 _init_tlv_field_var!(capacity_sats, required);
984                 _init_tlv_field_var!(announcement_message, required);
985                 read_tlv_fields!(reader, {
986                         (0, features, required),
987                         (1, announcement_received_time, (default_value, 0)),
988                         (2, node_one, required),
989                         (4, one_to_two_wrap, upgradable_option),
990                         (6, node_two, required),
991                         (8, two_to_one_wrap, upgradable_option),
992                         (10, capacity_sats, required),
993                         (12, announcement_message, required),
994                 });
995
996                 Ok(ChannelInfo {
997                         features: _init_tlv_based_struct_field!(features, required),
998                         node_one: _init_tlv_based_struct_field!(node_one, required),
999                         one_to_two: one_to_two_wrap.map(|w| w.0).unwrap_or(None),
1000                         node_two: _init_tlv_based_struct_field!(node_two, required),
1001                         two_to_one: two_to_one_wrap.map(|w| w.0).unwrap_or(None),
1002                         capacity_sats: _init_tlv_based_struct_field!(capacity_sats, required),
1003                         announcement_message: _init_tlv_based_struct_field!(announcement_message, required),
1004                         announcement_received_time: _init_tlv_based_struct_field!(announcement_received_time, (default_value, 0)),
1005                         node_one_counter: u32::max_value(),
1006                         node_two_counter: u32::max_value(),
1007                 })
1008         }
1009 }
1010
1011 /// A wrapper around [`ChannelInfo`] representing information about the channel as directed from a
1012 /// source node to a target node.
1013 #[derive(Clone)]
1014 pub struct DirectedChannelInfo<'a> {
1015         channel: &'a ChannelInfo,
1016         direction: &'a ChannelUpdateInfo,
1017         /// The direction this channel is in - if set, it indicates that we're traversing the channel
1018         /// from [`ChannelInfo::node_one`] to [`ChannelInfo::node_two`].
1019         from_node_one: bool,
1020 }
1021
1022 impl<'a> DirectedChannelInfo<'a> {
1023         #[inline]
1024         fn new(channel: &'a ChannelInfo, direction: &'a ChannelUpdateInfo, from_node_one: bool) -> Self {
1025                 Self { channel, direction, from_node_one }
1026         }
1027
1028         /// Returns information for the channel.
1029         #[inline]
1030         pub fn channel(&self) -> &'a ChannelInfo { self.channel }
1031
1032         /// Returns the [`EffectiveCapacity`] of the channel in the direction.
1033         ///
1034         /// This is either the total capacity from the funding transaction, if known, or the
1035         /// `htlc_maximum_msat` for the direction as advertised by the gossip network, if known,
1036         /// otherwise.
1037         #[inline]
1038         pub fn effective_capacity(&self) -> EffectiveCapacity {
1039                 let mut htlc_maximum_msat = self.direction().htlc_maximum_msat;
1040                 let capacity_msat = self.channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000);
1041
1042                 match capacity_msat {
1043                         Some(capacity_msat) => {
1044                                 htlc_maximum_msat = cmp::min(htlc_maximum_msat, capacity_msat);
1045                                 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat }
1046                         },
1047                         None => EffectiveCapacity::AdvertisedMaxHTLC { amount_msat: htlc_maximum_msat },
1048                 }
1049         }
1050
1051         /// Returns information for the direction.
1052         #[inline]
1053         pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.direction }
1054
1055         /// Returns the `node_id` of the source hop.
1056         ///
1057         /// Refers to the `node_id` forwarding the payment to the next hop.
1058         #[inline]
1059         pub fn source(&self) -> &'a NodeId { if self.from_node_one { &self.channel.node_one } else { &self.channel.node_two } }
1060
1061         /// Returns the `node_id` of the target hop.
1062         ///
1063         /// Refers to the `node_id` receiving the payment from the previous hop.
1064         #[inline]
1065         pub fn target(&self) -> &'a NodeId { if self.from_node_one { &self.channel.node_two } else { &self.channel.node_one } }
1066
1067         /// Returns the source node's counter
1068         #[inline]
1069         pub(super) fn source_counter(&self) -> u32 { if self.from_node_one { self.channel.node_one_counter } else { self.channel.node_two_counter } }
1070
1071         /// Returns the target node's counter
1072         #[inline]
1073         pub(super) fn target_counter(&self) -> u32 { if self.from_node_one { self.channel.node_two_counter } else { self.channel.node_one_counter } }
1074 }
1075
1076 impl<'a> fmt::Debug for DirectedChannelInfo<'a> {
1077         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1078                 f.debug_struct("DirectedChannelInfo")
1079                         .field("channel", &self.channel)
1080                         .finish()
1081         }
1082 }
1083
1084 /// The effective capacity of a channel for routing purposes.
1085 ///
1086 /// While this may be smaller than the actual channel capacity, amounts greater than
1087 /// [`Self::as_msat`] should not be routed through the channel.
1088 #[derive(Clone, Copy, Debug, PartialEq)]
1089 pub enum EffectiveCapacity {
1090         /// The available liquidity in the channel known from being a channel counterparty, and thus a
1091         /// direct hop.
1092         ExactLiquidity {
1093                 /// Either the inbound or outbound liquidity depending on the direction, denominated in
1094                 /// millisatoshi.
1095                 liquidity_msat: u64,
1096         },
1097         /// The maximum HTLC amount in one direction as advertised on the gossip network.
1098         AdvertisedMaxHTLC {
1099                 /// The maximum HTLC amount denominated in millisatoshi.
1100                 amount_msat: u64,
1101         },
1102         /// The total capacity of the channel as determined by the funding transaction.
1103         Total {
1104                 /// The funding amount denominated in millisatoshi.
1105                 capacity_msat: u64,
1106                 /// The maximum HTLC amount denominated in millisatoshi.
1107                 htlc_maximum_msat: u64
1108         },
1109         /// A capacity sufficient to route any payment, typically used for private channels provided by
1110         /// an invoice.
1111         Infinite,
1112         /// The maximum HTLC amount as provided by an invoice route hint.
1113         HintMaxHTLC {
1114                 /// The maximum HTLC amount denominated in millisatoshi.
1115                 amount_msat: u64,
1116         },
1117         /// A capacity that is unknown possibly because either the chain state is unavailable to know
1118         /// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
1119         Unknown,
1120 }
1121
1122 /// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
1123 /// use when making routing decisions.
1124 pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
1125
1126 impl EffectiveCapacity {
1127         /// Returns the effective capacity denominated in millisatoshi.
1128         pub fn as_msat(&self) -> u64 {
1129                 match self {
1130                         EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
1131                         EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } => *amount_msat,
1132                         EffectiveCapacity::Total { capacity_msat, .. } => *capacity_msat,
1133                         EffectiveCapacity::HintMaxHTLC { amount_msat } => *amount_msat,
1134                         EffectiveCapacity::Infinite => u64::max_value(),
1135                         EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
1136                 }
1137         }
1138 }
1139
1140 /// Fees for routing via a given channel or a node
1141 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash, Ord, PartialOrd)]
1142 pub struct RoutingFees {
1143         /// Flat routing fee in millisatoshis.
1144         pub base_msat: u32,
1145         /// Liquidity-based routing fee in millionths of a routed amount.
1146         /// In other words, 10000 is 1%.
1147         pub proportional_millionths: u32,
1148 }
1149
1150 impl_writeable_tlv_based!(RoutingFees, {
1151         (0, base_msat, required),
1152         (2, proportional_millionths, required)
1153 });
1154
1155 #[derive(Clone, Debug, PartialEq, Eq)]
1156 /// Information received in the latest node_announcement from this node.
1157 pub struct NodeAnnouncementInfo {
1158         /// Protocol features the node announced support for
1159         pub features: NodeFeatures,
1160         /// When the last known update to the node state was issued.
1161         /// Value is opaque, as set in the announcement.
1162         pub last_update: u32,
1163         /// Color assigned to the node
1164         pub rgb: [u8; 3],
1165         /// Moniker assigned to the node.
1166         /// May be invalid or malicious (eg control chars),
1167         /// should not be exposed to the user.
1168         pub alias: NodeAlias,
1169         /// An initial announcement of the node
1170         /// Mostly redundant with the data we store in fields explicitly.
1171         /// Everything else is useful only for sending out for initial routing sync.
1172         /// Not stored if contains excess data to prevent DoS.
1173         pub announcement_message: Option<NodeAnnouncement>
1174 }
1175
1176 impl NodeAnnouncementInfo {
1177         /// Internet-level addresses via which one can connect to the node
1178         pub fn addresses(&self) -> &[SocketAddress] {
1179                 self.announcement_message.as_ref()
1180                         .map(|msg| msg.contents.addresses.as_slice())
1181                         .unwrap_or_default()
1182         }
1183 }
1184
1185 impl Writeable for NodeAnnouncementInfo {
1186         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1187                 let empty_addresses = Vec::<SocketAddress>::new();
1188                 write_tlv_fields!(writer, {
1189                         (0, self.features, required),
1190                         (2, self.last_update, required),
1191                         (4, self.rgb, required),
1192                         (6, self.alias, required),
1193                         (8, self.announcement_message, option),
1194                         (10, empty_addresses, required_vec), // Versions prior to 0.0.115 require this field
1195                 });
1196                 Ok(())
1197         }
1198 }
1199
1200 impl Readable for NodeAnnouncementInfo {
1201         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1202                 _init_and_read_len_prefixed_tlv_fields!(reader, {
1203                         (0, features, required),
1204                         (2, last_update, required),
1205                         (4, rgb, required),
1206                         (6, alias, required),
1207                         (8, announcement_message, option),
1208                         (10, _addresses, optional_vec), // deprecated, not used anymore
1209                 });
1210                 let _: Option<Vec<SocketAddress>> = _addresses;
1211                 Ok(Self { features: features.0.unwrap(), last_update: last_update.0.unwrap(), rgb: rgb.0.unwrap(),
1212                         alias: alias.0.unwrap(), announcement_message })
1213         }
1214 }
1215
1216 /// A user-defined name for a node, which may be used when displaying the node in a graph.
1217 ///
1218 /// Since node aliases are provided by third parties, they are a potential avenue for injection
1219 /// attacks. Care must be taken when processing.
1220 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
1221 pub struct NodeAlias(pub [u8; 32]);
1222
1223 impl fmt::Display for NodeAlias {
1224         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1225                 let first_null = self.0.iter().position(|b| *b == 0).unwrap_or(self.0.len());
1226                 let bytes = self.0.split_at(first_null).0;
1227                 match core::str::from_utf8(bytes) {
1228                         Ok(alias) => PrintableString(alias).fmt(f)?,
1229                         Err(_) => {
1230                                 use core::fmt::Write;
1231                                 for c in bytes.iter().map(|b| *b as char) {
1232                                         // Display printable ASCII characters
1233                                         let control_symbol = core::char::REPLACEMENT_CHARACTER;
1234                                         let c = if c >= '\x20' && c <= '\x7e' { c } else { control_symbol };
1235                                         f.write_char(c)?;
1236                                 }
1237                         },
1238                 };
1239                 Ok(())
1240         }
1241 }
1242
1243 impl Writeable for NodeAlias {
1244         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1245                 self.0.write(w)
1246         }
1247 }
1248
1249 impl Readable for NodeAlias {
1250         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
1251                 Ok(NodeAlias(Readable::read(r)?))
1252         }
1253 }
1254
1255 #[derive(Clone, Debug, Eq)]
1256 /// Details about a node in the network, known from the network announcement.
1257 pub struct NodeInfo {
1258         /// All valid channels a node has announced
1259         pub channels: Vec<u64>,
1260         /// More information about a node from node_announcement.
1261         /// Optional because we store a Node entry after learning about it from
1262         /// a channel announcement, but before receiving a node announcement.
1263         pub announcement_info: Option<NodeAnnouncementInfo>,
1264         /// In memory, each node is assigned a unique ID. They are eagerly reused, ensuring they remain
1265         /// relatively dense.
1266         ///
1267         /// These IDs allow the router to avoid a `HashMap` lookup by simply using this value as an
1268         /// index in a `Vec`, skipping a big step in some of the hottest code when routing.
1269         pub(crate) node_counter: u32,
1270 }
1271
1272 impl PartialEq for NodeInfo {
1273         fn eq(&self, o: &NodeInfo) -> bool {
1274                 self.channels == o.channels && self.announcement_info == o.announcement_info
1275         }
1276 }
1277
1278 impl NodeInfo {
1279         /// Returns whether the node has only announced Tor addresses.
1280         pub fn is_tor_only(&self) -> bool {
1281                 self.announcement_info
1282                         .as_ref()
1283                         .map(|info| info.addresses())
1284                         .and_then(|addresses| (!addresses.is_empty()).then(|| addresses))
1285                         .map(|addresses| addresses.iter().all(|address| address.is_tor()))
1286                         .unwrap_or(false)
1287         }
1288 }
1289
1290 impl fmt::Display for NodeInfo {
1291         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1292                 write!(f, " channels: {:?}, announcement_info: {:?}",
1293                         &self.channels[..], self.announcement_info)?;
1294                 Ok(())
1295         }
1296 }
1297
1298 impl Writeable for NodeInfo {
1299         fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1300                 write_tlv_fields!(writer, {
1301                         // Note that older versions of LDK wrote the lowest inbound fees here at type 0
1302                         (2, self.announcement_info, option),
1303                         (4, self.channels, required_vec),
1304                 });
1305                 Ok(())
1306         }
1307 }
1308
1309 // A wrapper allowing for the optional deserialization of `NodeAnnouncementInfo`. Utilizing this is
1310 // necessary to maintain compatibility with previous serializations of `SocketAddress` that have an
1311 // invalid hostname set. We ignore and eat all errors until we are either able to read a
1312 // `NodeAnnouncementInfo` or hit a `ShortRead`, i.e., read the TLV field to the end.
1313 struct NodeAnnouncementInfoDeserWrapper(NodeAnnouncementInfo);
1314
1315 impl MaybeReadable for NodeAnnouncementInfoDeserWrapper {
1316         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
1317                 match crate::util::ser::Readable::read(reader) {
1318                         Ok(node_announcement_info) => return Ok(Some(Self(node_announcement_info))),
1319                         Err(_) => {
1320                                 copy(reader, &mut sink()).unwrap();
1321                                 return Ok(None)
1322                         },
1323                 };
1324         }
1325 }
1326
1327 impl Readable for NodeInfo {
1328         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1329                 // Historically, we tracked the lowest inbound fees for any node in order to use it as an
1330                 // A* heuristic when routing. Sadly, these days many, many nodes have at least one channel
1331                 // with zero inbound fees, causing that heuristic to provide little gain. Worse, because it
1332                 // requires additional complexity and lookups during routing, it ends up being a
1333                 // performance loss. Thus, we simply ignore the old field here and no longer track it.
1334                 _init_and_read_len_prefixed_tlv_fields!(reader, {
1335                         (0, _lowest_inbound_channel_fees, option),
1336                         (2, announcement_info_wrap, upgradable_option),
1337                         (4, channels, required_vec),
1338                 });
1339                 let _: Option<RoutingFees> = _lowest_inbound_channel_fees;
1340                 let announcement_info_wrap: Option<NodeAnnouncementInfoDeserWrapper> = announcement_info_wrap;
1341
1342                 Ok(NodeInfo {
1343                         announcement_info: announcement_info_wrap.map(|w| w.0),
1344                         channels,
1345                         node_counter: u32::max_value(),
1346                 })
1347         }
1348 }
1349
1350 const SERIALIZATION_VERSION: u8 = 1;
1351 const MIN_SERIALIZATION_VERSION: u8 = 1;
1352
1353 impl<L: Deref> Writeable for NetworkGraph<L> where L::Target: Logger {
1354         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1355                 self.test_node_counter_consistency();
1356
1357                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1358
1359                 self.chain_hash.write(writer)?;
1360                 let channels = self.channels.read().unwrap();
1361                 (channels.len() as u64).write(writer)?;
1362                 for (ref chan_id, ref chan_info) in channels.unordered_iter() {
1363                         (*chan_id).write(writer)?;
1364                         chan_info.write(writer)?;
1365                 }
1366                 let nodes = self.nodes.read().unwrap();
1367                 (nodes.len() as u64).write(writer)?;
1368                 for (ref node_id, ref node_info) in nodes.unordered_iter() {
1369                         node_id.write(writer)?;
1370                         node_info.write(writer)?;
1371                 }
1372
1373                 let last_rapid_gossip_sync_timestamp = self.get_last_rapid_gossip_sync_timestamp();
1374                 write_tlv_fields!(writer, {
1375                         (1, last_rapid_gossip_sync_timestamp, option),
1376                 });
1377                 Ok(())
1378         }
1379 }
1380
1381 impl<L: Deref> ReadableArgs<L> for NetworkGraph<L> where L::Target: Logger {
1382         fn read<R: io::Read>(reader: &mut R, logger: L) -> Result<NetworkGraph<L>, DecodeError> {
1383                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1384
1385                 let chain_hash: ChainHash = Readable::read(reader)?;
1386                 let channels_count: u64 = Readable::read(reader)?;
1387                 // In Nov, 2023 there were about 15,000 nodes; we cap allocations to 1.5x that.
1388                 let mut channels = IndexedMap::with_capacity(cmp::min(channels_count as usize, 22500));
1389                 for _ in 0..channels_count {
1390                         let chan_id: u64 = Readable::read(reader)?;
1391                         let chan_info: ChannelInfo = Readable::read(reader)?;
1392                         channels.insert(chan_id, chan_info);
1393                 }
1394                 let nodes_count: u64 = Readable::read(reader)?;
1395                 if nodes_count > u32::max_value() as u64 / 2 { return Err(DecodeError::InvalidValue); }
1396                 // In Nov, 2023 there were about 69K channels; we cap allocations to 1.5x that.
1397                 let mut nodes = IndexedMap::with_capacity(cmp::min(nodes_count as usize, 103500));
1398                 for i in 0..nodes_count {
1399                         let node_id = Readable::read(reader)?;
1400                         let mut node_info: NodeInfo = Readable::read(reader)?;
1401                         node_info.node_counter = i as u32;
1402                         nodes.insert(node_id, node_info);
1403                 }
1404
1405                 for (_, chan) in channels.unordered_iter_mut() {
1406                         chan.node_one_counter =
1407                                 nodes.get(&chan.node_one).ok_or(DecodeError::InvalidValue)?.node_counter;
1408                         chan.node_two_counter =
1409                                 nodes.get(&chan.node_two).ok_or(DecodeError::InvalidValue)?.node_counter;
1410                 }
1411
1412                 let mut last_rapid_gossip_sync_timestamp: Option<u32> = None;
1413                 read_tlv_fields!(reader, {
1414                         (1, last_rapid_gossip_sync_timestamp, option),
1415                 });
1416
1417                 Ok(NetworkGraph {
1418                         secp_ctx: Secp256k1::verification_only(),
1419                         chain_hash,
1420                         logger,
1421                         channels: RwLock::new(channels),
1422                         nodes: RwLock::new(nodes),
1423                         removed_node_counters: Mutex::new(Vec::new()),
1424                         next_node_counter: AtomicUsize::new(nodes_count as usize),
1425                         last_rapid_gossip_sync_timestamp: Mutex::new(last_rapid_gossip_sync_timestamp),
1426                         removed_nodes: Mutex::new(new_hash_map()),
1427                         removed_channels: Mutex::new(new_hash_map()),
1428                         pending_checks: utxo::PendingChecks::new(),
1429                 })
1430         }
1431 }
1432
1433 impl<L: Deref> fmt::Display for NetworkGraph<L> where L::Target: Logger {
1434         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1435                 writeln!(f, "Network map\n[Channels]")?;
1436                 for (key, val) in self.channels.read().unwrap().unordered_iter() {
1437                         writeln!(f, " {}: {}", key, val)?;
1438                 }
1439                 writeln!(f, "[Nodes]")?;
1440                 for (&node_id, val) in self.nodes.read().unwrap().unordered_iter() {
1441                         writeln!(f, " {}: {}", &node_id, val)?;
1442                 }
1443                 Ok(())
1444         }
1445 }
1446
1447 impl<L: Deref> Eq for NetworkGraph<L> where L::Target: Logger {}
1448 impl<L: Deref> PartialEq for NetworkGraph<L> where L::Target: Logger {
1449         fn eq(&self, other: &Self) -> bool {
1450                 // For a total lockorder, sort by position in memory and take the inner locks in that order.
1451                 // (Assumes that we can't move within memory while a lock is held).
1452                 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1453                 let a = if ord { (&self.channels, &self.nodes) } else { (&other.channels, &other.nodes) };
1454                 let b = if ord { (&other.channels, &other.nodes) } else { (&self.channels, &self.nodes) };
1455                 let (channels_a, channels_b) = (a.0.unsafe_well_ordered_double_lock_self(), b.0.unsafe_well_ordered_double_lock_self());
1456                 let (nodes_a, nodes_b) = (a.1.unsafe_well_ordered_double_lock_self(), b.1.unsafe_well_ordered_double_lock_self());
1457                 self.chain_hash.eq(&other.chain_hash) && channels_a.eq(&channels_b) && nodes_a.eq(&nodes_b)
1458         }
1459 }
1460
1461 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
1462         /// Creates a new, empty, network graph.
1463         pub fn new(network: Network, logger: L) -> NetworkGraph<L> {
1464                 Self {
1465                         secp_ctx: Secp256k1::verification_only(),
1466                         chain_hash: ChainHash::using_genesis_block(network),
1467                         logger,
1468                         channels: RwLock::new(IndexedMap::new()),
1469                         nodes: RwLock::new(IndexedMap::new()),
1470                         next_node_counter: AtomicUsize::new(0),
1471                         removed_node_counters: Mutex::new(Vec::new()),
1472                         last_rapid_gossip_sync_timestamp: Mutex::new(None),
1473                         removed_channels: Mutex::new(new_hash_map()),
1474                         removed_nodes: Mutex::new(new_hash_map()),
1475                         pending_checks: utxo::PendingChecks::new(),
1476                 }
1477         }
1478
1479         fn test_node_counter_consistency(&self) {
1480                 #[cfg(debug_assertions)] {
1481                         let channels = self.channels.read().unwrap();
1482                         let nodes = self.nodes.read().unwrap();
1483                         let removed_node_counters = self.removed_node_counters.lock().unwrap();
1484                         let next_counter = self.next_node_counter.load(Ordering::Acquire);
1485                         assert!(next_counter < (u32::max_value() as usize) / 2);
1486                         let mut used_node_counters = vec![0u8; next_counter / 8 + 1];
1487
1488                         for counter in removed_node_counters.iter() {
1489                                 let pos = (*counter as usize) / 8;
1490                                 let bit = 1 << (counter % 8);
1491                                 assert_eq!(used_node_counters[pos] & bit, 0);
1492                                 used_node_counters[pos] |= bit;
1493                         }
1494                         for (_, node) in nodes.unordered_iter() {
1495                                 assert!((node.node_counter as usize) < next_counter);
1496                                 let pos = (node.node_counter as usize) / 8;
1497                                 let bit = 1 << (node.node_counter % 8);
1498                                 assert_eq!(used_node_counters[pos] & bit, 0);
1499                                 used_node_counters[pos] |= bit;
1500                         }
1501
1502                         for (_, chan) in channels.unordered_iter() {
1503                                 assert_eq!(chan.node_one_counter, nodes.get(&chan.node_one).unwrap().node_counter);
1504                                 assert_eq!(chan.node_two_counter, nodes.get(&chan.node_two).unwrap().node_counter);
1505                         }
1506                 }
1507         }
1508
1509         /// Returns a read-only view of the network graph.
1510         pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
1511                 self.test_node_counter_consistency();
1512                 let channels = self.channels.read().unwrap();
1513                 let nodes = self.nodes.read().unwrap();
1514                 ReadOnlyNetworkGraph {
1515                         channels,
1516                         nodes,
1517                         max_node_counter: (self.next_node_counter.load(Ordering::Acquire) as u32).saturating_sub(1),
1518                 }
1519         }
1520
1521         /// The unix timestamp provided by the most recent rapid gossip sync.
1522         /// It will be set by the rapid sync process after every sync completion.
1523         pub fn get_last_rapid_gossip_sync_timestamp(&self) -> Option<u32> {
1524                 self.last_rapid_gossip_sync_timestamp.lock().unwrap().clone()
1525         }
1526
1527         /// Update the unix timestamp provided by the most recent rapid gossip sync.
1528         /// This should be done automatically by the rapid sync process after every sync completion.
1529         pub fn set_last_rapid_gossip_sync_timestamp(&self, last_rapid_gossip_sync_timestamp: u32) {
1530                 self.last_rapid_gossip_sync_timestamp.lock().unwrap().replace(last_rapid_gossip_sync_timestamp);
1531         }
1532
1533         /// Clears the `NodeAnnouncementInfo` field for all nodes in the `NetworkGraph` for testing
1534         /// purposes.
1535         #[cfg(test)]
1536         pub fn clear_nodes_announcement_info(&self) {
1537                 for node in self.nodes.write().unwrap().unordered_iter_mut() {
1538                         node.1.announcement_info = None;
1539                 }
1540         }
1541
1542         /// For an already known node (from channel announcements), update its stored properties from a
1543         /// given node announcement.
1544         ///
1545         /// You probably don't want to call this directly, instead relying on a P2PGossipSync's
1546         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1547         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1548         pub fn update_node_from_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), LightningError> {
1549                 verify_node_announcement(msg, &self.secp_ctx)?;
1550                 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1551         }
1552
1553         /// For an already known node (from channel announcements), update its stored properties from a
1554         /// given node announcement without verifying the associated signatures. Because we aren't
1555         /// given the associated signatures here we cannot relay the node announcement to any of our
1556         /// peers.
1557         pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1558                 self.update_node_from_announcement_intern(msg, None)
1559         }
1560
1561         fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1562                 let mut nodes = self.nodes.write().unwrap();
1563                 match nodes.get_mut(&msg.node_id) {
1564                         None => {
1565                                 core::mem::drop(nodes);
1566                                 self.pending_checks.check_hold_pending_node_announcement(msg, full_msg)?;
1567                                 Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError})
1568                         },
1569                         Some(node) => {
1570                                 if let Some(node_info) = node.announcement_info.as_ref() {
1571                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
1572                                         // updates to ensure you always have the latest one, only vaguely suggesting
1573                                         // that it be at least the current time.
1574                                         if node_info.last_update  > msg.timestamp {
1575                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1576                                         } else if node_info.last_update  == msg.timestamp {
1577                                                 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1578                                         }
1579                                 }
1580
1581                                 let should_relay =
1582                                         msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1583                                         msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1584                                         msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1585                                 node.announcement_info = Some(NodeAnnouncementInfo {
1586                                         features: msg.features.clone(),
1587                                         last_update: msg.timestamp,
1588                                         rgb: msg.rgb,
1589                                         alias: msg.alias,
1590                                         announcement_message: if should_relay { full_msg.cloned() } else { None },
1591                                 });
1592
1593                                 Ok(())
1594                         }
1595                 }
1596         }
1597
1598         /// Store or update channel info from a channel announcement.
1599         ///
1600         /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1601         /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1602         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1603         ///
1604         /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1605         /// the corresponding UTXO exists on chain and is correctly-formatted.
1606         pub fn update_channel_from_announcement<U: Deref>(
1607                 &self, msg: &msgs::ChannelAnnouncement, utxo_lookup: &Option<U>,
1608         ) -> Result<(), LightningError>
1609         where
1610                 U::Target: UtxoLookup,
1611         {
1612                 verify_channel_announcement(msg, &self.secp_ctx)?;
1613                 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), utxo_lookup)
1614         }
1615
1616         /// Store or update channel info from a channel announcement.
1617         ///
1618         /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1619         /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1620         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1621         ///
1622         /// This will skip verification of if the channel is actually on-chain.
1623         pub fn update_channel_from_announcement_no_lookup(
1624                 &self, msg: &ChannelAnnouncement
1625         ) -> Result<(), LightningError> {
1626                 self.update_channel_from_announcement::<&UtxoResolver>(msg, &None)
1627         }
1628
1629         /// Store or update channel info from a channel announcement without verifying the associated
1630         /// signatures. Because we aren't given the associated signatures here we cannot relay the
1631         /// channel announcement to any of our peers.
1632         ///
1633         /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1634         /// the corresponding UTXO exists on chain and is correctly-formatted.
1635         pub fn update_channel_from_unsigned_announcement<U: Deref>(
1636                 &self, msg: &msgs::UnsignedChannelAnnouncement, utxo_lookup: &Option<U>
1637         ) -> Result<(), LightningError>
1638         where
1639                 U::Target: UtxoLookup,
1640         {
1641                 self.update_channel_from_unsigned_announcement_intern(msg, None, utxo_lookup)
1642         }
1643
1644         /// Update channel from partial announcement data received via rapid gossip sync
1645         ///
1646         /// `timestamp: u64`: Timestamp emulating the backdated original announcement receipt (by the
1647         /// rapid gossip sync server)
1648         ///
1649         /// All other parameters as used in [`msgs::UnsignedChannelAnnouncement`] fields.
1650         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> {
1651                 if node_id_1 == node_id_2 {
1652                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1653                 };
1654
1655                 let node_1 = NodeId::from_pubkey(&node_id_1);
1656                 let node_2 = NodeId::from_pubkey(&node_id_2);
1657                 let channel_info = ChannelInfo {
1658                         features,
1659                         node_one: node_1.clone(),
1660                         one_to_two: None,
1661                         node_two: node_2.clone(),
1662                         two_to_one: None,
1663                         capacity_sats: None,
1664                         announcement_message: None,
1665                         announcement_received_time: timestamp,
1666                         node_one_counter: u32::max_value(),
1667                         node_two_counter: u32::max_value(),
1668                 };
1669
1670                 self.add_channel_between_nodes(short_channel_id, channel_info, None)
1671         }
1672
1673         fn add_channel_between_nodes(&self, short_channel_id: u64, channel_info: ChannelInfo, utxo_value: Option<u64>) -> Result<(), LightningError> {
1674                 let mut channels = self.channels.write().unwrap();
1675                 let mut nodes = self.nodes.write().unwrap();
1676
1677                 let node_id_a = channel_info.node_one.clone();
1678                 let node_id_b = channel_info.node_two.clone();
1679
1680                 log_gossip!(self.logger, "Adding channel {} between nodes {} and {}", short_channel_id, node_id_a, node_id_b);
1681
1682                 let channel_entry = channels.entry(short_channel_id);
1683                 let channel_info = match channel_entry {
1684                         IndexedMapEntry::Occupied(mut entry) => {
1685                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1686                                 //in the blockchain API, we need to handle it smartly here, though it's unclear
1687                                 //exactly how...
1688                                 if utxo_value.is_some() {
1689                                         // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1690                                         // only sometimes returns results. In any case remove the previous entry. Note
1691                                         // that the spec expects us to "blacklist" the node_ids involved, but we can't
1692                                         // do that because
1693                                         // a) we don't *require* a UTXO provider that always returns results.
1694                                         // b) we don't track UTXOs of channels we know about and remove them if they
1695                                         //    get reorg'd out.
1696                                         // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1697                                         self.remove_channel_in_nodes(&mut nodes, &entry.get(), short_channel_id);
1698                                         *entry.get_mut() = channel_info;
1699                                         entry.into_mut()
1700                                 } else {
1701                                         return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1702                                 }
1703                         },
1704                         IndexedMapEntry::Vacant(entry) => {
1705                                 entry.insert(channel_info)
1706                         }
1707                 };
1708
1709                 let mut node_counter_id = [
1710                         (&mut channel_info.node_one_counter, node_id_a),
1711                         (&mut channel_info.node_two_counter, node_id_b)
1712                 ];
1713                 for (node_counter, current_node_id) in node_counter_id.iter_mut() {
1714                         match nodes.entry(current_node_id.clone()) {
1715                                 IndexedMapEntry::Occupied(node_entry) => {
1716                                         let node = node_entry.into_mut();
1717                                         node.channels.push(short_channel_id);
1718                                         **node_counter = node.node_counter;
1719                                 },
1720                                 IndexedMapEntry::Vacant(node_entry) => {
1721                                         let mut removed_node_counters = self.removed_node_counters.lock().unwrap();
1722                                         **node_counter = removed_node_counters.pop()
1723                                                 .unwrap_or(self.next_node_counter.fetch_add(1, Ordering::Relaxed) as u32);
1724                                         node_entry.insert(NodeInfo {
1725                                                 channels: vec!(short_channel_id),
1726                                                 announcement_info: None,
1727                                                 node_counter: **node_counter,
1728                                         });
1729                                 }
1730                         };
1731                 };
1732
1733                 Ok(())
1734         }
1735
1736         fn update_channel_from_unsigned_announcement_intern<U: Deref>(
1737                 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, utxo_lookup: &Option<U>
1738         ) -> Result<(), LightningError>
1739         where
1740                 U::Target: UtxoLookup,
1741         {
1742                 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1743                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1744                 }
1745
1746                 if msg.chain_hash != self.chain_hash {
1747                         return Err(LightningError {
1748                                 err: "Channel announcement chain hash does not match genesis hash".to_owned(),
1749                                 action: ErrorAction::IgnoreAndLog(Level::Debug),
1750                         });
1751                 }
1752
1753                 {
1754                         let channels = self.channels.read().unwrap();
1755
1756                         if let Some(chan) = channels.get(&msg.short_channel_id) {
1757                                 if chan.capacity_sats.is_some() {
1758                                         // If we'd previously looked up the channel on-chain and checked the script
1759                                         // against what appears on-chain, ignore the duplicate announcement.
1760                                         //
1761                                         // Because a reorg could replace one channel with another at the same SCID, if
1762                                         // the channel appears to be different, we re-validate. This doesn't expose us
1763                                         // to any more DoS risk than not, as a peer can always flood us with
1764                                         // randomly-generated SCID values anyway.
1765                                         //
1766                                         // We use the Node IDs rather than the bitcoin_keys to check for "equivalence"
1767                                         // as we didn't (necessarily) store the bitcoin keys, and we only really care
1768                                         // if the peers on the channel changed anyway.
1769                                         if msg.node_id_1 == chan.node_one && msg.node_id_2 == chan.node_two {
1770                                                 return Err(LightningError {
1771                                                         err: "Already have chain-validated channel".to_owned(),
1772                                                         action: ErrorAction::IgnoreDuplicateGossip
1773                                                 });
1774                                         }
1775                                 } else if utxo_lookup.is_none() {
1776                                         // Similarly, if we can't check the chain right now anyway, ignore the
1777                                         // duplicate announcement without bothering to take the channels write lock.
1778                                         return Err(LightningError {
1779                                                 err: "Already have non-chain-validated channel".to_owned(),
1780                                                 action: ErrorAction::IgnoreDuplicateGossip
1781                                         });
1782                                 }
1783                         }
1784                 }
1785
1786                 {
1787                         let removed_channels = self.removed_channels.lock().unwrap();
1788                         let removed_nodes = self.removed_nodes.lock().unwrap();
1789                         if removed_channels.contains_key(&msg.short_channel_id) ||
1790                                 removed_nodes.contains_key(&msg.node_id_1) ||
1791                                 removed_nodes.contains_key(&msg.node_id_2) {
1792                                 return Err(LightningError{
1793                                         err: format!("Channel with SCID {} or one of its nodes was removed from our network graph recently", &msg.short_channel_id),
1794                                         action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1795                         }
1796                 }
1797
1798                 let utxo_value = self.pending_checks.check_channel_announcement(
1799                         utxo_lookup, msg, full_msg)?;
1800
1801                 #[allow(unused_mut, unused_assignments)]
1802                 let mut announcement_received_time = 0;
1803                 #[cfg(feature = "std")]
1804                 {
1805                         announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1806                 }
1807
1808                 let chan_info = ChannelInfo {
1809                         features: msg.features.clone(),
1810                         node_one: msg.node_id_1,
1811                         one_to_two: None,
1812                         node_two: msg.node_id_2,
1813                         two_to_one: None,
1814                         capacity_sats: utxo_value,
1815                         announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1816                                 { full_msg.cloned() } else { None },
1817                         announcement_received_time,
1818                         node_one_counter: u32::max_value(),
1819                         node_two_counter: u32::max_value(),
1820                 };
1821
1822                 self.add_channel_between_nodes(msg.short_channel_id, chan_info, utxo_value)?;
1823
1824                 log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.short_channel_id, if !msg.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
1825                 Ok(())
1826         }
1827
1828         /// Marks a channel in the graph as failed permanently.
1829         ///
1830         /// The channel and any node for which this was their last channel are removed from the graph.
1831         pub fn channel_failed_permanent(&self, short_channel_id: u64) {
1832                 #[cfg(feature = "std")]
1833                 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1834                 #[cfg(not(feature = "std"))]
1835                 let current_time_unix = None;
1836
1837                 self.channel_failed_permanent_with_time(short_channel_id, current_time_unix)
1838         }
1839
1840         /// Marks a channel in the graph as failed permanently.
1841         ///
1842         /// The channel and any node for which this was their last channel are removed from the graph.
1843         fn channel_failed_permanent_with_time(&self, short_channel_id: u64, current_time_unix: Option<u64>) {
1844                 let mut channels = self.channels.write().unwrap();
1845                 if let Some(chan) = channels.remove(&short_channel_id) {
1846                         let mut nodes = self.nodes.write().unwrap();
1847                         self.removed_channels.lock().unwrap().insert(short_channel_id, current_time_unix);
1848                         self.remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1849                 }
1850         }
1851
1852         /// Marks a node in the graph as permanently failed, effectively removing it and its channels
1853         /// from local storage.
1854         pub fn node_failed_permanent(&self, node_id: &PublicKey) {
1855                 #[cfg(feature = "std")]
1856                 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1857                 #[cfg(not(feature = "std"))]
1858                 let current_time_unix = None;
1859
1860                 let node_id = NodeId::from_pubkey(node_id);
1861                 let mut channels = self.channels.write().unwrap();
1862                 let mut nodes = self.nodes.write().unwrap();
1863                 let mut removed_channels = self.removed_channels.lock().unwrap();
1864                 let mut removed_nodes = self.removed_nodes.lock().unwrap();
1865
1866                 if let Some(node) = nodes.remove(&node_id) {
1867                         let mut removed_node_counters = self.removed_node_counters.lock().unwrap();
1868                         for scid in node.channels.iter() {
1869                                 if let Some(chan_info) = channels.remove(scid) {
1870                                         let other_node_id = if node_id == chan_info.node_one { chan_info.node_two } else { chan_info.node_one };
1871                                         if let IndexedMapEntry::Occupied(mut other_node_entry) = nodes.entry(other_node_id) {
1872                                                 other_node_entry.get_mut().channels.retain(|chan_id| {
1873                                                         *scid != *chan_id
1874                                                 });
1875                                                 if other_node_entry.get().channels.is_empty() {
1876                                                         removed_node_counters.push(other_node_entry.get().node_counter);
1877                                                         other_node_entry.remove_entry();
1878                                                 }
1879                                         }
1880                                         removed_channels.insert(*scid, current_time_unix);
1881                                 }
1882                         }
1883                         removed_node_counters.push(node.node_counter);
1884                         removed_nodes.insert(node_id, current_time_unix);
1885                 }
1886         }
1887
1888         #[cfg(feature = "std")]
1889         /// Removes information about channels that we haven't heard any updates about in some time.
1890         /// This can be used regularly to prune the network graph of channels that likely no longer
1891         /// exist.
1892         ///
1893         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1894         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1895         /// pruning occur for updates which are at least two weeks old, which we implement here.
1896         ///
1897         /// Note that for users of the `lightning-background-processor` crate this method may be
1898         /// automatically called regularly for you.
1899         ///
1900         /// This method will also cause us to stop tracking removed nodes and channels if they have been
1901         /// in the map for a while so that these can be resynced from gossip in the future.
1902         ///
1903         /// This method is only available with the `std` feature. See
1904         /// [`NetworkGraph::remove_stale_channels_and_tracking_with_time`] for `no-std` use.
1905         pub fn remove_stale_channels_and_tracking(&self) {
1906                 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1907                 self.remove_stale_channels_and_tracking_with_time(time);
1908         }
1909
1910         /// Removes information about channels that we haven't heard any updates about in some time.
1911         /// This can be used regularly to prune the network graph of channels that likely no longer
1912         /// exist.
1913         ///
1914         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1915         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1916         /// pruning occur for updates which are at least two weeks old, which we implement here.
1917         ///
1918         /// This method will also cause us to stop tracking removed nodes and channels if they have been
1919         /// in the map for a while so that these can be resynced from gossip in the future.
1920         ///
1921         /// This function takes the current unix time as an argument. For users with the `std` feature
1922         /// enabled, [`NetworkGraph::remove_stale_channels_and_tracking`] may be preferable.
1923         pub fn remove_stale_channels_and_tracking_with_time(&self, current_time_unix: u64) {
1924                 let mut channels = self.channels.write().unwrap();
1925                 // Time out if we haven't received an update in at least 14 days.
1926                 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1927                 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1928                 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1929                 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1930                 // time.
1931                 let mut scids_to_remove = Vec::new();
1932                 for (scid, info) in channels.unordered_iter_mut() {
1933                         if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1934                                 log_gossip!(self.logger, "Removing directional update one_to_two (0) for channel {} due to its timestamp {} being below {}",
1935                                         scid, info.one_to_two.as_ref().unwrap().last_update, min_time_unix);
1936                                 info.one_to_two = None;
1937                         }
1938                         if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1939                                 log_gossip!(self.logger, "Removing directional update two_to_one (1) for channel {} due to its timestamp {} being below {}",
1940                                         scid, info.two_to_one.as_ref().unwrap().last_update, min_time_unix);
1941                                 info.two_to_one = None;
1942                         }
1943                         if info.one_to_two.is_none() || info.two_to_one.is_none() {
1944                                 // We check the announcement_received_time here to ensure we don't drop
1945                                 // announcements that we just received and are just waiting for our peer to send a
1946                                 // channel_update for.
1947                                 let announcement_received_timestamp = info.announcement_received_time;
1948                                 if announcement_received_timestamp < min_time_unix as u64 {
1949                                         log_gossip!(self.logger, "Removing channel {} because both directional updates are missing and its announcement timestamp {} being below {}",
1950                                                 scid, announcement_received_timestamp, min_time_unix);
1951                                         scids_to_remove.push(*scid);
1952                                 }
1953                         }
1954                 }
1955                 if !scids_to_remove.is_empty() {
1956                         let mut nodes = self.nodes.write().unwrap();
1957                         for scid in scids_to_remove {
1958                                 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1959                                 self.remove_channel_in_nodes(&mut nodes, &info, scid);
1960                                 self.removed_channels.lock().unwrap().insert(scid, Some(current_time_unix));
1961                         }
1962                 }
1963
1964                 let should_keep_tracking = |time: &mut Option<u64>| {
1965                         if let Some(time) = time {
1966                                 current_time_unix.saturating_sub(*time) < REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS
1967                         } else {
1968                                 // NOTE: In the case of no-std, we won't have access to the current UNIX time at the time of removal,
1969                                 // so we'll just set the removal time here to the current UNIX time on the very next invocation
1970                                 // of this function.
1971                                 #[cfg(not(feature = "std"))]
1972                                 {
1973                                         let mut tracked_time = Some(current_time_unix);
1974                                         core::mem::swap(time, &mut tracked_time);
1975                                         return true;
1976                                 }
1977                                 #[allow(unreachable_code)]
1978                                 false
1979                         }};
1980
1981                 self.removed_channels.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1982                 self.removed_nodes.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1983         }
1984
1985         /// For an already known (from announcement) channel, update info about one of the directions
1986         /// of the channel.
1987         ///
1988         /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1989         /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1990         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1991         ///
1992         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1993         /// materially in the future will be rejected.
1994         pub fn update_channel(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
1995                 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), false)
1996         }
1997
1998         /// For an already known (from announcement) channel, update info about one of the directions
1999         /// of the channel without verifying the associated signatures. Because we aren't given the
2000         /// associated signatures here we cannot relay the channel update to any of our peers.
2001         ///
2002         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
2003         /// materially in the future will be rejected.
2004         pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
2005                 self.update_channel_internal(msg, None, None, false)
2006         }
2007
2008         /// For an already known (from announcement) channel, verify the given [`ChannelUpdate`].
2009         ///
2010         /// This checks whether the update currently is applicable by [`Self::update_channel`].
2011         ///
2012         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
2013         /// materially in the future will be rejected.
2014         pub fn verify_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
2015                 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), true)
2016         }
2017
2018         fn update_channel_internal(&self, msg: &msgs::UnsignedChannelUpdate,
2019                 full_msg: Option<&msgs::ChannelUpdate>, sig: Option<&secp256k1::ecdsa::Signature>,
2020                 only_verify: bool) -> Result<(), LightningError>
2021         {
2022                 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
2023
2024                 if msg.chain_hash != self.chain_hash {
2025                         return Err(LightningError {
2026                                 err: "Channel update chain hash does not match genesis hash".to_owned(),
2027                                 action: ErrorAction::IgnoreAndLog(Level::Debug),
2028                         });
2029                 }
2030
2031                 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
2032                 {
2033                         // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
2034                         // disable this check during tests!
2035                         let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2036                         if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
2037                                 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
2038                         }
2039                         if msg.timestamp as u64 > time + 60 * 60 * 24 {
2040                                 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
2041                         }
2042                 }
2043
2044                 log_gossip!(self.logger, "Updating channel {} in direction {} with timestamp {}", msg.short_channel_id, msg.flags & 1, msg.timestamp);
2045
2046                 let mut channels = self.channels.write().unwrap();
2047                 match channels.get_mut(&msg.short_channel_id) {
2048                         None => {
2049                                 core::mem::drop(channels);
2050                                 self.pending_checks.check_hold_pending_channel_update(msg, full_msg)?;
2051                                 return Err(LightningError {
2052                                         err: "Couldn't find channel for update".to_owned(),
2053                                         action: ErrorAction::IgnoreAndLog(Level::Gossip),
2054                                 });
2055                         },
2056                         Some(channel) => {
2057                                 if msg.htlc_maximum_msat > MAX_VALUE_MSAT {
2058                                         return Err(LightningError{err:
2059                                                 "htlc_maximum_msat is larger than maximum possible msats".to_owned(),
2060                                                 action: ErrorAction::IgnoreError});
2061                                 }
2062
2063                                 if let Some(capacity_sats) = channel.capacity_sats {
2064                                         // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
2065                                         // Don't query UTXO set here to reduce DoS risks.
2066                                         if capacity_sats > MAX_VALUE_MSAT / 1000 || msg.htlc_maximum_msat > capacity_sats * 1000 {
2067                                                 return Err(LightningError{err:
2068                                                         "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(),
2069                                                         action: ErrorAction::IgnoreError});
2070                                         }
2071                                 }
2072                                 macro_rules! check_update_latest {
2073                                         ($target: expr) => {
2074                                                 if let Some(existing_chan_info) = $target.as_ref() {
2075                                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to
2076                                                         // order updates to ensure you always have the latest one, only
2077                                                         // suggesting  that it be at least the current time. For
2078                                                         // channel_updates specifically, the BOLTs discuss the possibility of
2079                                                         // pruning based on the timestamp field being more than two weeks old,
2080                                                         // but only in the non-normative section.
2081                                                         if existing_chan_info.last_update > msg.timestamp {
2082                                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2083                                                         } else if existing_chan_info.last_update == msg.timestamp {
2084                                                                 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2085                                                         }
2086                                                 }
2087                                         }
2088                                 }
2089
2090                                 macro_rules! get_new_channel_info {
2091                                         () => { {
2092                                                 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
2093                                                         { full_msg.cloned() } else { None };
2094
2095                                                 let updated_channel_update_info = ChannelUpdateInfo {
2096                                                         enabled: chan_enabled,
2097                                                         last_update: msg.timestamp,
2098                                                         cltv_expiry_delta: msg.cltv_expiry_delta,
2099                                                         htlc_minimum_msat: msg.htlc_minimum_msat,
2100                                                         htlc_maximum_msat: msg.htlc_maximum_msat,
2101                                                         fees: RoutingFees {
2102                                                                 base_msat: msg.fee_base_msat,
2103                                                                 proportional_millionths: msg.fee_proportional_millionths,
2104                                                         },
2105                                                         last_update_message
2106                                                 };
2107                                                 Some(updated_channel_update_info)
2108                                         } }
2109                                 }
2110
2111                                 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg)[..]);
2112                                 if msg.flags & 1 == 1 {
2113                                         check_update_latest!(channel.two_to_one);
2114                                         if let Some(sig) = sig {
2115                                                 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
2116                                                         err: "Couldn't parse source node pubkey".to_owned(),
2117                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
2118                                                 })?, "channel_update");
2119                                         }
2120                                         if !only_verify {
2121                                                 channel.two_to_one = get_new_channel_info!();
2122                                         }
2123                                 } else {
2124                                         check_update_latest!(channel.one_to_two);
2125                                         if let Some(sig) = sig {
2126                                                 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
2127                                                         err: "Couldn't parse destination node pubkey".to_owned(),
2128                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
2129                                                 })?, "channel_update");
2130                                         }
2131                                         if !only_verify {
2132                                                 channel.one_to_two = get_new_channel_info!();
2133                                         }
2134                                 }
2135                         }
2136                 }
2137
2138                 Ok(())
2139         }
2140
2141         fn remove_channel_in_nodes(&self, nodes: &mut IndexedMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
2142                 macro_rules! remove_from_node {
2143                         ($node_id: expr) => {
2144                                 if let IndexedMapEntry::Occupied(mut entry) = nodes.entry($node_id) {
2145                                         entry.get_mut().channels.retain(|chan_id| {
2146                                                 short_channel_id != *chan_id
2147                                         });
2148                                         if entry.get().channels.is_empty() {
2149                                                 self.removed_node_counters.lock().unwrap().push(entry.get().node_counter);
2150                                                 entry.remove_entry();
2151                                         }
2152                                 } else {
2153                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
2154                                 }
2155                         }
2156                 }
2157
2158                 remove_from_node!(chan.node_one);
2159                 remove_from_node!(chan.node_two);
2160         }
2161 }
2162
2163 impl ReadOnlyNetworkGraph<'_> {
2164         /// Returns all known valid channels' short ids along with announced channel info.
2165         ///
2166         /// This is not exported to bindings users because we don't want to return lifetime'd references
2167         pub fn channels(&self) -> &IndexedMap<u64, ChannelInfo> {
2168                 &*self.channels
2169         }
2170
2171         /// Returns information on a channel with the given id.
2172         pub fn channel(&self, short_channel_id: u64) -> Option<&ChannelInfo> {
2173                 self.channels.get(&short_channel_id)
2174         }
2175
2176         #[cfg(c_bindings)] // Non-bindings users should use `channels`
2177         /// Returns the list of channels in the graph
2178         pub fn list_channels(&self) -> Vec<u64> {
2179                 self.channels.unordered_keys().map(|c| *c).collect()
2180         }
2181
2182         /// Returns all known nodes' public keys along with announced node info.
2183         ///
2184         /// This is not exported to bindings users because we don't want to return lifetime'd references
2185         pub fn nodes(&self) -> &IndexedMap<NodeId, NodeInfo> {
2186                 &*self.nodes
2187         }
2188
2189         /// Returns information on a node with the given id.
2190         pub fn node(&self, node_id: &NodeId) -> Option<&NodeInfo> {
2191                 self.nodes.get(node_id)
2192         }
2193
2194         #[cfg(c_bindings)] // Non-bindings users should use `nodes`
2195         /// Returns the list of nodes in the graph
2196         pub fn list_nodes(&self) -> Vec<NodeId> {
2197                 self.nodes.unordered_keys().map(|n| *n).collect()
2198         }
2199
2200         /// Get network addresses by node id.
2201         /// Returns None if the requested node is completely unknown,
2202         /// or if node announcement for the node was never received.
2203         pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<SocketAddress>> {
2204                 self.nodes.get(&NodeId::from_pubkey(&pubkey))
2205                         .and_then(|node| node.announcement_info.as_ref().map(|ann| ann.addresses().to_vec()))
2206         }
2207
2208         /// Gets the maximum possible node_counter for a node in this graph
2209         pub(crate) fn max_node_counter(&self) -> u32 {
2210                 self.max_node_counter
2211         }
2212 }
2213
2214 #[cfg(test)]
2215 pub(crate) mod tests {
2216         use crate::events::{MessageSendEvent, MessageSendEventsProvider};
2217         use crate::ln::channelmanager;
2218         use crate::ln::chan_utils::make_funding_redeemscript;
2219         #[cfg(feature = "std")]
2220         use crate::ln::features::InitFeatures;
2221         use crate::ln::msgs::SocketAddress;
2222         use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, NodeAlias, MAX_EXCESS_BYTES_FOR_RELAY, NodeId, RoutingFees, ChannelUpdateInfo, ChannelInfo, NodeAnnouncementInfo, NodeInfo};
2223         use crate::routing::utxo::{UtxoLookupError, UtxoResult};
2224         use crate::ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
2225                 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
2226                 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
2227         use crate::util::config::UserConfig;
2228         use crate::util::test_utils;
2229         use crate::util::ser::{Hostname, ReadableArgs, Readable, Writeable};
2230         use crate::util::scid_utils::scid_from_parts;
2231
2232         use crate::routing::gossip::REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS;
2233         use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
2234
2235         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
2236         use bitcoin::hashes::Hash;
2237         use bitcoin::hashes::hex::FromHex;
2238         use bitcoin::network::constants::Network;
2239         use bitcoin::blockdata::constants::ChainHash;
2240         use bitcoin::blockdata::script::ScriptBuf;
2241         use bitcoin::blockdata::transaction::TxOut;
2242         use bitcoin::secp256k1::{PublicKey, SecretKey};
2243         use bitcoin::secp256k1::{All, Secp256k1};
2244
2245         use crate::io;
2246         use bitcoin::secp256k1;
2247         use crate::prelude::*;
2248         use crate::sync::Arc;
2249
2250         fn create_network_graph() -> NetworkGraph<Arc<test_utils::TestLogger>> {
2251                 let logger = Arc::new(test_utils::TestLogger::new());
2252                 NetworkGraph::new(Network::Testnet, logger)
2253         }
2254
2255         fn create_gossip_sync(network_graph: &NetworkGraph<Arc<test_utils::TestLogger>>) -> (
2256                 Secp256k1<All>, P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>,
2257                 Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
2258         ) {
2259                 let secp_ctx = Secp256k1::new();
2260                 let logger = Arc::new(test_utils::TestLogger::new());
2261                 let gossip_sync = P2PGossipSync::new(network_graph, None, Arc::clone(&logger));
2262                 (secp_ctx, gossip_sync)
2263         }
2264
2265         #[test]
2266         #[cfg(feature = "std")]
2267         fn request_full_sync_finite_times() {
2268                 let network_graph = create_network_graph();
2269                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2270                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
2271
2272                 assert!(gossip_sync.should_request_full_sync(&node_id));
2273                 assert!(gossip_sync.should_request_full_sync(&node_id));
2274                 assert!(gossip_sync.should_request_full_sync(&node_id));
2275                 assert!(gossip_sync.should_request_full_sync(&node_id));
2276                 assert!(gossip_sync.should_request_full_sync(&node_id));
2277                 assert!(!gossip_sync.should_request_full_sync(&node_id));
2278         }
2279
2280         pub(crate) fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
2281                 let node_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_key));
2282                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2283                         features: channelmanager::provided_node_features(&UserConfig::default()),
2284                         timestamp: 100,
2285                         node_id,
2286                         rgb: [0; 3],
2287                         alias: NodeAlias([0; 32]),
2288                         addresses: Vec::new(),
2289                         excess_address_data: Vec::new(),
2290                         excess_data: Vec::new(),
2291                 };
2292                 f(&mut unsigned_announcement);
2293                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2294                 NodeAnnouncement {
2295                         signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2296                         contents: unsigned_announcement
2297                 }
2298         }
2299
2300         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 {
2301                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
2302                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
2303                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2304                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2305
2306                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
2307                         features: channelmanager::provided_channel_features(&UserConfig::default()),
2308                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2309                         short_channel_id: 0,
2310                         node_id_1: NodeId::from_pubkey(&node_id_1),
2311                         node_id_2: NodeId::from_pubkey(&node_id_2),
2312                         bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey)),
2313                         bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey)),
2314                         excess_data: Vec::new(),
2315                 };
2316                 f(&mut unsigned_announcement);
2317                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2318                 ChannelAnnouncement {
2319                         node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_key),
2320                         node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_key),
2321                         bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_btckey),
2322                         bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_btckey),
2323                         contents: unsigned_announcement,
2324                 }
2325         }
2326
2327         pub(crate) fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> ScriptBuf {
2328                 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
2329                 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
2330                 make_funding_redeemscript(&PublicKey::from_secret_key(secp_ctx, &node_1_btckey),
2331                         &PublicKey::from_secret_key(secp_ctx, &node_2_btckey)).to_v0_p2wsh()
2332         }
2333
2334         pub(crate) fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
2335                 let mut unsigned_channel_update = UnsignedChannelUpdate {
2336                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2337                         short_channel_id: 0,
2338                         timestamp: 100,
2339                         flags: 0,
2340                         cltv_expiry_delta: 144,
2341                         htlc_minimum_msat: 1_000_000,
2342                         htlc_maximum_msat: 1_000_000,
2343                         fee_base_msat: 10_000,
2344                         fee_proportional_millionths: 20,
2345                         excess_data: Vec::new()
2346                 };
2347                 f(&mut unsigned_channel_update);
2348                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2349                 ChannelUpdate {
2350                         signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2351                         contents: unsigned_channel_update
2352                 }
2353         }
2354
2355         #[test]
2356         fn handling_node_announcements() {
2357                 let network_graph = create_network_graph();
2358                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2359
2360                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2361                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2362                 let zero_hash = Sha256dHash::hash(&[0; 32]);
2363
2364                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2365                 match gossip_sync.handle_node_announcement(&valid_announcement) {
2366                         Ok(_) => panic!(),
2367                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
2368                 };
2369
2370                 {
2371                         // Announce a channel to add a corresponding node.
2372                         let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2373                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
2374                                 Ok(res) => assert!(res),
2375                                 _ => panic!()
2376                         };
2377                 }
2378
2379                 match gossip_sync.handle_node_announcement(&valid_announcement) {
2380                         Ok(res) => assert!(res),
2381                         Err(_) => panic!()
2382                 };
2383
2384                 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2385                 match gossip_sync.handle_node_announcement(
2386                         &NodeAnnouncement {
2387                                 signature: secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey),
2388                                 contents: valid_announcement.contents.clone()
2389                 }) {
2390                         Ok(_) => panic!(),
2391                         Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
2392                 };
2393
2394                 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
2395                         unsigned_announcement.timestamp += 1000;
2396                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2397                 }, node_1_privkey, &secp_ctx);
2398                 // Return false because contains excess data.
2399                 match gossip_sync.handle_node_announcement(&announcement_with_data) {
2400                         Ok(res) => assert!(!res),
2401                         Err(_) => panic!()
2402                 };
2403
2404                 // Even though previous announcement was not relayed further, we still accepted it,
2405                 // so we now won't accept announcements before the previous one.
2406                 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
2407                         unsigned_announcement.timestamp += 1000 - 10;
2408                 }, node_1_privkey, &secp_ctx);
2409                 match gossip_sync.handle_node_announcement(&outdated_announcement) {
2410                         Ok(_) => panic!(),
2411                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
2412                 };
2413         }
2414
2415         #[test]
2416         fn handling_channel_announcements() {
2417                 let secp_ctx = Secp256k1::new();
2418                 let logger = test_utils::TestLogger::new();
2419
2420                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2421                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2422
2423                 let good_script = get_channel_script(&secp_ctx);
2424                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2425
2426                 // Test if the UTXO lookups were not supported
2427                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2428                 let mut gossip_sync = P2PGossipSync::new(&network_graph, None, &logger);
2429                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2430                         Ok(res) => assert!(res),
2431                         _ => panic!()
2432                 };
2433
2434                 {
2435                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2436                                 None => panic!(),
2437                                 Some(_) => ()
2438                         };
2439                 }
2440
2441                 // If we receive announcement for the same channel (with UTXO lookups disabled),
2442                 // drop new one on the floor, since we can't see any changes.
2443                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2444                         Ok(_) => panic!(),
2445                         Err(e) => assert_eq!(e.err, "Already have non-chain-validated channel")
2446                 };
2447
2448                 // Test if an associated transaction were not on-chain (or not confirmed).
2449                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2450                 *chain_source.utxo_ret.lock().unwrap() = UtxoResult::Sync(Err(UtxoLookupError::UnknownTx));
2451                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2452                 gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2453
2454                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2455                         unsigned_announcement.short_channel_id += 1;
2456                 }, node_1_privkey, node_2_privkey, &secp_ctx);
2457                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2458                         Ok(_) => panic!(),
2459                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2460                 };
2461
2462                 // Now test if the transaction is found in the UTXO set and the script is correct.
2463                 *chain_source.utxo_ret.lock().unwrap() =
2464                         UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script.clone() }));
2465                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2466                         unsigned_announcement.short_channel_id += 2;
2467                 }, node_1_privkey, node_2_privkey, &secp_ctx);
2468                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2469                         Ok(res) => assert!(res),
2470                         _ => panic!()
2471                 };
2472
2473                 {
2474                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2475                                 None => panic!(),
2476                                 Some(_) => ()
2477                         };
2478                 }
2479
2480                 // If we receive announcement for the same channel, once we've validated it against the
2481                 // chain, we simply ignore all new (duplicate) announcements.
2482                 *chain_source.utxo_ret.lock().unwrap() =
2483                         UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script }));
2484                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2485                         Ok(_) => panic!(),
2486                         Err(e) => assert_eq!(e.err, "Already have chain-validated channel")
2487                 };
2488
2489                 #[cfg(feature = "std")]
2490                 {
2491                         use std::time::{SystemTime, UNIX_EPOCH};
2492
2493                         let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2494                         // Mark a node as permanently failed so it's tracked as removed.
2495                         gossip_sync.network_graph().node_failed_permanent(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2496
2497                         // Return error and ignore valid channel announcement if one of the nodes has been tracked as removed.
2498                         let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2499                                 unsigned_announcement.short_channel_id += 3;
2500                         }, node_1_privkey, node_2_privkey, &secp_ctx);
2501                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
2502                                 Ok(_) => panic!(),
2503                                 Err(e) => assert_eq!(e.err, "Channel with SCID 3 or one of its nodes was removed from our network graph recently")
2504                         }
2505
2506                         gossip_sync.network_graph().remove_stale_channels_and_tracking_with_time(tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2507
2508                         // The above channel announcement should be handled as per normal now.
2509                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
2510                                 Ok(res) => assert!(res),
2511                                 _ => panic!()
2512                         }
2513                 }
2514
2515                 // Don't relay valid channels with excess data
2516                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2517                         unsigned_announcement.short_channel_id += 4;
2518                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2519                 }, node_1_privkey, node_2_privkey, &secp_ctx);
2520                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2521                         Ok(res) => assert!(!res),
2522                         _ => panic!()
2523                 };
2524
2525                 let mut invalid_sig_announcement = valid_announcement.clone();
2526                 invalid_sig_announcement.contents.excess_data = Vec::new();
2527                 match gossip_sync.handle_channel_announcement(&invalid_sig_announcement) {
2528                         Ok(_) => panic!(),
2529                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
2530                 };
2531
2532                 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
2533                 match gossip_sync.handle_channel_announcement(&channel_to_itself_announcement) {
2534                         Ok(_) => panic!(),
2535                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2536                 };
2537
2538                 // Test that channel announcements with the wrong chain hash are ignored (network graph is testnet,
2539                 // announcement is mainnet).
2540                 let incorrect_chain_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2541                         unsigned_announcement.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2542                 }, node_1_privkey, node_2_privkey, &secp_ctx);
2543                 match gossip_sync.handle_channel_announcement(&incorrect_chain_announcement) {
2544                         Ok(_) => panic!(),
2545                         Err(e) => assert_eq!(e.err, "Channel announcement chain hash does not match genesis hash")
2546                 };
2547         }
2548
2549         #[test]
2550         fn handling_channel_update() {
2551                 let secp_ctx = Secp256k1::new();
2552                 let logger = test_utils::TestLogger::new();
2553                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2554                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2555                 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2556
2557                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2558                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2559
2560                 let amount_sats = 1000_000;
2561                 let short_channel_id;
2562
2563                 {
2564                         // Announce a channel we will update
2565                         let good_script = get_channel_script(&secp_ctx);
2566                         *chain_source.utxo_ret.lock().unwrap() =
2567                                 UtxoResult::Sync(Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() }));
2568
2569                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2570                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2571                         match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2572                                 Ok(_) => (),
2573                                 Err(_) => panic!()
2574                         };
2575
2576                 }
2577
2578                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2579                 network_graph.verify_channel_update(&valid_channel_update).unwrap();
2580                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2581                         Ok(res) => assert!(res),
2582                         _ => panic!(),
2583                 };
2584
2585                 {
2586                         match network_graph.read_only().channels().get(&short_channel_id) {
2587                                 None => panic!(),
2588                                 Some(channel_info) => {
2589                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
2590                                         assert!(channel_info.two_to_one.is_none());
2591                                 }
2592                         };
2593                 }
2594
2595                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2596                         unsigned_channel_update.timestamp += 100;
2597                         unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2598                 }, node_1_privkey, &secp_ctx);
2599                 // Return false because contains excess data
2600                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2601                         Ok(res) => assert!(!res),
2602                         _ => panic!()
2603                 };
2604
2605                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2606                         unsigned_channel_update.timestamp += 110;
2607                         unsigned_channel_update.short_channel_id += 1;
2608                 }, node_1_privkey, &secp_ctx);
2609                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2610                         Ok(_) => panic!(),
2611                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2612                 };
2613
2614                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2615                         unsigned_channel_update.htlc_maximum_msat = MAX_VALUE_MSAT + 1;
2616                         unsigned_channel_update.timestamp += 110;
2617                 }, node_1_privkey, &secp_ctx);
2618                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2619                         Ok(_) => panic!(),
2620                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
2621                 };
2622
2623                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2624                         unsigned_channel_update.htlc_maximum_msat = amount_sats * 1000 + 1;
2625                         unsigned_channel_update.timestamp += 110;
2626                 }, node_1_privkey, &secp_ctx);
2627                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2628                         Ok(_) => panic!(),
2629                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
2630                 };
2631
2632                 // Even though previous update was not relayed further, we still accepted it,
2633                 // so we now won't accept update before the previous one.
2634                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2635                         unsigned_channel_update.timestamp += 100;
2636                 }, node_1_privkey, &secp_ctx);
2637                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2638                         Ok(_) => panic!(),
2639                         Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
2640                 };
2641
2642                 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2643                         unsigned_channel_update.timestamp += 500;
2644                 }, node_1_privkey, &secp_ctx);
2645                 let zero_hash = Sha256dHash::hash(&[0; 32]);
2646                 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2647                 invalid_sig_channel_update.signature = secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey);
2648                 match gossip_sync.handle_channel_update(&invalid_sig_channel_update) {
2649                         Ok(_) => panic!(),
2650                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
2651                 };
2652
2653                 // Test that channel updates with the wrong chain hash are ignored (network graph is testnet, channel
2654                 // update is mainet).
2655                 let incorrect_chain_update = get_signed_channel_update(|unsigned_channel_update| {
2656                         unsigned_channel_update.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2657                 }, node_1_privkey, &secp_ctx);
2658
2659                 match gossip_sync.handle_channel_update(&incorrect_chain_update) {
2660                         Ok(_) => panic!(),
2661                         Err(e) => assert_eq!(e.err, "Channel update chain hash does not match genesis hash")
2662                 };
2663         }
2664
2665         #[test]
2666         fn handling_network_update() {
2667                 let logger = test_utils::TestLogger::new();
2668                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2669                 let secp_ctx = Secp256k1::new();
2670
2671                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2672                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2673                 let node_2_id = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2674
2675                 {
2676                         // There is no nodes in the table at the beginning.
2677                         assert_eq!(network_graph.read_only().nodes().len(), 0);
2678                 }
2679
2680                 let short_channel_id;
2681                 {
2682                         // Check we won't apply an update via `handle_network_update` for privacy reasons, but
2683                         // can continue fine if we manually apply it.
2684                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2685                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2686                         let chain_source: Option<&test_utils::TestChainSource> = None;
2687                         assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2688                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2689
2690                         let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2691                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2692
2693                         network_graph.handle_network_update(&NetworkUpdate::ChannelUpdateMessage {
2694                                 msg: valid_channel_update.clone(),
2695                         });
2696
2697                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2698                         network_graph.update_channel(&valid_channel_update).unwrap();
2699                 }
2700
2701                 // Non-permanent failure doesn't touch the channel at all
2702                 {
2703                         match network_graph.read_only().channels().get(&short_channel_id) {
2704                                 None => panic!(),
2705                                 Some(channel_info) => {
2706                                         assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2707                                 }
2708                         };
2709
2710                         network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2711                                 short_channel_id,
2712                                 is_permanent: false,
2713                         });
2714
2715                         match network_graph.read_only().channels().get(&short_channel_id) {
2716                                 None => panic!(),
2717                                 Some(channel_info) => {
2718                                         assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2719                                 }
2720                         };
2721                 }
2722
2723                 // Permanent closing deletes a channel
2724                 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2725                         short_channel_id,
2726                         is_permanent: true,
2727                 });
2728
2729                 assert_eq!(network_graph.read_only().channels().len(), 0);
2730                 // Nodes are also deleted because there are no associated channels anymore
2731                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2732
2733                 {
2734                         // Get a new network graph since we don't want to track removed nodes in this test with "std"
2735                         let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2736
2737                         // Announce a channel to test permanent node failure
2738                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2739                         let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2740                         let chain_source: Option<&test_utils::TestChainSource> = None;
2741                         assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2742                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2743
2744                         // Non-permanent node failure does not delete any nodes or channels
2745                         network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2746                                 node_id: node_2_id,
2747                                 is_permanent: false,
2748                         });
2749
2750                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2751                         assert!(network_graph.read_only().nodes().get(&NodeId::from_pubkey(&node_2_id)).is_some());
2752
2753                         // Permanent node failure deletes node and its channels
2754                         network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2755                                 node_id: node_2_id,
2756                                 is_permanent: true,
2757                         });
2758
2759                         assert_eq!(network_graph.read_only().nodes().len(), 0);
2760                         // Channels are also deleted because the associated node has been deleted
2761                         assert_eq!(network_graph.read_only().channels().len(), 0);
2762                 }
2763         }
2764
2765         #[test]
2766         fn test_channel_timeouts() {
2767                 // Test the removal of channels with `remove_stale_channels_and_tracking`.
2768                 let logger = test_utils::TestLogger::new();
2769                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2770                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2771                 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2772                 let secp_ctx = Secp256k1::new();
2773
2774                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2775                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2776
2777                 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2778                 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2779                 let chain_source: Option<&test_utils::TestChainSource> = None;
2780                 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2781                 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2782
2783                 // Submit two channel updates for each channel direction (update.flags bit).
2784                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2785                 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2786                 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2787
2788                 let valid_channel_update_2 = get_signed_channel_update(|update| {update.flags |=1;}, node_2_privkey, &secp_ctx);
2789                 gossip_sync.handle_channel_update(&valid_channel_update_2).unwrap();
2790                 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().two_to_one.is_some());
2791
2792                 network_graph.remove_stale_channels_and_tracking_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2793                 assert_eq!(network_graph.read_only().channels().len(), 1);
2794                 assert_eq!(network_graph.read_only().nodes().len(), 2);
2795
2796                 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2797                 #[cfg(not(feature = "std"))] {
2798                         // Make sure removed channels are tracked.
2799                         assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2800                 }
2801                 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2802                         REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2803
2804                 #[cfg(feature = "std")]
2805                 {
2806                         // In std mode, a further check is performed before fully removing the channel -
2807                         // the channel_announcement must have been received at least two weeks ago. We
2808                         // fudge that here by indicating the time has jumped two weeks.
2809                         assert_eq!(network_graph.read_only().channels().len(), 1);
2810                         assert_eq!(network_graph.read_only().nodes().len(), 2);
2811
2812                         // Note that the directional channel information will have been removed already..
2813                         // We want to check that this will work even if *one* of the channel updates is recent,
2814                         // so we should add it with a recent timestamp.
2815                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2816                         use std::time::{SystemTime, UNIX_EPOCH};
2817                         let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2818                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2819                                 unsigned_channel_update.timestamp = (announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
2820                         }, node_1_privkey, &secp_ctx);
2821                         assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2822                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2823                         network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2824                         // Make sure removed channels are tracked.
2825                         assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2826                         // Provide a later time so that sufficient time has passed
2827                         network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2828                                 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2829                 }
2830
2831                 assert_eq!(network_graph.read_only().channels().len(), 0);
2832                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2833                 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2834
2835                 #[cfg(feature = "std")]
2836                 {
2837                         use std::time::{SystemTime, UNIX_EPOCH};
2838
2839                         let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2840
2841                         // Clear tracked nodes and channels for clean slate
2842                         network_graph.removed_channels.lock().unwrap().clear();
2843                         network_graph.removed_nodes.lock().unwrap().clear();
2844
2845                         // Add a channel and nodes from channel announcement. So our network graph will
2846                         // now only consist of two nodes and one channel between them.
2847                         assert!(network_graph.update_channel_from_announcement(
2848                                 &valid_channel_announcement, &chain_source).is_ok());
2849
2850                         // Mark the channel as permanently failed. This will also remove the two nodes
2851                         // and all of the entries will be tracked as removed.
2852                         network_graph.channel_failed_permanent_with_time(short_channel_id, Some(tracking_time));
2853
2854                         // Should not remove from tracking if insufficient time has passed
2855                         network_graph.remove_stale_channels_and_tracking_with_time(
2856                                 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS - 1);
2857                         assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1, "Removed channel count â‰  1 with tracking_time {}", tracking_time);
2858
2859                         // Provide a later time so that sufficient time has passed
2860                         network_graph.remove_stale_channels_and_tracking_with_time(
2861                                 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2862                         assert!(network_graph.removed_channels.lock().unwrap().is_empty(), "Unexpectedly removed channels with tracking_time {}", tracking_time);
2863                         assert!(network_graph.removed_nodes.lock().unwrap().is_empty(), "Unexpectedly removed nodes with tracking_time {}", tracking_time);
2864                 }
2865
2866                 #[cfg(not(feature = "std"))]
2867                 {
2868                         // When we don't have access to the system clock, the time we started tracking removal will only
2869                         // be that provided by the first call to `remove_stale_channels_and_tracking_with_time`. Hence,
2870                         // only if sufficient time has passed after that first call, will the next call remove it from
2871                         // tracking.
2872                         let removal_time = 1664619654;
2873
2874                         // Clear removed nodes and channels for clean slate
2875                         network_graph.removed_channels.lock().unwrap().clear();
2876                         network_graph.removed_nodes.lock().unwrap().clear();
2877
2878                         // Add a channel and nodes from channel announcement. So our network graph will
2879                         // now only consist of two nodes and one channel between them.
2880                         assert!(network_graph.update_channel_from_announcement(
2881                                 &valid_channel_announcement, &chain_source).is_ok());
2882
2883                         // Mark the channel as permanently failed. This will also remove the two nodes
2884                         // and all of the entries will be tracked as removed.
2885                         network_graph.channel_failed_permanent(short_channel_id);
2886
2887                         // The first time we call the following, the channel will have a removal time assigned.
2888                         network_graph.remove_stale_channels_and_tracking_with_time(removal_time);
2889                         assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2890
2891                         // Provide a later time so that sufficient time has passed
2892                         network_graph.remove_stale_channels_and_tracking_with_time(
2893                                 removal_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2894                         assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2895                         assert!(network_graph.removed_nodes.lock().unwrap().is_empty());
2896                 }
2897         }
2898
2899         #[test]
2900         fn getting_next_channel_announcements() {
2901                 let network_graph = create_network_graph();
2902                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2903                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2904                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2905
2906                 // Channels were not announced yet.
2907                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(0);
2908                 assert!(channels_with_announcements.is_none());
2909
2910                 let short_channel_id;
2911                 {
2912                         // Announce a channel we will update
2913                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2914                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2915                         match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2916                                 Ok(_) => (),
2917                                 Err(_) => panic!()
2918                         };
2919                 }
2920
2921                 // Contains initial channel announcement now.
2922                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2923                 if let Some(channel_announcements) = channels_with_announcements {
2924                         let (_, ref update_1, ref update_2) = channel_announcements;
2925                         assert_eq!(update_1, &None);
2926                         assert_eq!(update_2, &None);
2927                 } else {
2928                         panic!();
2929                 }
2930
2931                 {
2932                         // Valid channel update
2933                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2934                                 unsigned_channel_update.timestamp = 101;
2935                         }, node_1_privkey, &secp_ctx);
2936                         match gossip_sync.handle_channel_update(&valid_channel_update) {
2937                                 Ok(_) => (),
2938                                 Err(_) => panic!()
2939                         };
2940                 }
2941
2942                 // Now contains an initial announcement and an update.
2943                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2944                 if let Some(channel_announcements) = channels_with_announcements {
2945                         let (_, ref update_1, ref update_2) = channel_announcements;
2946                         assert_ne!(update_1, &None);
2947                         assert_eq!(update_2, &None);
2948                 } else {
2949                         panic!();
2950                 }
2951
2952                 {
2953                         // Channel update with excess data.
2954                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2955                                 unsigned_channel_update.timestamp = 102;
2956                                 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2957                         }, node_1_privkey, &secp_ctx);
2958                         match gossip_sync.handle_channel_update(&valid_channel_update) {
2959                                 Ok(_) => (),
2960                                 Err(_) => panic!()
2961                         };
2962                 }
2963
2964                 // Test that announcements with excess data won't be returned
2965                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2966                 if let Some(channel_announcements) = channels_with_announcements {
2967                         let (_, ref update_1, ref update_2) = channel_announcements;
2968                         assert_eq!(update_1, &None);
2969                         assert_eq!(update_2, &None);
2970                 } else {
2971                         panic!();
2972                 }
2973
2974                 // Further starting point have no channels after it
2975                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id + 1000);
2976                 assert!(channels_with_announcements.is_none());
2977         }
2978
2979         #[test]
2980         fn getting_next_node_announcements() {
2981                 let network_graph = create_network_graph();
2982                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2983                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2984                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2985                 let node_id_1 = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2986
2987                 // No nodes yet.
2988                 let next_announcements = gossip_sync.get_next_node_announcement(None);
2989                 assert!(next_announcements.is_none());
2990
2991                 {
2992                         // Announce a channel to add 2 nodes
2993                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2994                         match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2995                                 Ok(_) => (),
2996                                 Err(_) => panic!()
2997                         };
2998                 }
2999
3000                 // Nodes were never announced
3001                 let next_announcements = gossip_sync.get_next_node_announcement(None);
3002                 assert!(next_announcements.is_none());
3003
3004                 {
3005                         let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3006                         match gossip_sync.handle_node_announcement(&valid_announcement) {
3007                                 Ok(_) => (),
3008                                 Err(_) => panic!()
3009                         };
3010
3011                         let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
3012                         match gossip_sync.handle_node_announcement(&valid_announcement) {
3013                                 Ok(_) => (),
3014                                 Err(_) => panic!()
3015                         };
3016                 }
3017
3018                 let next_announcements = gossip_sync.get_next_node_announcement(None);
3019                 assert!(next_announcements.is_some());
3020
3021                 // Skip the first node.
3022                 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3023                 assert!(next_announcements.is_some());
3024
3025                 {
3026                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
3027                         let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
3028                                 unsigned_announcement.timestamp += 10;
3029                                 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
3030                         }, node_2_privkey, &secp_ctx);
3031                         match gossip_sync.handle_node_announcement(&valid_announcement) {
3032                                 Ok(res) => assert!(!res),
3033                                 Err(_) => panic!()
3034                         };
3035                 }
3036
3037                 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3038                 assert!(next_announcements.is_none());
3039         }
3040
3041         #[test]
3042         fn network_graph_serialization() {
3043                 let network_graph = create_network_graph();
3044                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3045
3046                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3047                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3048
3049                 // Announce a channel to add a corresponding node.
3050                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3051                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3052                         Ok(res) => assert!(res),
3053                         _ => panic!()
3054                 };
3055
3056                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3057                 match gossip_sync.handle_node_announcement(&valid_announcement) {
3058                         Ok(_) => (),
3059                         Err(_) => panic!()
3060                 };
3061
3062                 let mut w = test_utils::TestVecWriter(Vec::new());
3063                 assert!(!network_graph.read_only().nodes().is_empty());
3064                 assert!(!network_graph.read_only().channels().is_empty());
3065                 network_graph.write(&mut w).unwrap();
3066
3067                 let logger = Arc::new(test_utils::TestLogger::new());
3068                 assert!(<NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), logger).unwrap() == network_graph);
3069         }
3070
3071         #[test]
3072         fn network_graph_tlv_serialization() {
3073                 let network_graph = create_network_graph();
3074                 network_graph.set_last_rapid_gossip_sync_timestamp(42);
3075
3076                 let mut w = test_utils::TestVecWriter(Vec::new());
3077                 network_graph.write(&mut w).unwrap();
3078
3079                 let logger = Arc::new(test_utils::TestLogger::new());
3080                 let reassembled_network_graph: NetworkGraph<_> = ReadableArgs::read(&mut io::Cursor::new(&w.0), logger).unwrap();
3081                 assert!(reassembled_network_graph == network_graph);
3082                 assert_eq!(reassembled_network_graph.get_last_rapid_gossip_sync_timestamp().unwrap(), 42);
3083         }
3084
3085         #[test]
3086         #[cfg(feature = "std")]
3087         fn calling_sync_routing_table() {
3088                 use std::time::{SystemTime, UNIX_EPOCH};
3089                 use crate::ln::msgs::Init;
3090
3091                 let network_graph = create_network_graph();
3092                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3093                 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
3094                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
3095
3096                 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3097
3098                 // It should ignore if gossip_queries feature is not enabled
3099                 {
3100                         let init_msg = Init { features: InitFeatures::empty(), networks: None, remote_network_address: None };
3101                         gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3102                         let events = gossip_sync.get_and_clear_pending_msg_events();
3103                         assert_eq!(events.len(), 0);
3104                 }
3105
3106                 // It should send a gossip_timestamp_filter with the correct information
3107                 {
3108                         let mut features = InitFeatures::empty();
3109                         features.set_gossip_queries_optional();
3110                         let init_msg = Init { features, networks: None, remote_network_address: None };
3111                         gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3112                         let events = gossip_sync.get_and_clear_pending_msg_events();
3113                         assert_eq!(events.len(), 1);
3114                         match &events[0] {
3115                                 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
3116                                         assert_eq!(node_id, &node_id_1);
3117                                         assert_eq!(msg.chain_hash, chain_hash);
3118                                         let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
3119                                         assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
3120                                         assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
3121                                         assert_eq!(msg.timestamp_range, u32::max_value());
3122                                 },
3123                                 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
3124                         };
3125                 }
3126         }
3127
3128         #[test]
3129         fn handling_query_channel_range() {
3130                 let network_graph = create_network_graph();
3131                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3132
3133                 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3134                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3135                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3136                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
3137
3138                 let mut scids: Vec<u64> = vec![
3139                         scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
3140                         scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
3141                 ];
3142
3143                 // used for testing multipart reply across blocks
3144                 for block in 100000..=108001 {
3145                         scids.push(scid_from_parts(block, 0, 0).unwrap());
3146                 }
3147
3148                 // used for testing resumption on same block
3149                 scids.push(scid_from_parts(108001, 1, 0).unwrap());
3150
3151                 for scid in scids {
3152                         let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
3153                                 unsigned_announcement.short_channel_id = scid;
3154                         }, node_1_privkey, node_2_privkey, &secp_ctx);
3155                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
3156                                 Ok(_) => (),
3157                                 _ => panic!()
3158                         };
3159                 }
3160
3161                 // Error when number_of_blocks=0
3162                 do_handling_query_channel_range(
3163                         &gossip_sync,
3164                         &node_id_2,
3165                         QueryChannelRange {
3166                                 chain_hash: chain_hash.clone(),
3167                                 first_blocknum: 0,
3168                                 number_of_blocks: 0,
3169                         },
3170                         false,
3171                         vec![ReplyChannelRange {
3172                                 chain_hash: chain_hash.clone(),
3173                                 first_blocknum: 0,
3174                                 number_of_blocks: 0,
3175                                 sync_complete: true,
3176                                 short_channel_ids: vec![]
3177                         }]
3178                 );
3179
3180                 // Error when wrong chain
3181                 do_handling_query_channel_range(
3182                         &gossip_sync,
3183                         &node_id_2,
3184                         QueryChannelRange {
3185                                 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3186                                 first_blocknum: 0,
3187                                 number_of_blocks: 0xffff_ffff,
3188                         },
3189                         false,
3190                         vec![ReplyChannelRange {
3191                                 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3192                                 first_blocknum: 0,
3193                                 number_of_blocks: 0xffff_ffff,
3194                                 sync_complete: true,
3195                                 short_channel_ids: vec![],
3196                         }]
3197                 );
3198
3199                 // Error when first_blocknum > 0xffffff
3200                 do_handling_query_channel_range(
3201                         &gossip_sync,
3202                         &node_id_2,
3203                         QueryChannelRange {
3204                                 chain_hash: chain_hash.clone(),
3205                                 first_blocknum: 0x01000000,
3206                                 number_of_blocks: 0xffff_ffff,
3207                         },
3208                         false,
3209                         vec![ReplyChannelRange {
3210                                 chain_hash: chain_hash.clone(),
3211                                 first_blocknum: 0x01000000,
3212                                 number_of_blocks: 0xffff_ffff,
3213                                 sync_complete: true,
3214                                 short_channel_ids: vec![]
3215                         }]
3216                 );
3217
3218                 // Empty reply when max valid SCID block num
3219                 do_handling_query_channel_range(
3220                         &gossip_sync,
3221                         &node_id_2,
3222                         QueryChannelRange {
3223                                 chain_hash: chain_hash.clone(),
3224                                 first_blocknum: 0xffffff,
3225                                 number_of_blocks: 1,
3226                         },
3227                         true,
3228                         vec![
3229                                 ReplyChannelRange {
3230                                         chain_hash: chain_hash.clone(),
3231                                         first_blocknum: 0xffffff,
3232                                         number_of_blocks: 1,
3233                                         sync_complete: true,
3234                                         short_channel_ids: vec![]
3235                                 },
3236                         ]
3237                 );
3238
3239                 // No results in valid query range
3240                 do_handling_query_channel_range(
3241                         &gossip_sync,
3242                         &node_id_2,
3243                         QueryChannelRange {
3244                                 chain_hash: chain_hash.clone(),
3245                                 first_blocknum: 1000,
3246                                 number_of_blocks: 1000,
3247                         },
3248                         true,
3249                         vec![
3250                                 ReplyChannelRange {
3251                                         chain_hash: chain_hash.clone(),
3252                                         first_blocknum: 1000,
3253                                         number_of_blocks: 1000,
3254                                         sync_complete: true,
3255                                         short_channel_ids: vec![],
3256                                 }
3257                         ]
3258                 );
3259
3260                 // Overflow first_blocknum + number_of_blocks
3261                 do_handling_query_channel_range(
3262                         &gossip_sync,
3263                         &node_id_2,
3264                         QueryChannelRange {
3265                                 chain_hash: chain_hash.clone(),
3266                                 first_blocknum: 0xfe0000,
3267                                 number_of_blocks: 0xffffffff,
3268                         },
3269                         true,
3270                         vec![
3271                                 ReplyChannelRange {
3272                                         chain_hash: chain_hash.clone(),
3273                                         first_blocknum: 0xfe0000,
3274                                         number_of_blocks: 0xffffffff - 0xfe0000,
3275                                         sync_complete: true,
3276                                         short_channel_ids: vec![
3277                                                 0xfffffe_ffffff_ffff, // max
3278                                         ]
3279                                 }
3280                         ]
3281                 );
3282
3283                 // Single block exactly full
3284                 do_handling_query_channel_range(
3285                         &gossip_sync,
3286                         &node_id_2,
3287                         QueryChannelRange {
3288                                 chain_hash: chain_hash.clone(),
3289                                 first_blocknum: 100000,
3290                                 number_of_blocks: 8000,
3291                         },
3292                         true,
3293                         vec![
3294                                 ReplyChannelRange {
3295                                         chain_hash: chain_hash.clone(),
3296                                         first_blocknum: 100000,
3297                                         number_of_blocks: 8000,
3298                                         sync_complete: true,
3299                                         short_channel_ids: (100000..=107999)
3300                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3301                                                 .collect(),
3302                                 },
3303                         ]
3304                 );
3305
3306                 // Multiple split on new block
3307                 do_handling_query_channel_range(
3308                         &gossip_sync,
3309                         &node_id_2,
3310                         QueryChannelRange {
3311                                 chain_hash: chain_hash.clone(),
3312                                 first_blocknum: 100000,
3313                                 number_of_blocks: 8001,
3314                         },
3315                         true,
3316                         vec![
3317                                 ReplyChannelRange {
3318                                         chain_hash: chain_hash.clone(),
3319                                         first_blocknum: 100000,
3320                                         number_of_blocks: 7999,
3321                                         sync_complete: false,
3322                                         short_channel_ids: (100000..=107999)
3323                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3324                                                 .collect(),
3325                                 },
3326                                 ReplyChannelRange {
3327                                         chain_hash: chain_hash.clone(),
3328                                         first_blocknum: 107999,
3329                                         number_of_blocks: 2,
3330                                         sync_complete: true,
3331                                         short_channel_ids: vec![
3332                                                 scid_from_parts(108000, 0, 0).unwrap(),
3333                                         ],
3334                                 }
3335                         ]
3336                 );
3337
3338                 // Multiple split on same block
3339                 do_handling_query_channel_range(
3340                         &gossip_sync,
3341                         &node_id_2,
3342                         QueryChannelRange {
3343                                 chain_hash: chain_hash.clone(),
3344                                 first_blocknum: 100002,
3345                                 number_of_blocks: 8000,
3346                         },
3347                         true,
3348                         vec![
3349                                 ReplyChannelRange {
3350                                         chain_hash: chain_hash.clone(),
3351                                         first_blocknum: 100002,
3352                                         number_of_blocks: 7999,
3353                                         sync_complete: false,
3354                                         short_channel_ids: (100002..=108001)
3355                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3356                                                 .collect(),
3357                                 },
3358                                 ReplyChannelRange {
3359                                         chain_hash: chain_hash.clone(),
3360                                         first_blocknum: 108001,
3361                                         number_of_blocks: 1,
3362                                         sync_complete: true,
3363                                         short_channel_ids: vec![
3364                                                 scid_from_parts(108001, 1, 0).unwrap(),
3365                                         ],
3366                                 }
3367                         ]
3368                 );
3369         }
3370
3371         fn do_handling_query_channel_range(
3372                 gossip_sync: &P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
3373                 test_node_id: &PublicKey,
3374                 msg: QueryChannelRange,
3375                 expected_ok: bool,
3376                 expected_replies: Vec<ReplyChannelRange>
3377         ) {
3378                 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
3379                 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
3380                 let query_end_blocknum = msg.end_blocknum();
3381                 let result = gossip_sync.handle_query_channel_range(test_node_id, msg);
3382
3383                 if expected_ok {
3384                         assert!(result.is_ok());
3385                 } else {
3386                         assert!(result.is_err());
3387                 }
3388
3389                 let events = gossip_sync.get_and_clear_pending_msg_events();
3390                 assert_eq!(events.len(), expected_replies.len());
3391
3392                 for i in 0..events.len() {
3393                         let expected_reply = &expected_replies[i];
3394                         match &events[i] {
3395                                 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
3396                                         assert_eq!(node_id, test_node_id);
3397                                         assert_eq!(msg.chain_hash, expected_reply.chain_hash);
3398                                         assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
3399                                         assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
3400                                         assert_eq!(msg.sync_complete, expected_reply.sync_complete);
3401                                         assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
3402
3403                                         // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
3404                                         assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
3405                                         assert!(msg.first_blocknum >= max_firstblocknum);
3406                                         max_firstblocknum = msg.first_blocknum;
3407                                         c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
3408
3409                                         // Check that the last block count is >= the query's end_blocknum
3410                                         if i == events.len() - 1 {
3411                                                 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
3412                                         }
3413                                 },
3414                                 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
3415                         }
3416                 }
3417         }
3418
3419         #[test]
3420         fn handling_query_short_channel_ids() {
3421                 let network_graph = create_network_graph();
3422                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3423                 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3424                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
3425
3426                 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3427
3428                 let result = gossip_sync.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
3429                         chain_hash,
3430                         short_channel_ids: vec![0x0003e8_000000_0000],
3431                 });
3432                 assert!(result.is_err());
3433         }
3434
3435         #[test]
3436         fn displays_node_alias() {
3437                 let format_str_alias = |alias: &str| {
3438                         let mut bytes = [0u8; 32];
3439                         bytes[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
3440                         format!("{}", NodeAlias(bytes))
3441                 };
3442
3443                 assert_eq!(format_str_alias("I\u{1F496}LDK! \u{26A1}"), "I\u{1F496}LDK! \u{26A1}");
3444                 assert_eq!(format_str_alias("I\u{1F496}LDK!\0\u{26A1}"), "I\u{1F496}LDK!");
3445                 assert_eq!(format_str_alias("I\u{1F496}LDK!\t\u{26A1}"), "I\u{1F496}LDK!\u{FFFD}\u{26A1}");
3446
3447                 let format_bytes_alias = |alias: &[u8]| {
3448                         let mut bytes = [0u8; 32];
3449                         bytes[..alias.len()].copy_from_slice(alias);
3450                         format!("{}", NodeAlias(bytes))
3451                 };
3452
3453                 assert_eq!(format_bytes_alias(b"\xFFI <heart> LDK!"), "\u{FFFD}I <heart> LDK!");
3454                 assert_eq!(format_bytes_alias(b"\xFFI <heart>\0LDK!"), "\u{FFFD}I <heart>");
3455                 assert_eq!(format_bytes_alias(b"\xFFI <heart>\tLDK!"), "\u{FFFD}I <heart>\u{FFFD}LDK!");
3456         }
3457
3458         #[test]
3459         fn channel_info_is_readable() {
3460                 let chanmon_cfgs = crate::ln::functional_test_utils::create_chanmon_cfgs(2);
3461                 let node_cfgs = crate::ln::functional_test_utils::create_node_cfgs(2, &chanmon_cfgs);
3462                 let node_chanmgrs = crate::ln::functional_test_utils::create_node_chanmgrs(2, &node_cfgs, &[None, None, None, None]);
3463                 let nodes = crate::ln::functional_test_utils::create_network(2, &node_cfgs, &node_chanmgrs);
3464                 let config = crate::ln::functional_test_utils::test_default_channel_config();
3465
3466                 // 1. Test encoding/decoding of ChannelUpdateInfo
3467                 let chan_update_info = ChannelUpdateInfo {
3468                         last_update: 23,
3469                         enabled: true,
3470                         cltv_expiry_delta: 42,
3471                         htlc_minimum_msat: 1234,
3472                         htlc_maximum_msat: 5678,
3473                         fees: RoutingFees { base_msat: 9, proportional_millionths: 10 },
3474                         last_update_message: None,
3475                 };
3476
3477                 let mut encoded_chan_update_info: Vec<u8> = Vec::new();
3478                 assert!(chan_update_info.write(&mut encoded_chan_update_info).is_ok());
3479
3480                 // First make sure we can read ChannelUpdateInfos we just wrote
3481                 let read_chan_update_info: ChannelUpdateInfo = crate::util::ser::Readable::read(&mut encoded_chan_update_info.as_slice()).unwrap();
3482                 assert_eq!(chan_update_info, read_chan_update_info);
3483
3484                 // Check the serialization hasn't changed.
3485                 let legacy_chan_update_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c0100").unwrap();
3486                 assert_eq!(encoded_chan_update_info, legacy_chan_update_info_with_some);
3487
3488                 // Check we fail if htlc_maximum_msat is not present in either the ChannelUpdateInfo itself
3489                 // or the ChannelUpdate enclosed with `last_update_message`.
3490                 let legacy_chan_update_info_with_some_and_fail_update: Vec<u8> = <Vec<u8>>::from_hex("b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f42400000271000000014").unwrap();
3491                 let read_chan_update_info_res: Result<ChannelUpdateInfo, crate::ln::msgs::DecodeError> = crate::util::ser::Readable::read(&mut legacy_chan_update_info_with_some_and_fail_update.as_slice());
3492                 assert!(read_chan_update_info_res.is_err());
3493
3494                 let legacy_chan_update_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100").unwrap();
3495                 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());
3496                 assert!(read_chan_update_info_res.is_err());
3497
3498                 // 2. Test encoding/decoding of ChannelInfo
3499                 // Check we can encode/decode ChannelInfo without ChannelUpdateInfo fields present.
3500                 let chan_info_none_updates = ChannelInfo {
3501                         features: channelmanager::provided_channel_features(&config),
3502                         node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3503                         one_to_two: None,
3504                         node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3505                         two_to_one: None,
3506                         capacity_sats: None,
3507                         announcement_message: None,
3508                         announcement_received_time: 87654,
3509                         node_one_counter: 0,
3510                         node_two_counter: 1,
3511                 };
3512
3513                 let mut encoded_chan_info: Vec<u8> = Vec::new();
3514                 assert!(chan_info_none_updates.write(&mut encoded_chan_info).is_ok());
3515
3516                 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3517                 assert_eq!(chan_info_none_updates, read_chan_info);
3518
3519                 // Check we can encode/decode ChannelInfo with ChannelUpdateInfo fields present.
3520                 let chan_info_some_updates = ChannelInfo {
3521                         features: channelmanager::provided_channel_features(&config),
3522                         node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3523                         one_to_two: Some(chan_update_info.clone()),
3524                         node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3525                         two_to_one: Some(chan_update_info.clone()),
3526                         capacity_sats: None,
3527                         announcement_message: None,
3528                         announcement_received_time: 87654,
3529                         node_one_counter: 0,
3530                         node_two_counter: 1,
3531                 };
3532
3533                 let mut encoded_chan_info: Vec<u8> = Vec::new();
3534                 assert!(chan_info_some_updates.write(&mut encoded_chan_info).is_ok());
3535
3536                 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3537                 assert_eq!(chan_info_some_updates, read_chan_info);
3538
3539                 // Check the serialization hasn't changed.
3540                 let legacy_chan_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88043636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23083636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3541                 assert_eq!(encoded_chan_info, legacy_chan_info_with_some);
3542
3543                 // Check we can decode legacy ChannelInfo, even if the `two_to_one` / `one_to_two` /
3544                 // `last_update_message` fields fail to decode due to missing htlc_maximum_msat.
3545                 let legacy_chan_info_with_some_and_fail_update = <Vec<u8>>::from_hex("fd01ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce8804b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f4240000027100000001406210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2308b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f424000002710000000140a01000c0100").unwrap();
3546                 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_some_and_fail_update.as_slice()).unwrap();
3547                 assert_eq!(read_chan_info.announcement_received_time, 87654);
3548                 assert_eq!(read_chan_info.one_to_two, None);
3549                 assert_eq!(read_chan_info.two_to_one, None);
3550
3551                 let legacy_chan_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("ba00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88042e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23082e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3552                 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_none.as_slice()).unwrap();
3553                 assert_eq!(read_chan_info.announcement_received_time, 87654);
3554                 assert_eq!(read_chan_info.one_to_two, None);
3555                 assert_eq!(read_chan_info.two_to_one, None);
3556         }
3557
3558         #[test]
3559         fn node_info_is_readable() {
3560                 // 1. Check we can read a valid NodeAnnouncementInfo and fail on an invalid one
3561                 let announcement_message = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000122013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010000701fffefdfc2607").unwrap();
3562                 let announcement_message = NodeAnnouncement::read(&mut announcement_message.as_slice()).unwrap();
3563                 let valid_node_ann_info = NodeAnnouncementInfo {
3564                         features: channelmanager::provided_node_features(&UserConfig::default()),
3565                         last_update: 0,
3566                         rgb: [0u8; 3],
3567                         alias: NodeAlias([0u8; 32]),
3568                         announcement_message: Some(announcement_message)
3569                 };
3570
3571                 let mut encoded_valid_node_ann_info = Vec::new();
3572                 assert!(valid_node_ann_info.write(&mut encoded_valid_node_ann_info).is_ok());
3573                 let read_valid_node_ann_info = NodeAnnouncementInfo::read(&mut encoded_valid_node_ann_info.as_slice()).unwrap();
3574                 assert_eq!(read_valid_node_ann_info, valid_node_ann_info);
3575                 assert_eq!(read_valid_node_ann_info.addresses().len(), 1);
3576
3577                 let encoded_invalid_node_ann_info = <Vec<u8>>::from_hex("3f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d2").unwrap();
3578                 let read_invalid_node_ann_info_res = NodeAnnouncementInfo::read(&mut encoded_invalid_node_ann_info.as_slice());
3579                 assert!(read_invalid_node_ann_info_res.is_err());
3580
3581                 // 2. Check we can read a NodeInfo anyways, but set the NodeAnnouncementInfo to None if invalid
3582                 let valid_node_info = NodeInfo {
3583                         channels: Vec::new(),
3584                         announcement_info: Some(valid_node_ann_info),
3585                         node_counter: 0,
3586                 };
3587
3588                 let mut encoded_valid_node_info = Vec::new();
3589                 assert!(valid_node_info.write(&mut encoded_valid_node_info).is_ok());
3590                 let read_valid_node_info = NodeInfo::read(&mut encoded_valid_node_info.as_slice()).unwrap();
3591                 assert_eq!(read_valid_node_info, valid_node_info);
3592
3593                 let encoded_invalid_node_info_hex = <Vec<u8>>::from_hex("4402403f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d20400").unwrap();
3594                 let read_invalid_node_info = NodeInfo::read(&mut encoded_invalid_node_info_hex.as_slice()).unwrap();
3595                 assert_eq!(read_invalid_node_info.announcement_info, None);
3596         }
3597
3598         #[test]
3599         fn test_node_info_keeps_compatibility() {
3600                 let old_ann_info_with_addresses = <Vec<u8>>::from_hex("3f0009000708a000080a51220204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014104d2").unwrap();
3601                 let ann_info_with_addresses = NodeAnnouncementInfo::read(&mut old_ann_info_with_addresses.as_slice())
3602                                 .expect("to be able to read an old NodeAnnouncementInfo with addresses");
3603                 // This serialized info has an address field but no announcement_message, therefore the addresses returned by our function will still be empty
3604                 assert!(ann_info_with_addresses.addresses().is_empty());
3605         }
3606
3607         #[test]
3608         fn test_node_id_display() {
3609                 let node_id = NodeId([42; 33]);
3610                 assert_eq!(format!("{}", &node_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
3611         }
3612
3613         #[test]
3614         fn is_tor_only_node() {
3615                 let network_graph = create_network_graph();
3616                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3617
3618                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3619                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3620                 let node_1_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
3621
3622                 let announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3623                 gossip_sync.handle_channel_announcement(&announcement).unwrap();
3624
3625                 let tcp_ip_v4 = SocketAddress::TcpIpV4 {
3626                         addr: [255, 254, 253, 252],
3627                         port: 9735
3628                 };
3629                 let tcp_ip_v6 = SocketAddress::TcpIpV6 {
3630                         addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
3631                         port: 9735
3632                 };
3633                 let onion_v2 = SocketAddress::OnionV2([255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]);
3634                 let onion_v3 = SocketAddress::OnionV3 {
3635                         ed25519_pubkey: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224],
3636                         checksum: 32,
3637                         version: 16,
3638                         port: 9735
3639                 };
3640                 let hostname = SocketAddress::Hostname {
3641                         hostname: Hostname::try_from(String::from("host")).unwrap(),
3642                         port: 9735,
3643                 };
3644
3645                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3646
3647                 let announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3648                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3649                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3650
3651                 let announcement = get_signed_node_announcement(
3652                         |announcement| {
3653                                 announcement.addresses = vec![
3654                                         tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone(),
3655                                         hostname.clone()
3656                                 ];
3657                                 announcement.timestamp += 1000;
3658                         },
3659                         node_1_privkey, &secp_ctx
3660                 );
3661                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3662                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3663
3664                 let announcement = get_signed_node_announcement(
3665                         |announcement| {
3666                                 announcement.addresses = vec![
3667                                         tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3668                                 ];
3669                                 announcement.timestamp += 2000;
3670                         },
3671                         node_1_privkey, &secp_ctx
3672                 );
3673                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3674                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3675
3676                 let announcement = get_signed_node_announcement(
3677                         |announcement| {
3678                                 announcement.addresses = vec![
3679                                         tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3680                                 ];
3681                                 announcement.timestamp += 3000;
3682                         },
3683                         node_1_privkey, &secp_ctx
3684                 );
3685                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3686                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3687
3688                 let announcement = get_signed_node_announcement(
3689                         |announcement| {
3690                                 announcement.addresses = vec![onion_v2.clone(), onion_v3.clone()];
3691                                 announcement.timestamp += 4000;
3692                         },
3693                         node_1_privkey, &secp_ctx
3694                 );
3695                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3696                 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3697
3698                 let announcement = get_signed_node_announcement(
3699                         |announcement| {
3700                                 announcement.addresses = vec![onion_v2.clone()];
3701                                 announcement.timestamp += 5000;
3702                         },
3703                         node_1_privkey, &secp_ctx
3704                 );
3705                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3706                 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3707
3708                 let announcement = get_signed_node_announcement(
3709                         |announcement| {
3710                                 announcement.addresses = vec![tcp_ip_v4.clone()];
3711                                 announcement.timestamp += 6000;
3712                         },
3713                         node_1_privkey, &secp_ctx
3714                 );
3715                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3716                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3717         }
3718 }
3719
3720 #[cfg(ldk_bench)]
3721 pub mod benches {
3722         use super::*;
3723         use std::io::Read;
3724         use criterion::{black_box, Criterion};
3725
3726         pub fn read_network_graph(bench: &mut Criterion) {
3727                 let logger = crate::util::test_utils::TestLogger::new();
3728                 let (mut d, _) = crate::routing::router::bench_utils::get_graph_scorer_file().unwrap();
3729                 let mut v = Vec::new();
3730                 d.read_to_end(&mut v).unwrap();
3731                 bench.bench_function("read_network_graph", |b| b.iter(||
3732                         NetworkGraph::read(&mut std::io::Cursor::new(black_box(&v)), &logger).unwrap()
3733                 ));
3734         }
3735
3736         pub fn write_network_graph(bench: &mut Criterion) {
3737                 let logger = crate::util::test_utils::TestLogger::new();
3738                 let (mut d, _) = crate::routing::router::bench_utils::get_graph_scorer_file().unwrap();
3739                 let net_graph = NetworkGraph::read(&mut d, &logger).unwrap();
3740                 bench.bench_function("write_network_graph", |b| b.iter(||
3741                         black_box(&net_graph).encode()
3742                 ));
3743         }
3744 }