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