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