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