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