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