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