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