Add a new `NodeCounters` utility to track counters when routing
[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
1068 impl<'a> fmt::Debug for DirectedChannelInfo<'a> {
1069         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1070                 f.debug_struct("DirectedChannelInfo")
1071                         .field("channel", &self.channel)
1072                         .finish()
1073         }
1074 }
1075
1076 /// The effective capacity of a channel for routing purposes.
1077 ///
1078 /// While this may be smaller than the actual channel capacity, amounts greater than
1079 /// [`Self::as_msat`] should not be routed through the channel.
1080 #[derive(Clone, Copy, Debug, PartialEq)]
1081 pub enum EffectiveCapacity {
1082         /// The available liquidity in the channel known from being a channel counterparty, and thus a
1083         /// direct hop.
1084         ExactLiquidity {
1085                 /// Either the inbound or outbound liquidity depending on the direction, denominated in
1086                 /// millisatoshi.
1087                 liquidity_msat: u64,
1088         },
1089         /// The maximum HTLC amount in one direction as advertised on the gossip network.
1090         AdvertisedMaxHTLC {
1091                 /// The maximum HTLC amount denominated in millisatoshi.
1092                 amount_msat: u64,
1093         },
1094         /// The total capacity of the channel as determined by the funding transaction.
1095         Total {
1096                 /// The funding amount denominated in millisatoshi.
1097                 capacity_msat: u64,
1098                 /// The maximum HTLC amount denominated in millisatoshi.
1099                 htlc_maximum_msat: u64
1100         },
1101         /// A capacity sufficient to route any payment, typically used for private channels provided by
1102         /// an invoice.
1103         Infinite,
1104         /// The maximum HTLC amount as provided by an invoice route hint.
1105         HintMaxHTLC {
1106                 /// The maximum HTLC amount denominated in millisatoshi.
1107                 amount_msat: u64,
1108         },
1109         /// A capacity that is unknown possibly because either the chain state is unavailable to know
1110         /// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
1111         Unknown,
1112 }
1113
1114 /// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
1115 /// use when making routing decisions.
1116 pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
1117
1118 impl EffectiveCapacity {
1119         /// Returns the effective capacity denominated in millisatoshi.
1120         pub fn as_msat(&self) -> u64 {
1121                 match self {
1122                         EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
1123                         EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } => *amount_msat,
1124                         EffectiveCapacity::Total { capacity_msat, .. } => *capacity_msat,
1125                         EffectiveCapacity::HintMaxHTLC { amount_msat } => *amount_msat,
1126                         EffectiveCapacity::Infinite => u64::max_value(),
1127                         EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
1128                 }
1129         }
1130 }
1131
1132 /// Fees for routing via a given channel or a node
1133 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash, Ord, PartialOrd)]
1134 pub struct RoutingFees {
1135         /// Flat routing fee in millisatoshis.
1136         pub base_msat: u32,
1137         /// Liquidity-based routing fee in millionths of a routed amount.
1138         /// In other words, 10000 is 1%.
1139         pub proportional_millionths: u32,
1140 }
1141
1142 impl_writeable_tlv_based!(RoutingFees, {
1143         (0, base_msat, required),
1144         (2, proportional_millionths, required)
1145 });
1146
1147 #[derive(Clone, Debug, PartialEq, Eq)]
1148 /// Information received in the latest node_announcement from this node.
1149 pub struct NodeAnnouncementInfo {
1150         /// Protocol features the node announced support for
1151         pub features: NodeFeatures,
1152         /// When the last known update to the node state was issued.
1153         /// Value is opaque, as set in the announcement.
1154         pub last_update: u32,
1155         /// Color assigned to the node
1156         pub rgb: [u8; 3],
1157         /// Moniker assigned to the node.
1158         /// May be invalid or malicious (eg control chars),
1159         /// should not be exposed to the user.
1160         pub alias: NodeAlias,
1161         /// An initial announcement of the node
1162         /// Mostly redundant with the data we store in fields explicitly.
1163         /// Everything else is useful only for sending out for initial routing sync.
1164         /// Not stored if contains excess data to prevent DoS.
1165         pub announcement_message: Option<NodeAnnouncement>
1166 }
1167
1168 impl NodeAnnouncementInfo {
1169         /// Internet-level addresses via which one can connect to the node
1170         pub fn addresses(&self) -> &[SocketAddress] {
1171                 self.announcement_message.as_ref()
1172                         .map(|msg| msg.contents.addresses.as_slice())
1173                         .unwrap_or_default()
1174         }
1175 }
1176
1177 impl Writeable for NodeAnnouncementInfo {
1178         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1179                 let empty_addresses = Vec::<SocketAddress>::new();
1180                 write_tlv_fields!(writer, {
1181                         (0, self.features, required),
1182                         (2, self.last_update, required),
1183                         (4, self.rgb, required),
1184                         (6, self.alias, required),
1185                         (8, self.announcement_message, option),
1186                         (10, empty_addresses, required_vec), // Versions prior to 0.0.115 require this field
1187                 });
1188                 Ok(())
1189         }
1190 }
1191
1192 impl Readable for NodeAnnouncementInfo {
1193         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1194                 _init_and_read_len_prefixed_tlv_fields!(reader, {
1195                         (0, features, required),
1196                         (2, last_update, required),
1197                         (4, rgb, required),
1198                         (6, alias, required),
1199                         (8, announcement_message, option),
1200                         (10, _addresses, optional_vec), // deprecated, not used anymore
1201                 });
1202                 let _: Option<Vec<SocketAddress>> = _addresses;
1203                 Ok(Self { features: features.0.unwrap(), last_update: last_update.0.unwrap(), rgb: rgb.0.unwrap(),
1204                         alias: alias.0.unwrap(), announcement_message })
1205         }
1206 }
1207
1208 /// A user-defined name for a node, which may be used when displaying the node in a graph.
1209 ///
1210 /// Since node aliases are provided by third parties, they are a potential avenue for injection
1211 /// attacks. Care must be taken when processing.
1212 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
1213 pub struct NodeAlias(pub [u8; 32]);
1214
1215 impl fmt::Display for NodeAlias {
1216         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1217                 let first_null = self.0.iter().position(|b| *b == 0).unwrap_or(self.0.len());
1218                 let bytes = self.0.split_at(first_null).0;
1219                 match core::str::from_utf8(bytes) {
1220                         Ok(alias) => PrintableString(alias).fmt(f)?,
1221                         Err(_) => {
1222                                 use core::fmt::Write;
1223                                 for c in bytes.iter().map(|b| *b as char) {
1224                                         // Display printable ASCII characters
1225                                         let control_symbol = core::char::REPLACEMENT_CHARACTER;
1226                                         let c = if c >= '\x20' && c <= '\x7e' { c } else { control_symbol };
1227                                         f.write_char(c)?;
1228                                 }
1229                         },
1230                 };
1231                 Ok(())
1232         }
1233 }
1234
1235 impl Writeable for NodeAlias {
1236         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1237                 self.0.write(w)
1238         }
1239 }
1240
1241 impl Readable for NodeAlias {
1242         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
1243                 Ok(NodeAlias(Readable::read(r)?))
1244         }
1245 }
1246
1247 #[derive(Clone, Debug, Eq)]
1248 /// Details about a node in the network, known from the network announcement.
1249 pub struct NodeInfo {
1250         /// All valid channels a node has announced
1251         pub channels: Vec<u64>,
1252         /// More information about a node from node_announcement.
1253         /// Optional because we store a Node entry after learning about it from
1254         /// a channel announcement, but before receiving a node announcement.
1255         pub announcement_info: Option<NodeAnnouncementInfo>,
1256         /// In memory, each node is assigned a unique ID. They are eagerly reused, ensuring they remain
1257         /// relatively dense.
1258         ///
1259         /// These IDs allow the router to avoid a `HashMap` lookup by simply using this value as an
1260         /// index in a `Vec`, skipping a big step in some of the hottest code when routing.
1261         pub(crate) node_counter: u32,
1262 }
1263
1264 impl PartialEq for NodeInfo {
1265         fn eq(&self, o: &NodeInfo) -> bool {
1266                 self.channels == o.channels && self.announcement_info == o.announcement_info
1267         }
1268 }
1269
1270 impl NodeInfo {
1271         /// Returns whether the node has only announced Tor addresses.
1272         pub fn is_tor_only(&self) -> bool {
1273                 self.announcement_info
1274                         .as_ref()
1275                         .map(|info| info.addresses())
1276                         .and_then(|addresses| (!addresses.is_empty()).then(|| addresses))
1277                         .map(|addresses| addresses.iter().all(|address| address.is_tor()))
1278                         .unwrap_or(false)
1279         }
1280 }
1281
1282 impl fmt::Display for NodeInfo {
1283         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1284                 write!(f, " channels: {:?}, announcement_info: {:?}",
1285                         &self.channels[..], self.announcement_info)?;
1286                 Ok(())
1287         }
1288 }
1289
1290 impl Writeable for NodeInfo {
1291         fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1292                 write_tlv_fields!(writer, {
1293                         // Note that older versions of LDK wrote the lowest inbound fees here at type 0
1294                         (2, self.announcement_info, option),
1295                         (4, self.channels, required_vec),
1296                 });
1297                 Ok(())
1298         }
1299 }
1300
1301 // A wrapper allowing for the optional deserialization of `NodeAnnouncementInfo`. Utilizing this is
1302 // necessary to maintain compatibility with previous serializations of `SocketAddress` that have an
1303 // invalid hostname set. We ignore and eat all errors until we are either able to read a
1304 // `NodeAnnouncementInfo` or hit a `ShortRead`, i.e., read the TLV field to the end.
1305 struct NodeAnnouncementInfoDeserWrapper(NodeAnnouncementInfo);
1306
1307 impl MaybeReadable for NodeAnnouncementInfoDeserWrapper {
1308         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
1309                 match crate::util::ser::Readable::read(reader) {
1310                         Ok(node_announcement_info) => return Ok(Some(Self(node_announcement_info))),
1311                         Err(_) => {
1312                                 copy(reader, &mut sink()).unwrap();
1313                                 return Ok(None)
1314                         },
1315                 };
1316         }
1317 }
1318
1319 impl Readable for NodeInfo {
1320         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1321                 // Historically, we tracked the lowest inbound fees for any node in order to use it as an
1322                 // A* heuristic when routing. Sadly, these days many, many nodes have at least one channel
1323                 // with zero inbound fees, causing that heuristic to provide little gain. Worse, because it
1324                 // requires additional complexity and lookups during routing, it ends up being a
1325                 // performance loss. Thus, we simply ignore the old field here and no longer track it.
1326                 _init_and_read_len_prefixed_tlv_fields!(reader, {
1327                         (0, _lowest_inbound_channel_fees, option),
1328                         (2, announcement_info_wrap, upgradable_option),
1329                         (4, channels, required_vec),
1330                 });
1331                 let _: Option<RoutingFees> = _lowest_inbound_channel_fees;
1332                 let announcement_info_wrap: Option<NodeAnnouncementInfoDeserWrapper> = announcement_info_wrap;
1333
1334                 Ok(NodeInfo {
1335                         announcement_info: announcement_info_wrap.map(|w| w.0),
1336                         channels,
1337                         node_counter: u32::max_value(),
1338                 })
1339         }
1340 }
1341
1342 const SERIALIZATION_VERSION: u8 = 1;
1343 const MIN_SERIALIZATION_VERSION: u8 = 1;
1344
1345 impl<L: Deref> Writeable for NetworkGraph<L> where L::Target: Logger {
1346         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1347                 self.test_node_counter_consistency();
1348
1349                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1350
1351                 self.chain_hash.write(writer)?;
1352                 let channels = self.channels.read().unwrap();
1353                 (channels.len() as u64).write(writer)?;
1354                 for (ref chan_id, ref chan_info) in channels.unordered_iter() {
1355                         (*chan_id).write(writer)?;
1356                         chan_info.write(writer)?;
1357                 }
1358                 let nodes = self.nodes.read().unwrap();
1359                 (nodes.len() as u64).write(writer)?;
1360                 for (ref node_id, ref node_info) in nodes.unordered_iter() {
1361                         node_id.write(writer)?;
1362                         node_info.write(writer)?;
1363                 }
1364
1365                 let last_rapid_gossip_sync_timestamp = self.get_last_rapid_gossip_sync_timestamp();
1366                 write_tlv_fields!(writer, {
1367                         (1, last_rapid_gossip_sync_timestamp, option),
1368                 });
1369                 Ok(())
1370         }
1371 }
1372
1373 impl<L: Deref> ReadableArgs<L> for NetworkGraph<L> where L::Target: Logger {
1374         fn read<R: io::Read>(reader: &mut R, logger: L) -> Result<NetworkGraph<L>, DecodeError> {
1375                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1376
1377                 let chain_hash: ChainHash = Readable::read(reader)?;
1378                 let channels_count: u64 = Readable::read(reader)?;
1379                 // In Nov, 2023 there were about 15,000 nodes; we cap allocations to 1.5x that.
1380                 let mut channels = IndexedMap::with_capacity(cmp::min(channels_count as usize, 22500));
1381                 for _ in 0..channels_count {
1382                         let chan_id: u64 = Readable::read(reader)?;
1383                         let chan_info: ChannelInfo = Readable::read(reader)?;
1384                         channels.insert(chan_id, chan_info);
1385                 }
1386                 let nodes_count: u64 = Readable::read(reader)?;
1387                 if nodes_count > u32::max_value() as u64 / 2 { return Err(DecodeError::InvalidValue); }
1388                 // In Nov, 2023 there were about 69K channels; we cap allocations to 1.5x that.
1389                 let mut nodes = IndexedMap::with_capacity(cmp::min(nodes_count as usize, 103500));
1390                 for i in 0..nodes_count {
1391                         let node_id = Readable::read(reader)?;
1392                         let mut node_info: NodeInfo = Readable::read(reader)?;
1393                         node_info.node_counter = i as u32;
1394                         nodes.insert(node_id, node_info);
1395                 }
1396
1397                 for (_, chan) in channels.unordered_iter_mut() {
1398                         chan.node_one_counter =
1399                                 nodes.get(&chan.node_one).ok_or(DecodeError::InvalidValue)?.node_counter;
1400                         chan.node_two_counter =
1401                                 nodes.get(&chan.node_two).ok_or(DecodeError::InvalidValue)?.node_counter;
1402                 }
1403
1404                 let mut last_rapid_gossip_sync_timestamp: Option<u32> = None;
1405                 read_tlv_fields!(reader, {
1406                         (1, last_rapid_gossip_sync_timestamp, option),
1407                 });
1408
1409                 Ok(NetworkGraph {
1410                         secp_ctx: Secp256k1::verification_only(),
1411                         chain_hash,
1412                         logger,
1413                         channels: RwLock::new(channels),
1414                         nodes: RwLock::new(nodes),
1415                         removed_node_counters: Mutex::new(Vec::new()),
1416                         next_node_counter: AtomicUsize::new(nodes_count as usize),
1417                         last_rapid_gossip_sync_timestamp: Mutex::new(last_rapid_gossip_sync_timestamp),
1418                         removed_nodes: Mutex::new(new_hash_map()),
1419                         removed_channels: Mutex::new(new_hash_map()),
1420                         pending_checks: utxo::PendingChecks::new(),
1421                 })
1422         }
1423 }
1424
1425 impl<L: Deref> fmt::Display for NetworkGraph<L> where L::Target: Logger {
1426         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1427                 writeln!(f, "Network map\n[Channels]")?;
1428                 for (key, val) in self.channels.read().unwrap().unordered_iter() {
1429                         writeln!(f, " {}: {}", key, val)?;
1430                 }
1431                 writeln!(f, "[Nodes]")?;
1432                 for (&node_id, val) in self.nodes.read().unwrap().unordered_iter() {
1433                         writeln!(f, " {}: {}", &node_id, val)?;
1434                 }
1435                 Ok(())
1436         }
1437 }
1438
1439 impl<L: Deref> Eq for NetworkGraph<L> where L::Target: Logger {}
1440 impl<L: Deref> PartialEq for NetworkGraph<L> where L::Target: Logger {
1441         fn eq(&self, other: &Self) -> bool {
1442                 // For a total lockorder, sort by position in memory and take the inner locks in that order.
1443                 // (Assumes that we can't move within memory while a lock is held).
1444                 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1445                 let a = if ord { (&self.channels, &self.nodes) } else { (&other.channels, &other.nodes) };
1446                 let b = if ord { (&other.channels, &other.nodes) } else { (&self.channels, &self.nodes) };
1447                 let (channels_a, channels_b) = (a.0.unsafe_well_ordered_double_lock_self(), b.0.unsafe_well_ordered_double_lock_self());
1448                 let (nodes_a, nodes_b) = (a.1.unsafe_well_ordered_double_lock_self(), b.1.unsafe_well_ordered_double_lock_self());
1449                 self.chain_hash.eq(&other.chain_hash) && channels_a.eq(&channels_b) && nodes_a.eq(&nodes_b)
1450         }
1451 }
1452
1453 impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
1454         /// Creates a new, empty, network graph.
1455         pub fn new(network: Network, logger: L) -> NetworkGraph<L> {
1456                 Self {
1457                         secp_ctx: Secp256k1::verification_only(),
1458                         chain_hash: ChainHash::using_genesis_block(network),
1459                         logger,
1460                         channels: RwLock::new(IndexedMap::new()),
1461                         nodes: RwLock::new(IndexedMap::new()),
1462                         next_node_counter: AtomicUsize::new(0),
1463                         removed_node_counters: Mutex::new(Vec::new()),
1464                         last_rapid_gossip_sync_timestamp: Mutex::new(None),
1465                         removed_channels: Mutex::new(new_hash_map()),
1466                         removed_nodes: Mutex::new(new_hash_map()),
1467                         pending_checks: utxo::PendingChecks::new(),
1468                 }
1469         }
1470
1471         fn test_node_counter_consistency(&self) {
1472                 #[cfg(debug_assertions)] {
1473                         let channels = self.channels.read().unwrap();
1474                         let nodes = self.nodes.read().unwrap();
1475                         let removed_node_counters = self.removed_node_counters.lock().unwrap();
1476                         let next_counter = self.next_node_counter.load(Ordering::Acquire);
1477                         assert!(next_counter < (u32::max_value() as usize) / 2);
1478                         let mut used_node_counters = vec![0u8; next_counter / 8 + 1];
1479
1480                         for counter in removed_node_counters.iter() {
1481                                 let pos = (*counter as usize) / 8;
1482                                 let bit = 1 << (counter % 8);
1483                                 assert_eq!(used_node_counters[pos] & bit, 0);
1484                                 used_node_counters[pos] |= bit;
1485                         }
1486                         for (_, node) in nodes.unordered_iter() {
1487                                 assert!((node.node_counter as usize) < next_counter);
1488                                 let pos = (node.node_counter as usize) / 8;
1489                                 let bit = 1 << (node.node_counter % 8);
1490                                 assert_eq!(used_node_counters[pos] & bit, 0);
1491                                 used_node_counters[pos] |= bit;
1492                         }
1493
1494                         for (_, chan) in channels.unordered_iter() {
1495                                 assert_eq!(chan.node_one_counter, nodes.get(&chan.node_one).unwrap().node_counter);
1496                                 assert_eq!(chan.node_two_counter, nodes.get(&chan.node_two).unwrap().node_counter);
1497                         }
1498                 }
1499         }
1500
1501         /// Returns a read-only view of the network graph.
1502         pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
1503                 self.test_node_counter_consistency();
1504                 let channels = self.channels.read().unwrap();
1505                 let nodes = self.nodes.read().unwrap();
1506                 ReadOnlyNetworkGraph {
1507                         channels,
1508                         nodes,
1509                         max_node_counter: (self.next_node_counter.load(Ordering::Acquire) as u32).saturating_sub(1),
1510                 }
1511         }
1512
1513         /// The unix timestamp provided by the most recent rapid gossip sync.
1514         /// It will be set by the rapid sync process after every sync completion.
1515         pub fn get_last_rapid_gossip_sync_timestamp(&self) -> Option<u32> {
1516                 self.last_rapid_gossip_sync_timestamp.lock().unwrap().clone()
1517         }
1518
1519         /// Update the unix timestamp provided by the most recent rapid gossip sync.
1520         /// This should be done automatically by the rapid sync process after every sync completion.
1521         pub fn set_last_rapid_gossip_sync_timestamp(&self, last_rapid_gossip_sync_timestamp: u32) {
1522                 self.last_rapid_gossip_sync_timestamp.lock().unwrap().replace(last_rapid_gossip_sync_timestamp);
1523         }
1524
1525         /// Clears the `NodeAnnouncementInfo` field for all nodes in the `NetworkGraph` for testing
1526         /// purposes.
1527         #[cfg(test)]
1528         pub fn clear_nodes_announcement_info(&self) {
1529                 for node in self.nodes.write().unwrap().unordered_iter_mut() {
1530                         node.1.announcement_info = None;
1531                 }
1532         }
1533
1534         /// For an already known node (from channel announcements), update its stored properties from a
1535         /// given node announcement.
1536         ///
1537         /// You probably don't want to call this directly, instead relying on a P2PGossipSync's
1538         /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1539         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1540         pub fn update_node_from_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), LightningError> {
1541                 verify_node_announcement(msg, &self.secp_ctx)?;
1542                 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1543         }
1544
1545         /// For an already known node (from channel announcements), update its stored properties from a
1546         /// given node announcement without verifying the associated signatures. Because we aren't
1547         /// given the associated signatures here we cannot relay the node announcement to any of our
1548         /// peers.
1549         pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1550                 self.update_node_from_announcement_intern(msg, None)
1551         }
1552
1553         fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1554                 let mut nodes = self.nodes.write().unwrap();
1555                 match nodes.get_mut(&msg.node_id) {
1556                         None => {
1557                                 core::mem::drop(nodes);
1558                                 self.pending_checks.check_hold_pending_node_announcement(msg, full_msg)?;
1559                                 Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError})
1560                         },
1561                         Some(node) => {
1562                                 if let Some(node_info) = node.announcement_info.as_ref() {
1563                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
1564                                         // updates to ensure you always have the latest one, only vaguely suggesting
1565                                         // that it be at least the current time.
1566                                         if node_info.last_update  > msg.timestamp {
1567                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1568                                         } else if node_info.last_update  == msg.timestamp {
1569                                                 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1570                                         }
1571                                 }
1572
1573                                 let should_relay =
1574                                         msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1575                                         msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1576                                         msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1577                                 node.announcement_info = Some(NodeAnnouncementInfo {
1578                                         features: msg.features.clone(),
1579                                         last_update: msg.timestamp,
1580                                         rgb: msg.rgb,
1581                                         alias: msg.alias,
1582                                         announcement_message: if should_relay { full_msg.cloned() } else { None },
1583                                 });
1584
1585                                 Ok(())
1586                         }
1587                 }
1588         }
1589
1590         /// Store or update channel info from a channel announcement.
1591         ///
1592         /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1593         /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1594         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1595         ///
1596         /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1597         /// the corresponding UTXO exists on chain and is correctly-formatted.
1598         pub fn update_channel_from_announcement<U: Deref>(
1599                 &self, msg: &msgs::ChannelAnnouncement, utxo_lookup: &Option<U>,
1600         ) -> Result<(), LightningError>
1601         where
1602                 U::Target: UtxoLookup,
1603         {
1604                 verify_channel_announcement(msg, &self.secp_ctx)?;
1605                 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), utxo_lookup)
1606         }
1607
1608         /// Store or update channel info from a channel announcement.
1609         ///
1610         /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1611         /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1612         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1613         ///
1614         /// This will skip verification of if the channel is actually on-chain.
1615         pub fn update_channel_from_announcement_no_lookup(
1616                 &self, msg: &ChannelAnnouncement
1617         ) -> Result<(), LightningError> {
1618                 self.update_channel_from_announcement::<&UtxoResolver>(msg, &None)
1619         }
1620
1621         /// Store or update channel info from a channel announcement without verifying the associated
1622         /// signatures. Because we aren't given the associated signatures here we cannot relay the
1623         /// channel announcement to any of our peers.
1624         ///
1625         /// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify
1626         /// the corresponding UTXO exists on chain and is correctly-formatted.
1627         pub fn update_channel_from_unsigned_announcement<U: Deref>(
1628                 &self, msg: &msgs::UnsignedChannelAnnouncement, utxo_lookup: &Option<U>
1629         ) -> Result<(), LightningError>
1630         where
1631                 U::Target: UtxoLookup,
1632         {
1633                 self.update_channel_from_unsigned_announcement_intern(msg, None, utxo_lookup)
1634         }
1635
1636         /// Update channel from partial announcement data received via rapid gossip sync
1637         ///
1638         /// `timestamp: u64`: Timestamp emulating the backdated original announcement receipt (by the
1639         /// rapid gossip sync server)
1640         ///
1641         /// All other parameters as used in [`msgs::UnsignedChannelAnnouncement`] fields.
1642         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> {
1643                 if node_id_1 == node_id_2 {
1644                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1645                 };
1646
1647                 let node_1 = NodeId::from_pubkey(&node_id_1);
1648                 let node_2 = NodeId::from_pubkey(&node_id_2);
1649                 let channel_info = ChannelInfo {
1650                         features,
1651                         node_one: node_1.clone(),
1652                         one_to_two: None,
1653                         node_two: node_2.clone(),
1654                         two_to_one: None,
1655                         capacity_sats: None,
1656                         announcement_message: None,
1657                         announcement_received_time: timestamp,
1658                         node_one_counter: u32::max_value(),
1659                         node_two_counter: u32::max_value(),
1660                 };
1661
1662                 self.add_channel_between_nodes(short_channel_id, channel_info, None)
1663         }
1664
1665         fn add_channel_between_nodes(&self, short_channel_id: u64, channel_info: ChannelInfo, utxo_value: Option<u64>) -> Result<(), LightningError> {
1666                 let mut channels = self.channels.write().unwrap();
1667                 let mut nodes = self.nodes.write().unwrap();
1668
1669                 let node_id_a = channel_info.node_one.clone();
1670                 let node_id_b = channel_info.node_two.clone();
1671
1672                 log_gossip!(self.logger, "Adding channel {} between nodes {} and {}", short_channel_id, node_id_a, node_id_b);
1673
1674                 let channel_entry = channels.entry(short_channel_id);
1675                 let channel_info = match channel_entry {
1676                         IndexedMapEntry::Occupied(mut entry) => {
1677                                 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1678                                 //in the blockchain API, we need to handle it smartly here, though it's unclear
1679                                 //exactly how...
1680                                 if utxo_value.is_some() {
1681                                         // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1682                                         // only sometimes returns results. In any case remove the previous entry. Note
1683                                         // that the spec expects us to "blacklist" the node_ids involved, but we can't
1684                                         // do that because
1685                                         // a) we don't *require* a UTXO provider that always returns results.
1686                                         // b) we don't track UTXOs of channels we know about and remove them if they
1687                                         //    get reorg'd out.
1688                                         // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1689                                         self.remove_channel_in_nodes(&mut nodes, &entry.get(), short_channel_id);
1690                                         *entry.get_mut() = channel_info;
1691                                         entry.into_mut()
1692                                 } else {
1693                                         return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1694                                 }
1695                         },
1696                         IndexedMapEntry::Vacant(entry) => {
1697                                 entry.insert(channel_info)
1698                         }
1699                 };
1700
1701                 let mut node_counter_id = [
1702                         (&mut channel_info.node_one_counter, node_id_a),
1703                         (&mut channel_info.node_two_counter, node_id_b)
1704                 ];
1705                 for (node_counter, current_node_id) in node_counter_id.iter_mut() {
1706                         match nodes.entry(current_node_id.clone()) {
1707                                 IndexedMapEntry::Occupied(node_entry) => {
1708                                         let node = node_entry.into_mut();
1709                                         node.channels.push(short_channel_id);
1710                                         **node_counter = node.node_counter;
1711                                 },
1712                                 IndexedMapEntry::Vacant(node_entry) => {
1713                                         let mut removed_node_counters = self.removed_node_counters.lock().unwrap();
1714                                         **node_counter = removed_node_counters.pop()
1715                                                 .unwrap_or(self.next_node_counter.fetch_add(1, Ordering::Relaxed) as u32);
1716                                         node_entry.insert(NodeInfo {
1717                                                 channels: vec!(short_channel_id),
1718                                                 announcement_info: None,
1719                                                 node_counter: **node_counter,
1720                                         });
1721                                 }
1722                         };
1723                 };
1724
1725                 Ok(())
1726         }
1727
1728         fn update_channel_from_unsigned_announcement_intern<U: Deref>(
1729                 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, utxo_lookup: &Option<U>
1730         ) -> Result<(), LightningError>
1731         where
1732                 U::Target: UtxoLookup,
1733         {
1734                 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1735                         return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1736                 }
1737
1738                 if msg.chain_hash != self.chain_hash {
1739                         return Err(LightningError {
1740                                 err: "Channel announcement chain hash does not match genesis hash".to_owned(),
1741                                 action: ErrorAction::IgnoreAndLog(Level::Debug),
1742                         });
1743                 }
1744
1745                 {
1746                         let channels = self.channels.read().unwrap();
1747
1748                         if let Some(chan) = channels.get(&msg.short_channel_id) {
1749                                 if chan.capacity_sats.is_some() {
1750                                         // If we'd previously looked up the channel on-chain and checked the script
1751                                         // against what appears on-chain, ignore the duplicate announcement.
1752                                         //
1753                                         // Because a reorg could replace one channel with another at the same SCID, if
1754                                         // the channel appears to be different, we re-validate. This doesn't expose us
1755                                         // to any more DoS risk than not, as a peer can always flood us with
1756                                         // randomly-generated SCID values anyway.
1757                                         //
1758                                         // We use the Node IDs rather than the bitcoin_keys to check for "equivalence"
1759                                         // as we didn't (necessarily) store the bitcoin keys, and we only really care
1760                                         // if the peers on the channel changed anyway.
1761                                         if msg.node_id_1 == chan.node_one && msg.node_id_2 == chan.node_two {
1762                                                 return Err(LightningError {
1763                                                         err: "Already have chain-validated channel".to_owned(),
1764                                                         action: ErrorAction::IgnoreDuplicateGossip
1765                                                 });
1766                                         }
1767                                 } else if utxo_lookup.is_none() {
1768                                         // Similarly, if we can't check the chain right now anyway, ignore the
1769                                         // duplicate announcement without bothering to take the channels write lock.
1770                                         return Err(LightningError {
1771                                                 err: "Already have non-chain-validated channel".to_owned(),
1772                                                 action: ErrorAction::IgnoreDuplicateGossip
1773                                         });
1774                                 }
1775                         }
1776                 }
1777
1778                 {
1779                         let removed_channels = self.removed_channels.lock().unwrap();
1780                         let removed_nodes = self.removed_nodes.lock().unwrap();
1781                         if removed_channels.contains_key(&msg.short_channel_id) ||
1782                                 removed_nodes.contains_key(&msg.node_id_1) ||
1783                                 removed_nodes.contains_key(&msg.node_id_2) {
1784                                 return Err(LightningError{
1785                                         err: format!("Channel with SCID {} or one of its nodes was removed from our network graph recently", &msg.short_channel_id),
1786                                         action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1787                         }
1788                 }
1789
1790                 let utxo_value = self.pending_checks.check_channel_announcement(
1791                         utxo_lookup, msg, full_msg)?;
1792
1793                 #[allow(unused_mut, unused_assignments)]
1794                 let mut announcement_received_time = 0;
1795                 #[cfg(feature = "std")]
1796                 {
1797                         announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1798                 }
1799
1800                 let chan_info = ChannelInfo {
1801                         features: msg.features.clone(),
1802                         node_one: msg.node_id_1,
1803                         one_to_two: None,
1804                         node_two: msg.node_id_2,
1805                         two_to_one: None,
1806                         capacity_sats: utxo_value,
1807                         announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1808                                 { full_msg.cloned() } else { None },
1809                         announcement_received_time,
1810                         node_one_counter: u32::max_value(),
1811                         node_two_counter: u32::max_value(),
1812                 };
1813
1814                 self.add_channel_between_nodes(msg.short_channel_id, chan_info, utxo_value)?;
1815
1816                 log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.short_channel_id, if !msg.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
1817                 Ok(())
1818         }
1819
1820         /// Marks a channel in the graph as failed permanently.
1821         ///
1822         /// The channel and any node for which this was their last channel are removed from the graph.
1823         pub fn channel_failed_permanent(&self, short_channel_id: u64) {
1824                 #[cfg(feature = "std")]
1825                 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1826                 #[cfg(not(feature = "std"))]
1827                 let current_time_unix = None;
1828
1829                 self.channel_failed_permanent_with_time(short_channel_id, current_time_unix)
1830         }
1831
1832         /// Marks a channel in the graph as failed permanently.
1833         ///
1834         /// The channel and any node for which this was their last channel are removed from the graph.
1835         fn channel_failed_permanent_with_time(&self, short_channel_id: u64, current_time_unix: Option<u64>) {
1836                 let mut channels = self.channels.write().unwrap();
1837                 if let Some(chan) = channels.remove(&short_channel_id) {
1838                         let mut nodes = self.nodes.write().unwrap();
1839                         self.removed_channels.lock().unwrap().insert(short_channel_id, current_time_unix);
1840                         self.remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1841                 }
1842         }
1843
1844         /// Marks a node in the graph as permanently failed, effectively removing it and its channels
1845         /// from local storage.
1846         pub fn node_failed_permanent(&self, node_id: &PublicKey) {
1847                 #[cfg(feature = "std")]
1848                 let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
1849                 #[cfg(not(feature = "std"))]
1850                 let current_time_unix = None;
1851
1852                 let node_id = NodeId::from_pubkey(node_id);
1853                 let mut channels = self.channels.write().unwrap();
1854                 let mut nodes = self.nodes.write().unwrap();
1855                 let mut removed_channels = self.removed_channels.lock().unwrap();
1856                 let mut removed_nodes = self.removed_nodes.lock().unwrap();
1857
1858                 if let Some(node) = nodes.remove(&node_id) {
1859                         let mut removed_node_counters = self.removed_node_counters.lock().unwrap();
1860                         for scid in node.channels.iter() {
1861                                 if let Some(chan_info) = channels.remove(scid) {
1862                                         let other_node_id = if node_id == chan_info.node_one { chan_info.node_two } else { chan_info.node_one };
1863                                         if let IndexedMapEntry::Occupied(mut other_node_entry) = nodes.entry(other_node_id) {
1864                                                 other_node_entry.get_mut().channels.retain(|chan_id| {
1865                                                         *scid != *chan_id
1866                                                 });
1867                                                 if other_node_entry.get().channels.is_empty() {
1868                                                         removed_node_counters.push(other_node_entry.get().node_counter);
1869                                                         other_node_entry.remove_entry();
1870                                                 }
1871                                         }
1872                                         removed_channels.insert(*scid, current_time_unix);
1873                                 }
1874                         }
1875                         removed_node_counters.push(node.node_counter);
1876                         removed_nodes.insert(node_id, current_time_unix);
1877                 }
1878         }
1879
1880         #[cfg(feature = "std")]
1881         /// Removes information about channels that we haven't heard any updates about in some time.
1882         /// This can be used regularly to prune the network graph of channels that likely no longer
1883         /// exist.
1884         ///
1885         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1886         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1887         /// pruning occur for updates which are at least two weeks old, which we implement here.
1888         ///
1889         /// Note that for users of the `lightning-background-processor` crate this method may be
1890         /// automatically called regularly for you.
1891         ///
1892         /// This method will also cause us to stop tracking removed nodes and channels if they have been
1893         /// in the map for a while so that these can be resynced from gossip in the future.
1894         ///
1895         /// This method is only available with the `std` feature. See
1896         /// [`NetworkGraph::remove_stale_channels_and_tracking_with_time`] for `no-std` use.
1897         pub fn remove_stale_channels_and_tracking(&self) {
1898                 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1899                 self.remove_stale_channels_and_tracking_with_time(time);
1900         }
1901
1902         /// Removes information about channels that we haven't heard any updates about in some time.
1903         /// This can be used regularly to prune the network graph of channels that likely no longer
1904         /// exist.
1905         ///
1906         /// While there is no formal requirement that nodes regularly re-broadcast their channel
1907         /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1908         /// pruning occur for updates which are at least two weeks old, which we implement here.
1909         ///
1910         /// This method will also cause us to stop tracking removed nodes and channels if they have been
1911         /// in the map for a while so that these can be resynced from gossip in the future.
1912         ///
1913         /// This function takes the current unix time as an argument. For users with the `std` feature
1914         /// enabled, [`NetworkGraph::remove_stale_channels_and_tracking`] may be preferable.
1915         pub fn remove_stale_channels_and_tracking_with_time(&self, current_time_unix: u64) {
1916                 let mut channels = self.channels.write().unwrap();
1917                 // Time out if we haven't received an update in at least 14 days.
1918                 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1919                 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1920                 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1921                 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1922                 // time.
1923                 let mut scids_to_remove = Vec::new();
1924                 for (scid, info) in channels.unordered_iter_mut() {
1925                         if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1926                                 log_gossip!(self.logger, "Removing directional update one_to_two (0) for channel {} due to its timestamp {} being below {}",
1927                                         scid, info.one_to_two.as_ref().unwrap().last_update, min_time_unix);
1928                                 info.one_to_two = None;
1929                         }
1930                         if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1931                                 log_gossip!(self.logger, "Removing directional update two_to_one (1) for channel {} due to its timestamp {} being below {}",
1932                                         scid, info.two_to_one.as_ref().unwrap().last_update, min_time_unix);
1933                                 info.two_to_one = None;
1934                         }
1935                         if info.one_to_two.is_none() || info.two_to_one.is_none() {
1936                                 // We check the announcement_received_time here to ensure we don't drop
1937                                 // announcements that we just received and are just waiting for our peer to send a
1938                                 // channel_update for.
1939                                 let announcement_received_timestamp = info.announcement_received_time;
1940                                 if announcement_received_timestamp < min_time_unix as u64 {
1941                                         log_gossip!(self.logger, "Removing channel {} because both directional updates are missing and its announcement timestamp {} being below {}",
1942                                                 scid, announcement_received_timestamp, min_time_unix);
1943                                         scids_to_remove.push(*scid);
1944                                 }
1945                         }
1946                 }
1947                 if !scids_to_remove.is_empty() {
1948                         let mut nodes = self.nodes.write().unwrap();
1949                         for scid in scids_to_remove {
1950                                 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1951                                 self.remove_channel_in_nodes(&mut nodes, &info, scid);
1952                                 self.removed_channels.lock().unwrap().insert(scid, Some(current_time_unix));
1953                         }
1954                 }
1955
1956                 let should_keep_tracking = |time: &mut Option<u64>| {
1957                         if let Some(time) = time {
1958                                 current_time_unix.saturating_sub(*time) < REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS
1959                         } else {
1960                                 // NOTE: In the case of no-std, we won't have access to the current UNIX time at the time of removal,
1961                                 // so we'll just set the removal time here to the current UNIX time on the very next invocation
1962                                 // of this function.
1963                                 #[cfg(not(feature = "std"))]
1964                                 {
1965                                         let mut tracked_time = Some(current_time_unix);
1966                                         core::mem::swap(time, &mut tracked_time);
1967                                         return true;
1968                                 }
1969                                 #[allow(unreachable_code)]
1970                                 false
1971                         }};
1972
1973                 self.removed_channels.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1974                 self.removed_nodes.lock().unwrap().retain(|_, time| should_keep_tracking(time));
1975         }
1976
1977         /// For an already known (from announcement) channel, update info about one of the directions
1978         /// of the channel.
1979         ///
1980         /// You probably don't want to call this directly, instead relying on a [`P2PGossipSync`]'s
1981         /// [`RoutingMessageHandler`] implementation to call it indirectly. This may be useful to accept
1982         /// routing messages from a source using a protocol other than the lightning P2P protocol.
1983         ///
1984         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1985         /// materially in the future will be rejected.
1986         pub fn update_channel(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
1987                 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), false)
1988         }
1989
1990         /// For an already known (from announcement) channel, update info about one of the directions
1991         /// of the channel without verifying the associated signatures. Because we aren't given the
1992         /// associated signatures here we cannot relay the channel update to any of our peers.
1993         ///
1994         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1995         /// materially in the future will be rejected.
1996         pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1997                 self.update_channel_internal(msg, None, None, false)
1998         }
1999
2000         /// For an already known (from announcement) channel, verify the given [`ChannelUpdate`].
2001         ///
2002         /// This checks whether the update currently is applicable by [`Self::update_channel`].
2003         ///
2004         /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
2005         /// materially in the future will be rejected.
2006         pub fn verify_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), LightningError> {
2007                 self.update_channel_internal(&msg.contents, Some(&msg), Some(&msg.signature), true)
2008         }
2009
2010         fn update_channel_internal(&self, msg: &msgs::UnsignedChannelUpdate,
2011                 full_msg: Option<&msgs::ChannelUpdate>, sig: Option<&secp256k1::ecdsa::Signature>,
2012                 only_verify: bool) -> Result<(), LightningError>
2013         {
2014                 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
2015
2016                 if msg.chain_hash != self.chain_hash {
2017                         return Err(LightningError {
2018                                 err: "Channel update chain hash does not match genesis hash".to_owned(),
2019                                 action: ErrorAction::IgnoreAndLog(Level::Debug),
2020                         });
2021                 }
2022
2023                 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
2024                 {
2025                         // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
2026                         // disable this check during tests!
2027                         let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2028                         if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
2029                                 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
2030                         }
2031                         if msg.timestamp as u64 > time + 60 * 60 * 24 {
2032                                 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
2033                         }
2034                 }
2035
2036                 log_gossip!(self.logger, "Updating channel {} in direction {} with timestamp {}", msg.short_channel_id, msg.flags & 1, msg.timestamp);
2037
2038                 let mut channels = self.channels.write().unwrap();
2039                 match channels.get_mut(&msg.short_channel_id) {
2040                         None => {
2041                                 core::mem::drop(channels);
2042                                 self.pending_checks.check_hold_pending_channel_update(msg, full_msg)?;
2043                                 return Err(LightningError {
2044                                         err: "Couldn't find channel for update".to_owned(),
2045                                         action: ErrorAction::IgnoreAndLog(Level::Gossip),
2046                                 });
2047                         },
2048                         Some(channel) => {
2049                                 if msg.htlc_maximum_msat > MAX_VALUE_MSAT {
2050                                         return Err(LightningError{err:
2051                                                 "htlc_maximum_msat is larger than maximum possible msats".to_owned(),
2052                                                 action: ErrorAction::IgnoreError});
2053                                 }
2054
2055                                 if let Some(capacity_sats) = channel.capacity_sats {
2056                                         // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
2057                                         // Don't query UTXO set here to reduce DoS risks.
2058                                         if capacity_sats > MAX_VALUE_MSAT / 1000 || msg.htlc_maximum_msat > capacity_sats * 1000 {
2059                                                 return Err(LightningError{err:
2060                                                         "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(),
2061                                                         action: ErrorAction::IgnoreError});
2062                                         }
2063                                 }
2064                                 macro_rules! check_update_latest {
2065                                         ($target: expr) => {
2066                                                 if let Some(existing_chan_info) = $target.as_ref() {
2067                                                         // The timestamp field is somewhat of a misnomer - the BOLTs use it to
2068                                                         // order updates to ensure you always have the latest one, only
2069                                                         // suggesting  that it be at least the current time. For
2070                                                         // channel_updates specifically, the BOLTs discuss the possibility of
2071                                                         // pruning based on the timestamp field being more than two weeks old,
2072                                                         // but only in the non-normative section.
2073                                                         if existing_chan_info.last_update > msg.timestamp {
2074                                                                 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2075                                                         } else if existing_chan_info.last_update == msg.timestamp {
2076                                                                 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
2077                                                         }
2078                                                 }
2079                                         }
2080                                 }
2081
2082                                 macro_rules! get_new_channel_info {
2083                                         () => { {
2084                                                 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
2085                                                         { full_msg.cloned() } else { None };
2086
2087                                                 let updated_channel_update_info = ChannelUpdateInfo {
2088                                                         enabled: chan_enabled,
2089                                                         last_update: msg.timestamp,
2090                                                         cltv_expiry_delta: msg.cltv_expiry_delta,
2091                                                         htlc_minimum_msat: msg.htlc_minimum_msat,
2092                                                         htlc_maximum_msat: msg.htlc_maximum_msat,
2093                                                         fees: RoutingFees {
2094                                                                 base_msat: msg.fee_base_msat,
2095                                                                 proportional_millionths: msg.fee_proportional_millionths,
2096                                                         },
2097                                                         last_update_message
2098                                                 };
2099                                                 Some(updated_channel_update_info)
2100                                         } }
2101                                 }
2102
2103                                 let msg_hash = hash_to_message!(&message_sha256d_hash(&msg)[..]);
2104                                 if msg.flags & 1 == 1 {
2105                                         check_update_latest!(channel.two_to_one);
2106                                         if let Some(sig) = sig {
2107                                                 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
2108                                                         err: "Couldn't parse source node pubkey".to_owned(),
2109                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
2110                                                 })?, "channel_update");
2111                                         }
2112                                         if !only_verify {
2113                                                 channel.two_to_one = get_new_channel_info!();
2114                                         }
2115                                 } else {
2116                                         check_update_latest!(channel.one_to_two);
2117                                         if let Some(sig) = sig {
2118                                                 secp_verify_sig!(self.secp_ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
2119                                                         err: "Couldn't parse destination node pubkey".to_owned(),
2120                                                         action: ErrorAction::IgnoreAndLog(Level::Debug)
2121                                                 })?, "channel_update");
2122                                         }
2123                                         if !only_verify {
2124                                                 channel.one_to_two = get_new_channel_info!();
2125                                         }
2126                                 }
2127                         }
2128                 }
2129
2130                 Ok(())
2131         }
2132
2133         fn remove_channel_in_nodes(&self, nodes: &mut IndexedMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
2134                 macro_rules! remove_from_node {
2135                         ($node_id: expr) => {
2136                                 if let IndexedMapEntry::Occupied(mut entry) = nodes.entry($node_id) {
2137                                         entry.get_mut().channels.retain(|chan_id| {
2138                                                 short_channel_id != *chan_id
2139                                         });
2140                                         if entry.get().channels.is_empty() {
2141                                                 self.removed_node_counters.lock().unwrap().push(entry.get().node_counter);
2142                                                 entry.remove_entry();
2143                                         }
2144                                 } else {
2145                                         panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
2146                                 }
2147                         }
2148                 }
2149
2150                 remove_from_node!(chan.node_one);
2151                 remove_from_node!(chan.node_two);
2152         }
2153 }
2154
2155 impl ReadOnlyNetworkGraph<'_> {
2156         /// Returns all known valid channels' short ids along with announced channel info.
2157         ///
2158         /// This is not exported to bindings users because we don't want to return lifetime'd references
2159         pub fn channels(&self) -> &IndexedMap<u64, ChannelInfo> {
2160                 &*self.channels
2161         }
2162
2163         /// Returns information on a channel with the given id.
2164         pub fn channel(&self, short_channel_id: u64) -> Option<&ChannelInfo> {
2165                 self.channels.get(&short_channel_id)
2166         }
2167
2168         #[cfg(c_bindings)] // Non-bindings users should use `channels`
2169         /// Returns the list of channels in the graph
2170         pub fn list_channels(&self) -> Vec<u64> {
2171                 self.channels.unordered_keys().map(|c| *c).collect()
2172         }
2173
2174         /// Returns all known nodes' public keys along with announced node info.
2175         ///
2176         /// This is not exported to bindings users because we don't want to return lifetime'd references
2177         pub fn nodes(&self) -> &IndexedMap<NodeId, NodeInfo> {
2178                 &*self.nodes
2179         }
2180
2181         /// Returns information on a node with the given id.
2182         pub fn node(&self, node_id: &NodeId) -> Option<&NodeInfo> {
2183                 self.nodes.get(node_id)
2184         }
2185
2186         #[cfg(c_bindings)] // Non-bindings users should use `nodes`
2187         /// Returns the list of nodes in the graph
2188         pub fn list_nodes(&self) -> Vec<NodeId> {
2189                 self.nodes.unordered_keys().map(|n| *n).collect()
2190         }
2191
2192         /// Get network addresses by node id.
2193         /// Returns None if the requested node is completely unknown,
2194         /// or if node announcement for the node was never received.
2195         pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<SocketAddress>> {
2196                 self.nodes.get(&NodeId::from_pubkey(&pubkey))
2197                         .and_then(|node| node.announcement_info.as_ref().map(|ann| ann.addresses().to_vec()))
2198         }
2199
2200         /// Gets the maximum possible node_counter for a node in this graph
2201         pub(crate) fn max_node_counter(&self) -> u32 {
2202                 self.max_node_counter
2203         }
2204 }
2205
2206 #[cfg(test)]
2207 pub(crate) mod tests {
2208         use crate::events::{MessageSendEvent, MessageSendEventsProvider};
2209         use crate::ln::channelmanager;
2210         use crate::ln::chan_utils::make_funding_redeemscript;
2211         #[cfg(feature = "std")]
2212         use crate::ln::features::InitFeatures;
2213         use crate::ln::msgs::SocketAddress;
2214         use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate, NodeAlias, MAX_EXCESS_BYTES_FOR_RELAY, NodeId, RoutingFees, ChannelUpdateInfo, ChannelInfo, NodeAnnouncementInfo, NodeInfo};
2215         use crate::routing::utxo::{UtxoLookupError, UtxoResult};
2216         use crate::ln::msgs::{RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
2217                 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
2218                 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
2219         use crate::util::config::UserConfig;
2220         use crate::util::test_utils;
2221         use crate::util::ser::{Hostname, ReadableArgs, Readable, Writeable};
2222         use crate::util::scid_utils::scid_from_parts;
2223
2224         use crate::routing::gossip::REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS;
2225         use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
2226
2227         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
2228         use bitcoin::hashes::Hash;
2229         use bitcoin::hashes::hex::FromHex;
2230         use bitcoin::network::constants::Network;
2231         use bitcoin::blockdata::constants::ChainHash;
2232         use bitcoin::blockdata::script::ScriptBuf;
2233         use bitcoin::blockdata::transaction::TxOut;
2234         use bitcoin::secp256k1::{PublicKey, SecretKey};
2235         use bitcoin::secp256k1::{All, Secp256k1};
2236
2237         use crate::io;
2238         use bitcoin::secp256k1;
2239         use crate::prelude::*;
2240         use crate::sync::Arc;
2241
2242         fn create_network_graph() -> NetworkGraph<Arc<test_utils::TestLogger>> {
2243                 let logger = Arc::new(test_utils::TestLogger::new());
2244                 NetworkGraph::new(Network::Testnet, logger)
2245         }
2246
2247         fn create_gossip_sync(network_graph: &NetworkGraph<Arc<test_utils::TestLogger>>) -> (
2248                 Secp256k1<All>, P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>,
2249                 Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
2250         ) {
2251                 let secp_ctx = Secp256k1::new();
2252                 let logger = Arc::new(test_utils::TestLogger::new());
2253                 let gossip_sync = P2PGossipSync::new(network_graph, None, Arc::clone(&logger));
2254                 (secp_ctx, gossip_sync)
2255         }
2256
2257         #[test]
2258         #[cfg(feature = "std")]
2259         fn request_full_sync_finite_times() {
2260                 let network_graph = create_network_graph();
2261                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2262                 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&<Vec<u8>>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
2263
2264                 assert!(gossip_sync.should_request_full_sync(&node_id));
2265                 assert!(gossip_sync.should_request_full_sync(&node_id));
2266                 assert!(gossip_sync.should_request_full_sync(&node_id));
2267                 assert!(gossip_sync.should_request_full_sync(&node_id));
2268                 assert!(gossip_sync.should_request_full_sync(&node_id));
2269                 assert!(!gossip_sync.should_request_full_sync(&node_id));
2270         }
2271
2272         pub(crate) fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
2273                 let node_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_key));
2274                 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2275                         features: channelmanager::provided_node_features(&UserConfig::default()),
2276                         timestamp: 100,
2277                         node_id,
2278                         rgb: [0; 3],
2279                         alias: NodeAlias([0; 32]),
2280                         addresses: Vec::new(),
2281                         excess_address_data: Vec::new(),
2282                         excess_data: Vec::new(),
2283                 };
2284                 f(&mut unsigned_announcement);
2285                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2286                 NodeAnnouncement {
2287                         signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2288                         contents: unsigned_announcement
2289                 }
2290         }
2291
2292         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 {
2293                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
2294                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
2295                 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2296                 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2297
2298                 let mut unsigned_announcement = UnsignedChannelAnnouncement {
2299                         features: channelmanager::provided_channel_features(&UserConfig::default()),
2300                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2301                         short_channel_id: 0,
2302                         node_id_1: NodeId::from_pubkey(&node_id_1),
2303                         node_id_2: NodeId::from_pubkey(&node_id_2),
2304                         bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey)),
2305                         bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey)),
2306                         excess_data: Vec::new(),
2307                 };
2308                 f(&mut unsigned_announcement);
2309                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2310                 ChannelAnnouncement {
2311                         node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_key),
2312                         node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_key),
2313                         bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_btckey),
2314                         bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_btckey),
2315                         contents: unsigned_announcement,
2316                 }
2317         }
2318
2319         pub(crate) fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> ScriptBuf {
2320                 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
2321                 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
2322                 make_funding_redeemscript(&PublicKey::from_secret_key(secp_ctx, &node_1_btckey),
2323                         &PublicKey::from_secret_key(secp_ctx, &node_2_btckey)).to_v0_p2wsh()
2324         }
2325
2326         pub(crate) fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
2327                 let mut unsigned_channel_update = UnsignedChannelUpdate {
2328                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
2329                         short_channel_id: 0,
2330                         timestamp: 100,
2331                         flags: 0,
2332                         cltv_expiry_delta: 144,
2333                         htlc_minimum_msat: 1_000_000,
2334                         htlc_maximum_msat: 1_000_000,
2335                         fee_base_msat: 10_000,
2336                         fee_proportional_millionths: 20,
2337                         excess_data: Vec::new()
2338                 };
2339                 f(&mut unsigned_channel_update);
2340                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2341                 ChannelUpdate {
2342                         signature: secp_ctx.sign_ecdsa(&msghash, node_key),
2343                         contents: unsigned_channel_update
2344                 }
2345         }
2346
2347         #[test]
2348         fn handling_node_announcements() {
2349                 let network_graph = create_network_graph();
2350                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2351
2352                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2353                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2354                 let zero_hash = Sha256dHash::hash(&[0; 32]);
2355
2356                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2357                 match gossip_sync.handle_node_announcement(&valid_announcement) {
2358                         Ok(_) => panic!(),
2359                         Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
2360                 };
2361
2362                 {
2363                         // Announce a channel to add a corresponding node.
2364                         let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2365                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
2366                                 Ok(res) => assert!(res),
2367                                 _ => panic!()
2368                         };
2369                 }
2370
2371                 match gossip_sync.handle_node_announcement(&valid_announcement) {
2372                         Ok(res) => assert!(res),
2373                         Err(_) => panic!()
2374                 };
2375
2376                 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2377                 match gossip_sync.handle_node_announcement(
2378                         &NodeAnnouncement {
2379                                 signature: secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey),
2380                                 contents: valid_announcement.contents.clone()
2381                 }) {
2382                         Ok(_) => panic!(),
2383                         Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
2384                 };
2385
2386                 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
2387                         unsigned_announcement.timestamp += 1000;
2388                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2389                 }, node_1_privkey, &secp_ctx);
2390                 // Return false because contains excess data.
2391                 match gossip_sync.handle_node_announcement(&announcement_with_data) {
2392                         Ok(res) => assert!(!res),
2393                         Err(_) => panic!()
2394                 };
2395
2396                 // Even though previous announcement was not relayed further, we still accepted it,
2397                 // so we now won't accept announcements before the previous one.
2398                 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
2399                         unsigned_announcement.timestamp += 1000 - 10;
2400                 }, node_1_privkey, &secp_ctx);
2401                 match gossip_sync.handle_node_announcement(&outdated_announcement) {
2402                         Ok(_) => panic!(),
2403                         Err(e) => assert_eq!(e.err, "Update older than last processed update")
2404                 };
2405         }
2406
2407         #[test]
2408         fn handling_channel_announcements() {
2409                 let secp_ctx = Secp256k1::new();
2410                 let logger = test_utils::TestLogger::new();
2411
2412                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2413                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2414
2415                 let good_script = get_channel_script(&secp_ctx);
2416                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2417
2418                 // Test if the UTXO lookups were not supported
2419                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2420                 let mut gossip_sync = P2PGossipSync::new(&network_graph, None, &logger);
2421                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2422                         Ok(res) => assert!(res),
2423                         _ => panic!()
2424                 };
2425
2426                 {
2427                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2428                                 None => panic!(),
2429                                 Some(_) => ()
2430                         };
2431                 }
2432
2433                 // If we receive announcement for the same channel (with UTXO lookups disabled),
2434                 // drop new one on the floor, since we can't see any changes.
2435                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2436                         Ok(_) => panic!(),
2437                         Err(e) => assert_eq!(e.err, "Already have non-chain-validated channel")
2438                 };
2439
2440                 // Test if an associated transaction were not on-chain (or not confirmed).
2441                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2442                 *chain_source.utxo_ret.lock().unwrap() = UtxoResult::Sync(Err(UtxoLookupError::UnknownTx));
2443                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2444                 gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2445
2446                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2447                         unsigned_announcement.short_channel_id += 1;
2448                 }, node_1_privkey, node_2_privkey, &secp_ctx);
2449                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2450                         Ok(_) => panic!(),
2451                         Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2452                 };
2453
2454                 // Now test if the transaction is found in the UTXO set and the script is correct.
2455                 *chain_source.utxo_ret.lock().unwrap() =
2456                         UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script.clone() }));
2457                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2458                         unsigned_announcement.short_channel_id += 2;
2459                 }, node_1_privkey, node_2_privkey, &secp_ctx);
2460                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2461                         Ok(res) => assert!(res),
2462                         _ => panic!()
2463                 };
2464
2465                 {
2466                         match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
2467                                 None => panic!(),
2468                                 Some(_) => ()
2469                         };
2470                 }
2471
2472                 // If we receive announcement for the same channel, once we've validated it against the
2473                 // chain, we simply ignore all new (duplicate) announcements.
2474                 *chain_source.utxo_ret.lock().unwrap() =
2475                         UtxoResult::Sync(Ok(TxOut { value: 0, script_pubkey: good_script }));
2476                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2477                         Ok(_) => panic!(),
2478                         Err(e) => assert_eq!(e.err, "Already have chain-validated channel")
2479                 };
2480
2481                 #[cfg(feature = "std")]
2482                 {
2483                         use std::time::{SystemTime, UNIX_EPOCH};
2484
2485                         let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2486                         // Mark a node as permanently failed so it's tracked as removed.
2487                         gossip_sync.network_graph().node_failed_permanent(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2488
2489                         // Return error and ignore valid channel announcement if one of the nodes has been tracked as removed.
2490                         let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2491                                 unsigned_announcement.short_channel_id += 3;
2492                         }, node_1_privkey, node_2_privkey, &secp_ctx);
2493                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
2494                                 Ok(_) => panic!(),
2495                                 Err(e) => assert_eq!(e.err, "Channel with SCID 3 or one of its nodes was removed from our network graph recently")
2496                         }
2497
2498                         gossip_sync.network_graph().remove_stale_channels_and_tracking_with_time(tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2499
2500                         // The above channel announcement should be handled as per normal now.
2501                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
2502                                 Ok(res) => assert!(res),
2503                                 _ => panic!()
2504                         }
2505                 }
2506
2507                 // Don't relay valid channels with excess data
2508                 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2509                         unsigned_announcement.short_channel_id += 4;
2510                         unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2511                 }, node_1_privkey, node_2_privkey, &secp_ctx);
2512                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
2513                         Ok(res) => assert!(!res),
2514                         _ => panic!()
2515                 };
2516
2517                 let mut invalid_sig_announcement = valid_announcement.clone();
2518                 invalid_sig_announcement.contents.excess_data = Vec::new();
2519                 match gossip_sync.handle_channel_announcement(&invalid_sig_announcement) {
2520                         Ok(_) => panic!(),
2521                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
2522                 };
2523
2524                 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
2525                 match gossip_sync.handle_channel_announcement(&channel_to_itself_announcement) {
2526                         Ok(_) => panic!(),
2527                         Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2528                 };
2529
2530                 // Test that channel announcements with the wrong chain hash are ignored (network graph is testnet,
2531                 // announcement is mainnet).
2532                 let incorrect_chain_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2533                         unsigned_announcement.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2534                 }, node_1_privkey, node_2_privkey, &secp_ctx);
2535                 match gossip_sync.handle_channel_announcement(&incorrect_chain_announcement) {
2536                         Ok(_) => panic!(),
2537                         Err(e) => assert_eq!(e.err, "Channel announcement chain hash does not match genesis hash")
2538                 };
2539         }
2540
2541         #[test]
2542         fn handling_channel_update() {
2543                 let secp_ctx = Secp256k1::new();
2544                 let logger = test_utils::TestLogger::new();
2545                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2546                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2547                 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2548
2549                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2550                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2551
2552                 let amount_sats = 1000_000;
2553                 let short_channel_id;
2554
2555                 {
2556                         // Announce a channel we will update
2557                         let good_script = get_channel_script(&secp_ctx);
2558                         *chain_source.utxo_ret.lock().unwrap() =
2559                                 UtxoResult::Sync(Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() }));
2560
2561                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2562                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2563                         match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2564                                 Ok(_) => (),
2565                                 Err(_) => panic!()
2566                         };
2567
2568                 }
2569
2570                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2571                 network_graph.verify_channel_update(&valid_channel_update).unwrap();
2572                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2573                         Ok(res) => assert!(res),
2574                         _ => panic!(),
2575                 };
2576
2577                 {
2578                         match network_graph.read_only().channels().get(&short_channel_id) {
2579                                 None => panic!(),
2580                                 Some(channel_info) => {
2581                                         assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
2582                                         assert!(channel_info.two_to_one.is_none());
2583                                 }
2584                         };
2585                 }
2586
2587                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2588                         unsigned_channel_update.timestamp += 100;
2589                         unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
2590                 }, node_1_privkey, &secp_ctx);
2591                 // Return false because contains excess data
2592                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2593                         Ok(res) => assert!(!res),
2594                         _ => panic!()
2595                 };
2596
2597                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2598                         unsigned_channel_update.timestamp += 110;
2599                         unsigned_channel_update.short_channel_id += 1;
2600                 }, node_1_privkey, &secp_ctx);
2601                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2602                         Ok(_) => panic!(),
2603                         Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2604                 };
2605
2606                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2607                         unsigned_channel_update.htlc_maximum_msat = MAX_VALUE_MSAT + 1;
2608                         unsigned_channel_update.timestamp += 110;
2609                 }, node_1_privkey, &secp_ctx);
2610                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2611                         Ok(_) => panic!(),
2612                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
2613                 };
2614
2615                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2616                         unsigned_channel_update.htlc_maximum_msat = amount_sats * 1000 + 1;
2617                         unsigned_channel_update.timestamp += 110;
2618                 }, node_1_privkey, &secp_ctx);
2619                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2620                         Ok(_) => panic!(),
2621                         Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
2622                 };
2623
2624                 // Even though previous update was not relayed further, we still accepted it,
2625                 // so we now won't accept update before the previous one.
2626                 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2627                         unsigned_channel_update.timestamp += 100;
2628                 }, node_1_privkey, &secp_ctx);
2629                 match gossip_sync.handle_channel_update(&valid_channel_update) {
2630                         Ok(_) => panic!(),
2631                         Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
2632                 };
2633
2634                 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2635                         unsigned_channel_update.timestamp += 500;
2636                 }, node_1_privkey, &secp_ctx);
2637                 let zero_hash = Sha256dHash::hash(&[0; 32]);
2638                 let fake_msghash = hash_to_message!(zero_hash.as_byte_array());
2639                 invalid_sig_channel_update.signature = secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey);
2640                 match gossip_sync.handle_channel_update(&invalid_sig_channel_update) {
2641                         Ok(_) => panic!(),
2642                         Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
2643                 };
2644
2645                 // Test that channel updates with the wrong chain hash are ignored (network graph is testnet, channel
2646                 // update is mainet).
2647                 let incorrect_chain_update = get_signed_channel_update(|unsigned_channel_update| {
2648                         unsigned_channel_update.chain_hash = ChainHash::using_genesis_block(Network::Bitcoin);
2649                 }, node_1_privkey, &secp_ctx);
2650
2651                 match gossip_sync.handle_channel_update(&incorrect_chain_update) {
2652                         Ok(_) => panic!(),
2653                         Err(e) => assert_eq!(e.err, "Channel update chain hash does not match genesis hash")
2654                 };
2655         }
2656
2657         #[test]
2658         fn handling_network_update() {
2659                 let logger = test_utils::TestLogger::new();
2660                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2661                 let secp_ctx = Secp256k1::new();
2662
2663                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2664                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2665                 let node_2_id = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2666
2667                 {
2668                         // There is no nodes in the table at the beginning.
2669                         assert_eq!(network_graph.read_only().nodes().len(), 0);
2670                 }
2671
2672                 let short_channel_id;
2673                 {
2674                         // Check we won't apply an update via `handle_network_update` for privacy reasons, but
2675                         // can continue fine if we manually apply it.
2676                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2677                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2678                         let chain_source: Option<&test_utils::TestChainSource> = None;
2679                         assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2680                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2681
2682                         let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2683                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2684
2685                         network_graph.handle_network_update(&NetworkUpdate::ChannelUpdateMessage {
2686                                 msg: valid_channel_update.clone(),
2687                         });
2688
2689                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2690                         network_graph.update_channel(&valid_channel_update).unwrap();
2691                 }
2692
2693                 // Non-permanent failure doesn't touch the channel at all
2694                 {
2695                         match network_graph.read_only().channels().get(&short_channel_id) {
2696                                 None => panic!(),
2697                                 Some(channel_info) => {
2698                                         assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2699                                 }
2700                         };
2701
2702                         network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2703                                 short_channel_id,
2704                                 is_permanent: false,
2705                         });
2706
2707                         match network_graph.read_only().channels().get(&short_channel_id) {
2708                                 None => panic!(),
2709                                 Some(channel_info) => {
2710                                         assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2711                                 }
2712                         };
2713                 }
2714
2715                 // Permanent closing deletes a channel
2716                 network_graph.handle_network_update(&NetworkUpdate::ChannelFailure {
2717                         short_channel_id,
2718                         is_permanent: true,
2719                 });
2720
2721                 assert_eq!(network_graph.read_only().channels().len(), 0);
2722                 // Nodes are also deleted because there are no associated channels anymore
2723                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2724
2725                 {
2726                         // Get a new network graph since we don't want to track removed nodes in this test with "std"
2727                         let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2728
2729                         // Announce a channel to test permanent node failure
2730                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2731                         let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2732                         let chain_source: Option<&test_utils::TestChainSource> = None;
2733                         assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2734                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2735
2736                         // Non-permanent node failure does not delete any nodes or channels
2737                         network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2738                                 node_id: node_2_id,
2739                                 is_permanent: false,
2740                         });
2741
2742                         assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2743                         assert!(network_graph.read_only().nodes().get(&NodeId::from_pubkey(&node_2_id)).is_some());
2744
2745                         // Permanent node failure deletes node and its channels
2746                         network_graph.handle_network_update(&NetworkUpdate::NodeFailure {
2747                                 node_id: node_2_id,
2748                                 is_permanent: true,
2749                         });
2750
2751                         assert_eq!(network_graph.read_only().nodes().len(), 0);
2752                         // Channels are also deleted because the associated node has been deleted
2753                         assert_eq!(network_graph.read_only().channels().len(), 0);
2754                 }
2755         }
2756
2757         #[test]
2758         fn test_channel_timeouts() {
2759                 // Test the removal of channels with `remove_stale_channels_and_tracking`.
2760                 let logger = test_utils::TestLogger::new();
2761                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2762                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
2763                 let gossip_sync = P2PGossipSync::new(&network_graph, Some(&chain_source), &logger);
2764                 let secp_ctx = Secp256k1::new();
2765
2766                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2767                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2768
2769                 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2770                 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2771                 let chain_source: Option<&test_utils::TestChainSource> = None;
2772                 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source).is_ok());
2773                 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2774
2775                 // Submit two channel updates for each channel direction (update.flags bit).
2776                 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2777                 assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2778                 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2779
2780                 let valid_channel_update_2 = get_signed_channel_update(|update| {update.flags |=1;}, node_2_privkey, &secp_ctx);
2781                 gossip_sync.handle_channel_update(&valid_channel_update_2).unwrap();
2782                 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().two_to_one.is_some());
2783
2784                 network_graph.remove_stale_channels_and_tracking_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2785                 assert_eq!(network_graph.read_only().channels().len(), 1);
2786                 assert_eq!(network_graph.read_only().nodes().len(), 2);
2787
2788                 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2789                 #[cfg(not(feature = "std"))] {
2790                         // Make sure removed channels are tracked.
2791                         assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2792                 }
2793                 network_graph.remove_stale_channels_and_tracking_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2794                         REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2795
2796                 #[cfg(feature = "std")]
2797                 {
2798                         // In std mode, a further check is performed before fully removing the channel -
2799                         // the channel_announcement must have been received at least two weeks ago. We
2800                         // fudge that here by indicating the time has jumped two weeks.
2801                         assert_eq!(network_graph.read_only().channels().len(), 1);
2802                         assert_eq!(network_graph.read_only().nodes().len(), 2);
2803
2804                         // Note that the directional channel information will have been removed already..
2805                         // We want to check that this will work even if *one* of the channel updates is recent,
2806                         // so we should add it with a recent timestamp.
2807                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2808                         use std::time::{SystemTime, UNIX_EPOCH};
2809                         let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2810                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2811                                 unsigned_channel_update.timestamp = (announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
2812                         }, node_1_privkey, &secp_ctx);
2813                         assert!(gossip_sync.handle_channel_update(&valid_channel_update).is_ok());
2814                         assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2815                         network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2816                         // Make sure removed channels are tracked.
2817                         assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2818                         // Provide a later time so that sufficient time has passed
2819                         network_graph.remove_stale_channels_and_tracking_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS +
2820                                 REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2821                 }
2822
2823                 assert_eq!(network_graph.read_only().channels().len(), 0);
2824                 assert_eq!(network_graph.read_only().nodes().len(), 0);
2825                 assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2826
2827                 #[cfg(feature = "std")]
2828                 {
2829                         use std::time::{SystemTime, UNIX_EPOCH};
2830
2831                         let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2832
2833                         // Clear tracked nodes and channels for clean slate
2834                         network_graph.removed_channels.lock().unwrap().clear();
2835                         network_graph.removed_nodes.lock().unwrap().clear();
2836
2837                         // Add a channel and nodes from channel announcement. So our network graph will
2838                         // now only consist of two nodes and one channel between them.
2839                         assert!(network_graph.update_channel_from_announcement(
2840                                 &valid_channel_announcement, &chain_source).is_ok());
2841
2842                         // Mark the channel as permanently failed. This will also remove the two nodes
2843                         // and all of the entries will be tracked as removed.
2844                         network_graph.channel_failed_permanent_with_time(short_channel_id, Some(tracking_time));
2845
2846                         // Should not remove from tracking if insufficient time has passed
2847                         network_graph.remove_stale_channels_and_tracking_with_time(
2848                                 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS - 1);
2849                         assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1, "Removed channel count â‰  1 with tracking_time {}", tracking_time);
2850
2851                         // Provide a later time so that sufficient time has passed
2852                         network_graph.remove_stale_channels_and_tracking_with_time(
2853                                 tracking_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2854                         assert!(network_graph.removed_channels.lock().unwrap().is_empty(), "Unexpectedly removed channels with tracking_time {}", tracking_time);
2855                         assert!(network_graph.removed_nodes.lock().unwrap().is_empty(), "Unexpectedly removed nodes with tracking_time {}", tracking_time);
2856                 }
2857
2858                 #[cfg(not(feature = "std"))]
2859                 {
2860                         // When we don't have access to the system clock, the time we started tracking removal will only
2861                         // be that provided by the first call to `remove_stale_channels_and_tracking_with_time`. Hence,
2862                         // only if sufficient time has passed after that first call, will the next call remove it from
2863                         // tracking.
2864                         let removal_time = 1664619654;
2865
2866                         // Clear removed nodes and channels for clean slate
2867                         network_graph.removed_channels.lock().unwrap().clear();
2868                         network_graph.removed_nodes.lock().unwrap().clear();
2869
2870                         // Add a channel and nodes from channel announcement. So our network graph will
2871                         // now only consist of two nodes and one channel between them.
2872                         assert!(network_graph.update_channel_from_announcement(
2873                                 &valid_channel_announcement, &chain_source).is_ok());
2874
2875                         // Mark the channel as permanently failed. This will also remove the two nodes
2876                         // and all of the entries will be tracked as removed.
2877                         network_graph.channel_failed_permanent(short_channel_id);
2878
2879                         // The first time we call the following, the channel will have a removal time assigned.
2880                         network_graph.remove_stale_channels_and_tracking_with_time(removal_time);
2881                         assert_eq!(network_graph.removed_channels.lock().unwrap().len(), 1);
2882
2883                         // Provide a later time so that sufficient time has passed
2884                         network_graph.remove_stale_channels_and_tracking_with_time(
2885                                 removal_time + REMOVED_ENTRIES_TRACKING_AGE_LIMIT_SECS);
2886                         assert!(network_graph.removed_channels.lock().unwrap().is_empty());
2887                         assert!(network_graph.removed_nodes.lock().unwrap().is_empty());
2888                 }
2889         }
2890
2891         #[test]
2892         fn getting_next_channel_announcements() {
2893                 let network_graph = create_network_graph();
2894                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2895                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2896                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2897
2898                 // Channels were not announced yet.
2899                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(0);
2900                 assert!(channels_with_announcements.is_none());
2901
2902                 let short_channel_id;
2903                 {
2904                         // Announce a channel we will update
2905                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2906                         short_channel_id = valid_channel_announcement.contents.short_channel_id;
2907                         match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2908                                 Ok(_) => (),
2909                                 Err(_) => panic!()
2910                         };
2911                 }
2912
2913                 // Contains initial channel announcement now.
2914                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2915                 if let Some(channel_announcements) = channels_with_announcements {
2916                         let (_, ref update_1, ref update_2) = channel_announcements;
2917                         assert_eq!(update_1, &None);
2918                         assert_eq!(update_2, &None);
2919                 } else {
2920                         panic!();
2921                 }
2922
2923                 {
2924                         // Valid channel update
2925                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2926                                 unsigned_channel_update.timestamp = 101;
2927                         }, node_1_privkey, &secp_ctx);
2928                         match gossip_sync.handle_channel_update(&valid_channel_update) {
2929                                 Ok(_) => (),
2930                                 Err(_) => panic!()
2931                         };
2932                 }
2933
2934                 // Now contains an initial announcement and an update.
2935                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2936                 if let Some(channel_announcements) = channels_with_announcements {
2937                         let (_, ref update_1, ref update_2) = channel_announcements;
2938                         assert_ne!(update_1, &None);
2939                         assert_eq!(update_2, &None);
2940                 } else {
2941                         panic!();
2942                 }
2943
2944                 {
2945                         // Channel update with excess data.
2946                         let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2947                                 unsigned_channel_update.timestamp = 102;
2948                                 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2949                         }, node_1_privkey, &secp_ctx);
2950                         match gossip_sync.handle_channel_update(&valid_channel_update) {
2951                                 Ok(_) => (),
2952                                 Err(_) => panic!()
2953                         };
2954                 }
2955
2956                 // Test that announcements with excess data won't be returned
2957                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id);
2958                 if let Some(channel_announcements) = channels_with_announcements {
2959                         let (_, ref update_1, ref update_2) = channel_announcements;
2960                         assert_eq!(update_1, &None);
2961                         assert_eq!(update_2, &None);
2962                 } else {
2963                         panic!();
2964                 }
2965
2966                 // Further starting point have no channels after it
2967                 let channels_with_announcements = gossip_sync.get_next_channel_announcement(short_channel_id + 1000);
2968                 assert!(channels_with_announcements.is_none());
2969         }
2970
2971         #[test]
2972         fn getting_next_node_announcements() {
2973                 let network_graph = create_network_graph();
2974                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
2975                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2976                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2977                 let node_id_1 = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
2978
2979                 // No nodes yet.
2980                 let next_announcements = gossip_sync.get_next_node_announcement(None);
2981                 assert!(next_announcements.is_none());
2982
2983                 {
2984                         // Announce a channel to add 2 nodes
2985                         let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2986                         match gossip_sync.handle_channel_announcement(&valid_channel_announcement) {
2987                                 Ok(_) => (),
2988                                 Err(_) => panic!()
2989                         };
2990                 }
2991
2992                 // Nodes were never announced
2993                 let next_announcements = gossip_sync.get_next_node_announcement(None);
2994                 assert!(next_announcements.is_none());
2995
2996                 {
2997                         let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2998                         match gossip_sync.handle_node_announcement(&valid_announcement) {
2999                                 Ok(_) => (),
3000                                 Err(_) => panic!()
3001                         };
3002
3003                         let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
3004                         match gossip_sync.handle_node_announcement(&valid_announcement) {
3005                                 Ok(_) => (),
3006                                 Err(_) => panic!()
3007                         };
3008                 }
3009
3010                 let next_announcements = gossip_sync.get_next_node_announcement(None);
3011                 assert!(next_announcements.is_some());
3012
3013                 // Skip the first node.
3014                 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3015                 assert!(next_announcements.is_some());
3016
3017                 {
3018                         // Later announcement which should not be relayed (excess data) prevent us from sharing a node
3019                         let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
3020                                 unsigned_announcement.timestamp += 10;
3021                                 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
3022                         }, node_2_privkey, &secp_ctx);
3023                         match gossip_sync.handle_node_announcement(&valid_announcement) {
3024                                 Ok(res) => assert!(!res),
3025                                 Err(_) => panic!()
3026                         };
3027                 }
3028
3029                 let next_announcements = gossip_sync.get_next_node_announcement(Some(&node_id_1));
3030                 assert!(next_announcements.is_none());
3031         }
3032
3033         #[test]
3034         fn network_graph_serialization() {
3035                 let network_graph = create_network_graph();
3036                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3037
3038                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3039                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3040
3041                 // Announce a channel to add a corresponding node.
3042                 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3043                 match gossip_sync.handle_channel_announcement(&valid_announcement) {
3044                         Ok(res) => assert!(res),
3045                         _ => panic!()
3046                 };
3047
3048                 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3049                 match gossip_sync.handle_node_announcement(&valid_announcement) {
3050                         Ok(_) => (),
3051                         Err(_) => panic!()
3052                 };
3053
3054                 let mut w = test_utils::TestVecWriter(Vec::new());
3055                 assert!(!network_graph.read_only().nodes().is_empty());
3056                 assert!(!network_graph.read_only().channels().is_empty());
3057                 network_graph.write(&mut w).unwrap();
3058
3059                 let logger = Arc::new(test_utils::TestLogger::new());
3060                 assert!(<NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), logger).unwrap() == network_graph);
3061         }
3062
3063         #[test]
3064         fn network_graph_tlv_serialization() {
3065                 let network_graph = create_network_graph();
3066                 network_graph.set_last_rapid_gossip_sync_timestamp(42);
3067
3068                 let mut w = test_utils::TestVecWriter(Vec::new());
3069                 network_graph.write(&mut w).unwrap();
3070
3071                 let logger = Arc::new(test_utils::TestLogger::new());
3072                 let reassembled_network_graph: NetworkGraph<_> = ReadableArgs::read(&mut io::Cursor::new(&w.0), logger).unwrap();
3073                 assert!(reassembled_network_graph == network_graph);
3074                 assert_eq!(reassembled_network_graph.get_last_rapid_gossip_sync_timestamp().unwrap(), 42);
3075         }
3076
3077         #[test]
3078         #[cfg(feature = "std")]
3079         fn calling_sync_routing_table() {
3080                 use std::time::{SystemTime, UNIX_EPOCH};
3081                 use crate::ln::msgs::Init;
3082
3083                 let network_graph = create_network_graph();
3084                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3085                 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
3086                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
3087
3088                 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3089
3090                 // It should ignore if gossip_queries feature is not enabled
3091                 {
3092                         let init_msg = Init { features: InitFeatures::empty(), networks: None, remote_network_address: None };
3093                         gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3094                         let events = gossip_sync.get_and_clear_pending_msg_events();
3095                         assert_eq!(events.len(), 0);
3096                 }
3097
3098                 // It should send a gossip_timestamp_filter with the correct information
3099                 {
3100                         let mut features = InitFeatures::empty();
3101                         features.set_gossip_queries_optional();
3102                         let init_msg = Init { features, networks: None, remote_network_address: None };
3103                         gossip_sync.peer_connected(&node_id_1, &init_msg, true).unwrap();
3104                         let events = gossip_sync.get_and_clear_pending_msg_events();
3105                         assert_eq!(events.len(), 1);
3106                         match &events[0] {
3107                                 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
3108                                         assert_eq!(node_id, &node_id_1);
3109                                         assert_eq!(msg.chain_hash, chain_hash);
3110                                         let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
3111                                         assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
3112                                         assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
3113                                         assert_eq!(msg.timestamp_range, u32::max_value());
3114                                 },
3115                                 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
3116                         };
3117                 }
3118         }
3119
3120         #[test]
3121         fn handling_query_channel_range() {
3122                 let network_graph = create_network_graph();
3123                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3124
3125                 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3126                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3127                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3128                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
3129
3130                 let mut scids: Vec<u64> = vec![
3131                         scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
3132                         scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
3133                 ];
3134
3135                 // used for testing multipart reply across blocks
3136                 for block in 100000..=108001 {
3137                         scids.push(scid_from_parts(block, 0, 0).unwrap());
3138                 }
3139
3140                 // used for testing resumption on same block
3141                 scids.push(scid_from_parts(108001, 1, 0).unwrap());
3142
3143                 for scid in scids {
3144                         let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
3145                                 unsigned_announcement.short_channel_id = scid;
3146                         }, node_1_privkey, node_2_privkey, &secp_ctx);
3147                         match gossip_sync.handle_channel_announcement(&valid_announcement) {
3148                                 Ok(_) => (),
3149                                 _ => panic!()
3150                         };
3151                 }
3152
3153                 // Error when number_of_blocks=0
3154                 do_handling_query_channel_range(
3155                         &gossip_sync,
3156                         &node_id_2,
3157                         QueryChannelRange {
3158                                 chain_hash: chain_hash.clone(),
3159                                 first_blocknum: 0,
3160                                 number_of_blocks: 0,
3161                         },
3162                         false,
3163                         vec![ReplyChannelRange {
3164                                 chain_hash: chain_hash.clone(),
3165                                 first_blocknum: 0,
3166                                 number_of_blocks: 0,
3167                                 sync_complete: true,
3168                                 short_channel_ids: vec![]
3169                         }]
3170                 );
3171
3172                 // Error when wrong chain
3173                 do_handling_query_channel_range(
3174                         &gossip_sync,
3175                         &node_id_2,
3176                         QueryChannelRange {
3177                                 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3178                                 first_blocknum: 0,
3179                                 number_of_blocks: 0xffff_ffff,
3180                         },
3181                         false,
3182                         vec![ReplyChannelRange {
3183                                 chain_hash: ChainHash::using_genesis_block(Network::Bitcoin),
3184                                 first_blocknum: 0,
3185                                 number_of_blocks: 0xffff_ffff,
3186                                 sync_complete: true,
3187                                 short_channel_ids: vec![],
3188                         }]
3189                 );
3190
3191                 // Error when first_blocknum > 0xffffff
3192                 do_handling_query_channel_range(
3193                         &gossip_sync,
3194                         &node_id_2,
3195                         QueryChannelRange {
3196                                 chain_hash: chain_hash.clone(),
3197                                 first_blocknum: 0x01000000,
3198                                 number_of_blocks: 0xffff_ffff,
3199                         },
3200                         false,
3201                         vec![ReplyChannelRange {
3202                                 chain_hash: chain_hash.clone(),
3203                                 first_blocknum: 0x01000000,
3204                                 number_of_blocks: 0xffff_ffff,
3205                                 sync_complete: true,
3206                                 short_channel_ids: vec![]
3207                         }]
3208                 );
3209
3210                 // Empty reply when max valid SCID block num
3211                 do_handling_query_channel_range(
3212                         &gossip_sync,
3213                         &node_id_2,
3214                         QueryChannelRange {
3215                                 chain_hash: chain_hash.clone(),
3216                                 first_blocknum: 0xffffff,
3217                                 number_of_blocks: 1,
3218                         },
3219                         true,
3220                         vec![
3221                                 ReplyChannelRange {
3222                                         chain_hash: chain_hash.clone(),
3223                                         first_blocknum: 0xffffff,
3224                                         number_of_blocks: 1,
3225                                         sync_complete: true,
3226                                         short_channel_ids: vec![]
3227                                 },
3228                         ]
3229                 );
3230
3231                 // No results in valid query range
3232                 do_handling_query_channel_range(
3233                         &gossip_sync,
3234                         &node_id_2,
3235                         QueryChannelRange {
3236                                 chain_hash: chain_hash.clone(),
3237                                 first_blocknum: 1000,
3238                                 number_of_blocks: 1000,
3239                         },
3240                         true,
3241                         vec![
3242                                 ReplyChannelRange {
3243                                         chain_hash: chain_hash.clone(),
3244                                         first_blocknum: 1000,
3245                                         number_of_blocks: 1000,
3246                                         sync_complete: true,
3247                                         short_channel_ids: vec![],
3248                                 }
3249                         ]
3250                 );
3251
3252                 // Overflow first_blocknum + number_of_blocks
3253                 do_handling_query_channel_range(
3254                         &gossip_sync,
3255                         &node_id_2,
3256                         QueryChannelRange {
3257                                 chain_hash: chain_hash.clone(),
3258                                 first_blocknum: 0xfe0000,
3259                                 number_of_blocks: 0xffffffff,
3260                         },
3261                         true,
3262                         vec![
3263                                 ReplyChannelRange {
3264                                         chain_hash: chain_hash.clone(),
3265                                         first_blocknum: 0xfe0000,
3266                                         number_of_blocks: 0xffffffff - 0xfe0000,
3267                                         sync_complete: true,
3268                                         short_channel_ids: vec![
3269                                                 0xfffffe_ffffff_ffff, // max
3270                                         ]
3271                                 }
3272                         ]
3273                 );
3274
3275                 // Single block exactly full
3276                 do_handling_query_channel_range(
3277                         &gossip_sync,
3278                         &node_id_2,
3279                         QueryChannelRange {
3280                                 chain_hash: chain_hash.clone(),
3281                                 first_blocknum: 100000,
3282                                 number_of_blocks: 8000,
3283                         },
3284                         true,
3285                         vec![
3286                                 ReplyChannelRange {
3287                                         chain_hash: chain_hash.clone(),
3288                                         first_blocknum: 100000,
3289                                         number_of_blocks: 8000,
3290                                         sync_complete: true,
3291                                         short_channel_ids: (100000..=107999)
3292                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3293                                                 .collect(),
3294                                 },
3295                         ]
3296                 );
3297
3298                 // Multiple split on new block
3299                 do_handling_query_channel_range(
3300                         &gossip_sync,
3301                         &node_id_2,
3302                         QueryChannelRange {
3303                                 chain_hash: chain_hash.clone(),
3304                                 first_blocknum: 100000,
3305                                 number_of_blocks: 8001,
3306                         },
3307                         true,
3308                         vec![
3309                                 ReplyChannelRange {
3310                                         chain_hash: chain_hash.clone(),
3311                                         first_blocknum: 100000,
3312                                         number_of_blocks: 7999,
3313                                         sync_complete: false,
3314                                         short_channel_ids: (100000..=107999)
3315                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3316                                                 .collect(),
3317                                 },
3318                                 ReplyChannelRange {
3319                                         chain_hash: chain_hash.clone(),
3320                                         first_blocknum: 107999,
3321                                         number_of_blocks: 2,
3322                                         sync_complete: true,
3323                                         short_channel_ids: vec![
3324                                                 scid_from_parts(108000, 0, 0).unwrap(),
3325                                         ],
3326                                 }
3327                         ]
3328                 );
3329
3330                 // Multiple split on same block
3331                 do_handling_query_channel_range(
3332                         &gossip_sync,
3333                         &node_id_2,
3334                         QueryChannelRange {
3335                                 chain_hash: chain_hash.clone(),
3336                                 first_blocknum: 100002,
3337                                 number_of_blocks: 8000,
3338                         },
3339                         true,
3340                         vec![
3341                                 ReplyChannelRange {
3342                                         chain_hash: chain_hash.clone(),
3343                                         first_blocknum: 100002,
3344                                         number_of_blocks: 7999,
3345                                         sync_complete: false,
3346                                         short_channel_ids: (100002..=108001)
3347                                                 .map(|block| scid_from_parts(block, 0, 0).unwrap())
3348                                                 .collect(),
3349                                 },
3350                                 ReplyChannelRange {
3351                                         chain_hash: chain_hash.clone(),
3352                                         first_blocknum: 108001,
3353                                         number_of_blocks: 1,
3354                                         sync_complete: true,
3355                                         short_channel_ids: vec![
3356                                                 scid_from_parts(108001, 1, 0).unwrap(),
3357                                         ],
3358                                 }
3359                         ]
3360                 );
3361         }
3362
3363         fn do_handling_query_channel_range(
3364                 gossip_sync: &P2PGossipSync<&NetworkGraph<Arc<test_utils::TestLogger>>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
3365                 test_node_id: &PublicKey,
3366                 msg: QueryChannelRange,
3367                 expected_ok: bool,
3368                 expected_replies: Vec<ReplyChannelRange>
3369         ) {
3370                 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
3371                 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
3372                 let query_end_blocknum = msg.end_blocknum();
3373                 let result = gossip_sync.handle_query_channel_range(test_node_id, msg);
3374
3375                 if expected_ok {
3376                         assert!(result.is_ok());
3377                 } else {
3378                         assert!(result.is_err());
3379                 }
3380
3381                 let events = gossip_sync.get_and_clear_pending_msg_events();
3382                 assert_eq!(events.len(), expected_replies.len());
3383
3384                 for i in 0..events.len() {
3385                         let expected_reply = &expected_replies[i];
3386                         match &events[i] {
3387                                 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
3388                                         assert_eq!(node_id, test_node_id);
3389                                         assert_eq!(msg.chain_hash, expected_reply.chain_hash);
3390                                         assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
3391                                         assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
3392                                         assert_eq!(msg.sync_complete, expected_reply.sync_complete);
3393                                         assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
3394
3395                                         // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
3396                                         assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
3397                                         assert!(msg.first_blocknum >= max_firstblocknum);
3398                                         max_firstblocknum = msg.first_blocknum;
3399                                         c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
3400
3401                                         // Check that the last block count is >= the query's end_blocknum
3402                                         if i == events.len() - 1 {
3403                                                 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
3404                                         }
3405                                 },
3406                                 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
3407                         }
3408                 }
3409         }
3410
3411         #[test]
3412         fn handling_query_short_channel_ids() {
3413                 let network_graph = create_network_graph();
3414                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3415                 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3416                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
3417
3418                 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
3419
3420                 let result = gossip_sync.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
3421                         chain_hash,
3422                         short_channel_ids: vec![0x0003e8_000000_0000],
3423                 });
3424                 assert!(result.is_err());
3425         }
3426
3427         #[test]
3428         fn displays_node_alias() {
3429                 let format_str_alias = |alias: &str| {
3430                         let mut bytes = [0u8; 32];
3431                         bytes[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
3432                         format!("{}", NodeAlias(bytes))
3433                 };
3434
3435                 assert_eq!(format_str_alias("I\u{1F496}LDK! \u{26A1}"), "I\u{1F496}LDK! \u{26A1}");
3436                 assert_eq!(format_str_alias("I\u{1F496}LDK!\0\u{26A1}"), "I\u{1F496}LDK!");
3437                 assert_eq!(format_str_alias("I\u{1F496}LDK!\t\u{26A1}"), "I\u{1F496}LDK!\u{FFFD}\u{26A1}");
3438
3439                 let format_bytes_alias = |alias: &[u8]| {
3440                         let mut bytes = [0u8; 32];
3441                         bytes[..alias.len()].copy_from_slice(alias);
3442                         format!("{}", NodeAlias(bytes))
3443                 };
3444
3445                 assert_eq!(format_bytes_alias(b"\xFFI <heart> LDK!"), "\u{FFFD}I <heart> LDK!");
3446                 assert_eq!(format_bytes_alias(b"\xFFI <heart>\0LDK!"), "\u{FFFD}I <heart>");
3447                 assert_eq!(format_bytes_alias(b"\xFFI <heart>\tLDK!"), "\u{FFFD}I <heart>\u{FFFD}LDK!");
3448         }
3449
3450         #[test]
3451         fn channel_info_is_readable() {
3452                 let chanmon_cfgs = crate::ln::functional_test_utils::create_chanmon_cfgs(2);
3453                 let node_cfgs = crate::ln::functional_test_utils::create_node_cfgs(2, &chanmon_cfgs);
3454                 let node_chanmgrs = crate::ln::functional_test_utils::create_node_chanmgrs(2, &node_cfgs, &[None, None, None, None]);
3455                 let nodes = crate::ln::functional_test_utils::create_network(2, &node_cfgs, &node_chanmgrs);
3456                 let config = crate::ln::functional_test_utils::test_default_channel_config();
3457
3458                 // 1. Test encoding/decoding of ChannelUpdateInfo
3459                 let chan_update_info = ChannelUpdateInfo {
3460                         last_update: 23,
3461                         enabled: true,
3462                         cltv_expiry_delta: 42,
3463                         htlc_minimum_msat: 1234,
3464                         htlc_maximum_msat: 5678,
3465                         fees: RoutingFees { base_msat: 9, proportional_millionths: 10 },
3466                         last_update_message: None,
3467                 };
3468
3469                 let mut encoded_chan_update_info: Vec<u8> = Vec::new();
3470                 assert!(chan_update_info.write(&mut encoded_chan_update_info).is_ok());
3471
3472                 // First make sure we can read ChannelUpdateInfos we just wrote
3473                 let read_chan_update_info: ChannelUpdateInfo = crate::util::ser::Readable::read(&mut encoded_chan_update_info.as_slice()).unwrap();
3474                 assert_eq!(chan_update_info, read_chan_update_info);
3475
3476                 // Check the serialization hasn't changed.
3477                 let legacy_chan_update_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c0100").unwrap();
3478                 assert_eq!(encoded_chan_update_info, legacy_chan_update_info_with_some);
3479
3480                 // Check we fail if htlc_maximum_msat is not present in either the ChannelUpdateInfo itself
3481                 // or the ChannelUpdate enclosed with `last_update_message`.
3482                 let legacy_chan_update_info_with_some_and_fail_update: Vec<u8> = <Vec<u8>>::from_hex("b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f42400000271000000014").unwrap();
3483                 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());
3484                 assert!(read_chan_update_info_res.is_err());
3485
3486                 let legacy_chan_update_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c0100").unwrap();
3487                 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());
3488                 assert!(read_chan_update_info_res.is_err());
3489
3490                 // 2. Test encoding/decoding of ChannelInfo
3491                 // Check we can encode/decode ChannelInfo without ChannelUpdateInfo fields present.
3492                 let chan_info_none_updates = ChannelInfo {
3493                         features: channelmanager::provided_channel_features(&config),
3494                         node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3495                         one_to_two: None,
3496                         node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3497                         two_to_one: None,
3498                         capacity_sats: None,
3499                         announcement_message: None,
3500                         announcement_received_time: 87654,
3501                         node_one_counter: 0,
3502                         node_two_counter: 1,
3503                 };
3504
3505                 let mut encoded_chan_info: Vec<u8> = Vec::new();
3506                 assert!(chan_info_none_updates.write(&mut encoded_chan_info).is_ok());
3507
3508                 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3509                 assert_eq!(chan_info_none_updates, read_chan_info);
3510
3511                 // Check we can encode/decode ChannelInfo with ChannelUpdateInfo fields present.
3512                 let chan_info_some_updates = ChannelInfo {
3513                         features: channelmanager::provided_channel_features(&config),
3514                         node_one: NodeId::from_pubkey(&nodes[0].node.get_our_node_id()),
3515                         one_to_two: Some(chan_update_info.clone()),
3516                         node_two: NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
3517                         two_to_one: Some(chan_update_info.clone()),
3518                         capacity_sats: None,
3519                         announcement_message: None,
3520                         announcement_received_time: 87654,
3521                         node_one_counter: 0,
3522                         node_two_counter: 1,
3523                 };
3524
3525                 let mut encoded_chan_info: Vec<u8> = Vec::new();
3526                 assert!(chan_info_some_updates.write(&mut encoded_chan_info).is_ok());
3527
3528                 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut encoded_chan_info.as_slice()).unwrap();
3529                 assert_eq!(chan_info_some_updates, read_chan_info);
3530
3531                 // Check the serialization hasn't changed.
3532                 let legacy_chan_info_with_some: Vec<u8> = <Vec<u8>>::from_hex("ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88043636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23083636340004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3533                 assert_eq!(encoded_chan_info, legacy_chan_info_with_some);
3534
3535                 // Check we can decode legacy ChannelInfo, even if the `two_to_one` / `one_to_two` /
3536                 // `last_update_message` fields fail to decode due to missing htlc_maximum_msat.
3537                 let legacy_chan_info_with_some_and_fail_update = <Vec<u8>>::from_hex("fd01ca00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce8804b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f4240000027100000001406210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2308b6b6b40004000000170201010402002a060800000000000004d2080909000000000000162e0a0d0c00040000000902040000000a0c8181d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f00083a840000034d013413a70000009000000000000f424000002710000000140a01000c0100").unwrap();
3538                 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_some_and_fail_update.as_slice()).unwrap();
3539                 assert_eq!(read_chan_info.announcement_received_time, 87654);
3540                 assert_eq!(read_chan_info.one_to_two, None);
3541                 assert_eq!(read_chan_info.two_to_one, None);
3542
3543                 let legacy_chan_info_with_none: Vec<u8> = <Vec<u8>>::from_hex("ba00020000010800000000000156660221027f921585f2ac0c7c70e36110adecfd8fd14b8a99bfb3d000a283fcac358fce88042e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c010006210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23082e2e2c0004000000170201010402002a060800000000000004d20801000a0d0c00040000000902040000000a0c01000a01000c0100").unwrap();
3544                 let read_chan_info: ChannelInfo = crate::util::ser::Readable::read(&mut legacy_chan_info_with_none.as_slice()).unwrap();
3545                 assert_eq!(read_chan_info.announcement_received_time, 87654);
3546                 assert_eq!(read_chan_info.one_to_two, None);
3547                 assert_eq!(read_chan_info.two_to_one, None);
3548         }
3549
3550         #[test]
3551         fn node_info_is_readable() {
3552                 // 1. Check we can read a valid NodeAnnouncementInfo and fail on an invalid one
3553                 let announcement_message = <Vec<u8>>::from_hex("d977cb9b53d93a6ff64bb5f1e158b4094b66e798fb12911168a3ccdf80a83096340a6a95da0ae8d9f776528eecdbb747eb6b545495a4319ed5378e35b21e073a000122013413a7031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f2020201010101010101010101010101010101010101010101010101010101010101010000701fffefdfc2607").unwrap();
3554                 let announcement_message = NodeAnnouncement::read(&mut announcement_message.as_slice()).unwrap();
3555                 let valid_node_ann_info = NodeAnnouncementInfo {
3556                         features: channelmanager::provided_node_features(&UserConfig::default()),
3557                         last_update: 0,
3558                         rgb: [0u8; 3],
3559                         alias: NodeAlias([0u8; 32]),
3560                         announcement_message: Some(announcement_message)
3561                 };
3562
3563                 let mut encoded_valid_node_ann_info = Vec::new();
3564                 assert!(valid_node_ann_info.write(&mut encoded_valid_node_ann_info).is_ok());
3565                 let read_valid_node_ann_info = NodeAnnouncementInfo::read(&mut encoded_valid_node_ann_info.as_slice()).unwrap();
3566                 assert_eq!(read_valid_node_ann_info, valid_node_ann_info);
3567                 assert_eq!(read_valid_node_ann_info.addresses().len(), 1);
3568
3569                 let encoded_invalid_node_ann_info = <Vec<u8>>::from_hex("3f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d2").unwrap();
3570                 let read_invalid_node_ann_info_res = NodeAnnouncementInfo::read(&mut encoded_invalid_node_ann_info.as_slice());
3571                 assert!(read_invalid_node_ann_info_res.is_err());
3572
3573                 // 2. Check we can read a NodeInfo anyways, but set the NodeAnnouncementInfo to None if invalid
3574                 let valid_node_info = NodeInfo {
3575                         channels: Vec::new(),
3576                         announcement_info: Some(valid_node_ann_info),
3577                         node_counter: 0,
3578                 };
3579
3580                 let mut encoded_valid_node_info = Vec::new();
3581                 assert!(valid_node_info.write(&mut encoded_valid_node_info).is_ok());
3582                 let read_valid_node_info = NodeInfo::read(&mut encoded_valid_node_info.as_slice()).unwrap();
3583                 assert_eq!(read_valid_node_info, valid_node_info);
3584
3585                 let encoded_invalid_node_info_hex = <Vec<u8>>::from_hex("4402403f0009000788a000080a51a20204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014004d20400").unwrap();
3586                 let read_invalid_node_info = NodeInfo::read(&mut encoded_invalid_node_info_hex.as_slice()).unwrap();
3587                 assert_eq!(read_invalid_node_info.announcement_info, None);
3588         }
3589
3590         #[test]
3591         fn test_node_info_keeps_compatibility() {
3592                 let old_ann_info_with_addresses = <Vec<u8>>::from_hex("3f0009000708a000080a51220204000000000403000000062000000000000000000000000000000000000000000000000000000000000000000a0505014104d2").unwrap();
3593                 let ann_info_with_addresses = NodeAnnouncementInfo::read(&mut old_ann_info_with_addresses.as_slice())
3594                                 .expect("to be able to read an old NodeAnnouncementInfo with addresses");
3595                 // This serialized info has an address field but no announcement_message, therefore the addresses returned by our function will still be empty
3596                 assert!(ann_info_with_addresses.addresses().is_empty());
3597         }
3598
3599         #[test]
3600         fn test_node_id_display() {
3601                 let node_id = NodeId([42; 33]);
3602                 assert_eq!(format!("{}", &node_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
3603         }
3604
3605         #[test]
3606         fn is_tor_only_node() {
3607                 let network_graph = create_network_graph();
3608                 let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph);
3609
3610                 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
3611                 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3612                 let node_1_id = NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));
3613
3614                 let announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
3615                 gossip_sync.handle_channel_announcement(&announcement).unwrap();
3616
3617                 let tcp_ip_v4 = SocketAddress::TcpIpV4 {
3618                         addr: [255, 254, 253, 252],
3619                         port: 9735
3620                 };
3621                 let tcp_ip_v6 = SocketAddress::TcpIpV6 {
3622                         addr: [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240],
3623                         port: 9735
3624                 };
3625                 let onion_v2 = SocketAddress::OnionV2([255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]);
3626                 let onion_v3 = SocketAddress::OnionV3 {
3627                         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],
3628                         checksum: 32,
3629                         version: 16,
3630                         port: 9735
3631                 };
3632                 let hostname = SocketAddress::Hostname {
3633                         hostname: Hostname::try_from(String::from("host")).unwrap(),
3634                         port: 9735,
3635                 };
3636
3637                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3638
3639                 let announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
3640                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3641                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3642
3643                 let announcement = get_signed_node_announcement(
3644                         |announcement| {
3645                                 announcement.addresses = vec![
3646                                         tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone(),
3647                                         hostname.clone()
3648                                 ];
3649                                 announcement.timestamp += 1000;
3650                         },
3651                         node_1_privkey, &secp_ctx
3652                 );
3653                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3654                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3655
3656                 let announcement = get_signed_node_announcement(
3657                         |announcement| {
3658                                 announcement.addresses = vec![
3659                                         tcp_ip_v4.clone(), tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3660                                 ];
3661                                 announcement.timestamp += 2000;
3662                         },
3663                         node_1_privkey, &secp_ctx
3664                 );
3665                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3666                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3667
3668                 let announcement = get_signed_node_announcement(
3669                         |announcement| {
3670                                 announcement.addresses = vec![
3671                                         tcp_ip_v6.clone(), onion_v2.clone(), onion_v3.clone()
3672                                 ];
3673                                 announcement.timestamp += 3000;
3674                         },
3675                         node_1_privkey, &secp_ctx
3676                 );
3677                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3678                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3679
3680                 let announcement = get_signed_node_announcement(
3681                         |announcement| {
3682                                 announcement.addresses = vec![onion_v2.clone(), onion_v3.clone()];
3683                                 announcement.timestamp += 4000;
3684                         },
3685                         node_1_privkey, &secp_ctx
3686                 );
3687                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3688                 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3689
3690                 let announcement = get_signed_node_announcement(
3691                         |announcement| {
3692                                 announcement.addresses = vec![onion_v2.clone()];
3693                                 announcement.timestamp += 5000;
3694                         },
3695                         node_1_privkey, &secp_ctx
3696                 );
3697                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3698                 assert!(network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3699
3700                 let announcement = get_signed_node_announcement(
3701                         |announcement| {
3702                                 announcement.addresses = vec![tcp_ip_v4.clone()];
3703                                 announcement.timestamp += 6000;
3704                         },
3705                         node_1_privkey, &secp_ctx
3706                 );
3707                 gossip_sync.handle_node_announcement(&announcement).unwrap();
3708                 assert!(!network_graph.read_only().node(&node_1_id).unwrap().is_tor_only());
3709         }
3710 }
3711
3712 #[cfg(ldk_bench)]
3713 pub mod benches {
3714         use super::*;
3715         use std::io::Read;
3716         use criterion::{black_box, Criterion};
3717
3718         pub fn read_network_graph(bench: &mut Criterion) {
3719                 let logger = crate::util::test_utils::TestLogger::new();
3720                 let (mut d, _) = crate::routing::router::bench_utils::get_graph_scorer_file().unwrap();
3721                 let mut v = Vec::new();
3722                 d.read_to_end(&mut v).unwrap();
3723                 bench.bench_function("read_network_graph", |b| b.iter(||
3724                         NetworkGraph::read(&mut std::io::Cursor::new(black_box(&v)), &logger).unwrap()
3725                 ));
3726         }
3727
3728         pub fn write_network_graph(bench: &mut Criterion) {
3729                 let logger = crate::util::test_utils::TestLogger::new();
3730                 let (mut d, _) = crate::routing::router::bench_utils::get_graph_scorer_file().unwrap();
3731                 let net_graph = NetworkGraph::read(&mut d, &logger).unwrap();
3732                 bench.bench_function("write_network_graph", |b| b.iter(||
3733                         black_box(&net_graph).encode()
3734                 ));
3735         }
3736 }