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