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