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