Export Onion Message structs in their respective modules
[rust-lightning] / lightning / src / ln / peer_handler.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 //! Top level peer message handling and socket handling logic lives here.
11 //!
12 //! Instead of actually servicing sockets ourselves we require that you implement the
13 //! SocketDescriptor interface and use that to receive actions which you should perform on the
14 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
15 //! call into the provided message handlers (probably a ChannelManager and P2PGossipSync) with
16 //! messages they should handle, and encoding/sending response messages.
17
18 use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
19
20 use crate::ln::features::{InitFeatures, NodeFeatures};
21 use crate::ln::msgs;
22 use crate::ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
23 use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24 use crate::util::ser::{VecWriter, Writeable, Writer};
25 use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
26 use crate::ln::wire;
27 use crate::ln::wire::Encode;
28 use crate::onion_message::messenger::{CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
29 use crate::onion_message::packet::CustomOnionMessageContents;
30 use crate::routing::gossip::{NetworkGraph, P2PGossipSync};
31 use crate::util::atomic_counter::AtomicCounter;
32 use crate::util::crypto::sign;
33 use crate::util::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
34 use crate::util::logger::Logger;
35
36 use crate::prelude::*;
37 use crate::io;
38 use alloc::collections::LinkedList;
39 use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock};
40 use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
41 use core::{cmp, hash, fmt, mem};
42 use core::ops::Deref;
43 use core::convert::Infallible;
44 #[cfg(feature = "std")] use std::error;
45
46 use bitcoin::hashes::sha256::Hash as Sha256;
47 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
48 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
49 use bitcoin::hashes::{HashEngine, Hash};
50
51 /// Handler for BOLT1-compliant messages.
52 pub trait CustomMessageHandler: wire::CustomMessageReader {
53         /// Called with the message type that was received and the buffer to be read.
54         /// Can return a `MessageHandlingError` if the message could not be handled.
55         fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
56
57         /// Gets the list of pending messages which were generated by the custom message
58         /// handler, clearing the list in the process. The first tuple element must
59         /// correspond to the intended recipients node ids. If no connection to one of the
60         /// specified node does not exist, the message is simply not sent to it.
61         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
62 }
63
64 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
65 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
66 pub struct IgnoringMessageHandler{}
67 impl MessageSendEventsProvider for IgnoringMessageHandler {
68         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
69 }
70 impl RoutingMessageHandler for IgnoringMessageHandler {
71         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
72         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
73         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
74         fn get_next_channel_announcement(&self, _starting_point: u64) ->
75                 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
76         fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> { None }
77         fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) -> Result<(), ()> { Ok(()) }
78         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
79         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
80         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
81         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
82         fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
83         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
84                 InitFeatures::empty()
85         }
86 }
87 impl OnionMessageProvider for IgnoringMessageHandler {
88         fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
89 }
90 impl OnionMessageHandler for IgnoringMessageHandler {
91         fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
92         fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) -> Result<(), ()> { Ok(()) }
93         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
94         fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
95         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
96                 InitFeatures::empty()
97         }
98 }
99 impl CustomOnionMessageHandler for IgnoringMessageHandler {
100         type CustomMessage = Infallible;
101         fn handle_custom_message(&self, _msg: Infallible) {
102                 // Since we always return `None` in the read the handle method should never be called.
103                 unreachable!();
104         }
105         fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
106                 Ok(None)
107         }
108 }
109
110 impl CustomOnionMessageContents for Infallible {
111         fn tlv_type(&self) -> u64 { unreachable!(); }
112 }
113
114 impl Deref for IgnoringMessageHandler {
115         type Target = IgnoringMessageHandler;
116         fn deref(&self) -> &Self { self }
117 }
118
119 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
120 // method that takes self for it.
121 impl wire::Type for Infallible {
122         fn type_id(&self) -> u16 {
123                 unreachable!();
124         }
125 }
126 impl Writeable for Infallible {
127         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
128                 unreachable!();
129         }
130 }
131
132 impl wire::CustomMessageReader for IgnoringMessageHandler {
133         type CustomMessage = Infallible;
134         fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
135                 Ok(None)
136         }
137 }
138
139 impl CustomMessageHandler for IgnoringMessageHandler {
140         fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
141                 // Since we always return `None` in the read the handle method should never be called.
142                 unreachable!();
143         }
144
145         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
146 }
147
148 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
149 /// You can provide one of these as the route_handler in a MessageHandler.
150 pub struct ErroringMessageHandler {
151         message_queue: Mutex<Vec<MessageSendEvent>>
152 }
153 impl ErroringMessageHandler {
154         /// Constructs a new ErroringMessageHandler
155         pub fn new() -> Self {
156                 Self { message_queue: Mutex::new(Vec::new()) }
157         }
158         fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
159                 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
160                         action: msgs::ErrorAction::SendErrorMessage {
161                                 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
162                         },
163                         node_id: node_id.clone(),
164                 });
165         }
166 }
167 impl MessageSendEventsProvider for ErroringMessageHandler {
168         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
169                 let mut res = Vec::new();
170                 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
171                 res
172         }
173 }
174 impl ChannelMessageHandler for ErroringMessageHandler {
175         // Any messages which are related to a specific channel generate an error message to let the
176         // peer know we don't care about channels.
177         fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
178                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
179         }
180         fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
181                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
182         }
183         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
184                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
185         }
186         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
187                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
188         }
189         fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
190                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
191         }
192         fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
193                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
194         }
195         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
196                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
197         }
198         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
199                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
200         }
201         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
202                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
203         }
204         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
205                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
206         }
207         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
208                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
209         }
210         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
211                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
212         }
213         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
214                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
215         }
216         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
217                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
218         }
219         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
220                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
221         }
222         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
223                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
224         }
225         // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
226         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
227         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
228         fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) -> Result<(), ()> { Ok(()) }
229         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
230         fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
231         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
232                 // Set a number of features which various nodes may require to talk to us. It's totally
233                 // reasonable to indicate we "support" all kinds of channel features...we just reject all
234                 // channels.
235                 let mut features = InitFeatures::empty();
236                 features.set_data_loss_protect_optional();
237                 features.set_upfront_shutdown_script_optional();
238                 features.set_variable_length_onion_optional();
239                 features.set_static_remote_key_optional();
240                 features.set_payment_secret_optional();
241                 features.set_basic_mpp_optional();
242                 features.set_wumbo_optional();
243                 features.set_shutdown_any_segwit_optional();
244                 features.set_channel_type_optional();
245                 features.set_scid_privacy_optional();
246                 features.set_zero_conf_optional();
247                 features
248         }
249 }
250 impl Deref for ErroringMessageHandler {
251         type Target = ErroringMessageHandler;
252         fn deref(&self) -> &Self { self }
253 }
254
255 /// Provides references to trait impls which handle different types of messages.
256 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref> where
257                 CM::Target: ChannelMessageHandler,
258                 RM::Target: RoutingMessageHandler,
259                 OM::Target: OnionMessageHandler,
260 {
261         /// A message handler which handles messages specific to channels. Usually this is just a
262         /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
263         ///
264         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
265         pub chan_handler: CM,
266         /// A message handler which handles messages updating our knowledge of the network channel
267         /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
268         ///
269         /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
270         pub route_handler: RM,
271
272         /// A message handler which handles onion messages. For now, this can only be an
273         /// [`IgnoringMessageHandler`].
274         pub onion_message_handler: OM,
275 }
276
277 /// Provides an object which can be used to send data to and which uniquely identifies a connection
278 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
279 /// implement Hash to meet the PeerManager API.
280 ///
281 /// For efficiency, Clone should be relatively cheap for this type.
282 ///
283 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
284 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
285 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
286 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
287 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
288 /// to simply use another value which is guaranteed to be globally unique instead.
289 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
290         /// Attempts to send some data from the given slice to the peer.
291         ///
292         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
293         /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
294         /// called and further write attempts may occur until that time.
295         ///
296         /// If the returned size is smaller than `data.len()`, a
297         /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
298         /// written. Additionally, until a `send_data` event completes fully, no further
299         /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
300         /// prevent denial-of-service issues, you should not read or buffer any data from the socket
301         /// until then.
302         ///
303         /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
304         /// (indicating that read events should be paused to prevent DoS in the send buffer),
305         /// `resume_read` may be set indicating that read events on this descriptor should resume. A
306         /// `resume_read` of false carries no meaning, and should not cause any action.
307         fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
308         /// Disconnect the socket pointed to by this SocketDescriptor.
309         ///
310         /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
311         /// call (doing so is a noop).
312         fn disconnect_socket(&mut self);
313 }
314
315 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
316 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
317 /// descriptor.
318 #[derive(Clone)]
319 pub struct PeerHandleError {
320         /// Used to indicate that we probably can't make any future connections to this peer (e.g.
321         /// because we required features that our peer was missing, or vice versa).
322         ///
323         /// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close
324         /// any channels with this peer or check for new versions of LDK.
325         ///
326         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
327         pub no_connection_possible: bool,
328 }
329 impl fmt::Debug for PeerHandleError {
330         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
331                 formatter.write_str("Peer Sent Invalid Data")
332         }
333 }
334 impl fmt::Display for PeerHandleError {
335         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
336                 formatter.write_str("Peer Sent Invalid Data")
337         }
338 }
339
340 #[cfg(feature = "std")]
341 impl error::Error for PeerHandleError {
342         fn description(&self) -> &str {
343                 "Peer Sent Invalid Data"
344         }
345 }
346
347 enum InitSyncTracker{
348         NoSyncRequested,
349         ChannelsSyncing(u64),
350         NodesSyncing(PublicKey),
351 }
352
353 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
354 /// forwarding gossip messages to peers altogether.
355 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
356
357 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
358 /// we have fewer than this many messages in the outbound buffer again.
359 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
360 /// refilled as we send bytes.
361 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
362 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
363 /// the peer.
364 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
365
366 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
367 /// the socket receive buffer before receiving the ping.
368 ///
369 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
370 /// including any network delays, outbound traffic, or the same for messages from other peers.
371 ///
372 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
373 /// per connected peer to respond to a ping, as long as they send us at least one message during
374 /// each tick, ensuring we aren't actually just disconnected.
375 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
376 /// peer.
377 ///
378 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
379 /// two connected peers, assuming most LDK-running systems have at least two cores.
380 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
381
382 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
383 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
384 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
385 /// process before the next ping.
386 ///
387 /// Note that we continue responding to other messages even after we've sent this many messages, so
388 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
389 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
390 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
391
392 struct Peer {
393         channel_encryptor: PeerChannelEncryptor,
394         their_node_id: Option<PublicKey>,
395         their_features: Option<InitFeatures>,
396         their_net_address: Option<NetAddress>,
397
398         pending_outbound_buffer: LinkedList<Vec<u8>>,
399         pending_outbound_buffer_first_msg_offset: usize,
400         /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
401         /// prioritize channel messages over them.
402         ///
403         /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
404         gossip_broadcast_buffer: LinkedList<Vec<u8>>,
405         awaiting_write_event: bool,
406
407         pending_read_buffer: Vec<u8>,
408         pending_read_buffer_pos: usize,
409         pending_read_is_header: bool,
410
411         sync_status: InitSyncTracker,
412
413         msgs_sent_since_pong: usize,
414         awaiting_pong_timer_tick_intervals: i8,
415         received_message_since_timer_tick: bool,
416         sent_gossip_timestamp_filter: bool,
417 }
418
419 impl Peer {
420         /// Returns true if the channel announcements/updates for the given channel should be
421         /// forwarded to this peer.
422         /// If we are sending our routing table to this peer and we have not yet sent channel
423         /// announcements/updates for the given channel_id then we will send it when we get to that
424         /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
425         /// sent the old versions, we should send the update, and so return true here.
426         fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
427                 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
428                         !self.sent_gossip_timestamp_filter {
429                                 return false;
430                         }
431                 match self.sync_status {
432                         InitSyncTracker::NoSyncRequested => true,
433                         InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
434                         InitSyncTracker::NodesSyncing(_) => true,
435                 }
436         }
437
438         /// Similar to the above, but for node announcements indexed by node_id.
439         fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
440                 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
441                         !self.sent_gossip_timestamp_filter {
442                                 return false;
443                         }
444                 match self.sync_status {
445                         InitSyncTracker::NoSyncRequested => true,
446                         InitSyncTracker::ChannelsSyncing(_) => false,
447                         InitSyncTracker::NodesSyncing(pk) => pk < node_id,
448                 }
449         }
450
451         /// Returns whether we should be reading bytes from this peer, based on whether its outbound
452         /// buffer still has space and we don't need to pause reads to get some writes out.
453         fn should_read(&self) -> bool {
454                 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE
455         }
456
457         /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
458         /// outbound buffer. This is checked every time the peer's buffer may have been drained.
459         fn should_buffer_gossip_backfill(&self) -> bool {
460                 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
461                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
462         }
463
464         /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
465         /// every time the peer's buffer may have been drained.
466         fn should_buffer_onion_message(&self) -> bool {
467                 self.pending_outbound_buffer.is_empty()
468                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
469         }
470
471         /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
472         /// buffer. This is checked every time the peer's buffer may have been drained.
473         fn should_buffer_gossip_broadcast(&self) -> bool {
474                 self.pending_outbound_buffer.is_empty()
475                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
476         }
477
478         /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
479         fn buffer_full_drop_gossip_broadcast(&self) -> bool {
480                 let total_outbound_buffered =
481                         self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
482
483                 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
484                         self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
485         }
486 }
487
488 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
489 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
490 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
491 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
492 /// issues such as overly long function definitions.
493 ///
494 /// (C-not exported) as `Arc`s don't make sense in bindings.
495 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, Arc<C>, Arc<L>>>, Arc<SimpleArcOnionMessenger<L>>, Arc<L>, IgnoringMessageHandler>;
496
497 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
498 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
499 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
500 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
501 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
502 /// helps with issues such as long function definitions.
503 ///
504 /// (C-not exported) as general type aliases don't make sense in bindings.
505 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e P2PGossipSync<&'g NetworkGraph<&'f L>, &'h C, &'f L>, &'i SimpleRefOnionMessenger<'j, 'k, L>, &'f L, IgnoringMessageHandler>;
506
507 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
508 /// socket events into messages which it passes on to its [`MessageHandler`].
509 ///
510 /// Locks are taken internally, so you must never assume that reentrancy from a
511 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
512 ///
513 /// Calls to [`read_event`] will decode relevant messages and pass them to the
514 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
515 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
516 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
517 /// calls only after previous ones have returned.
518 ///
519 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
520 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
521 /// essentially you should default to using a SimpleRefPeerManager, and use a
522 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
523 /// you're using lightning-net-tokio.
524 ///
525 /// [`read_event`]: PeerManager::read_event
526 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> where
527                 CM::Target: ChannelMessageHandler,
528                 RM::Target: RoutingMessageHandler,
529                 OM::Target: OnionMessageHandler,
530                 L::Target: Logger,
531                 CMH::Target: CustomMessageHandler {
532         message_handler: MessageHandler<CM, RM, OM>,
533         /// Connection state for each connected peer - we have an outer read-write lock which is taken
534         /// as read while we're doing processing for a peer and taken write when a peer is being added
535         /// or removed.
536         ///
537         /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
538         /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
539         /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
540         /// the `MessageHandler`s for a given peer is already guaranteed.
541         peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
542         /// Only add to this set when noise completes.
543         /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
544         /// lock held. Entries may be added with only the `peers` read lock held (though the
545         /// `Descriptor` value must already exist in `peers`).
546         node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
547         /// We can only have one thread processing events at once, but we don't usually need the full
548         /// `peers` write lock to do so, so instead we block on this empty mutex when entering
549         /// `process_events`.
550         event_processing_lock: Mutex<()>,
551         /// Because event processing is global and always does all available work before returning,
552         /// there is no reason for us to have many event processors waiting on the lock at once.
553         /// Instead, we limit the total blocked event processors to always exactly one by setting this
554         /// when an event process call is waiting.
555         blocked_event_processors: AtomicBool,
556
557         /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
558         /// value increases strictly since we don't assume access to a time source.
559         last_node_announcement_serial: AtomicU32,
560
561         our_node_secret: SecretKey,
562         ephemeral_key_midstate: Sha256Engine,
563         custom_message_handler: CMH,
564
565         peer_counter: AtomicCounter,
566
567         logger: L,
568         secp_ctx: Secp256k1<secp256k1::SignOnly>
569 }
570
571 enum MessageHandlingError {
572         PeerHandleError(PeerHandleError),
573         LightningError(LightningError),
574 }
575
576 impl From<PeerHandleError> for MessageHandlingError {
577         fn from(error: PeerHandleError) -> Self {
578                 MessageHandlingError::PeerHandleError(error)
579         }
580 }
581
582 impl From<LightningError> for MessageHandlingError {
583         fn from(error: LightningError) -> Self {
584                 MessageHandlingError::LightningError(error)
585         }
586 }
587
588 macro_rules! encode_msg {
589         ($msg: expr) => {{
590                 let mut buffer = VecWriter(Vec::new());
591                 wire::write($msg, &mut buffer).unwrap();
592                 buffer.0
593         }}
594 }
595
596 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler> where
597                 CM::Target: ChannelMessageHandler,
598                 OM::Target: OnionMessageHandler,
599                 L::Target: Logger {
600         /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
601         /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
602         /// ignored.
603         ///
604         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
605         /// cryptographically secure random bytes.
606         ///
607         /// `current_time` is used as an always-increasing counter that survives across restarts and is
608         /// incremented irregularly internally. In general it is best to simply use the current UNIX
609         /// timestamp, however if it is not available a persistent counter that increases once per
610         /// minute should suffice.
611         ///
612         /// (C-not exported) as we can't export a PeerManager with a dummy route handler
613         pub fn new_channel_only(channel_message_handler: CM, onion_message_handler: OM, our_node_secret: SecretKey, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
614                 Self::new(MessageHandler {
615                         chan_handler: channel_message_handler,
616                         route_handler: IgnoringMessageHandler{},
617                         onion_message_handler,
618                 }, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
619         }
620 }
621
622 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
623                 RM::Target: RoutingMessageHandler,
624                 L::Target: Logger {
625         /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
626         /// handler or onion message handler is used and onion and channel messages will be ignored (or
627         /// generate error messages). Note that some other lightning implementations time-out connections
628         /// after some time if no channel is built with the peer.
629         ///
630         /// `current_time` is used as an always-increasing counter that survives across restarts and is
631         /// incremented irregularly internally. In general it is best to simply use the current UNIX
632         /// timestamp, however if it is not available a persistent counter that increases once per
633         /// minute should suffice.
634         ///
635         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
636         /// cryptographically secure random bytes.
637         ///
638         /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
639         pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
640                 Self::new(MessageHandler {
641                         chan_handler: ErroringMessageHandler::new(),
642                         route_handler: routing_message_handler,
643                         onion_message_handler: IgnoringMessageHandler{},
644                 }, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
645         }
646 }
647
648 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
649 /// This works around `format!()` taking a reference to each argument, preventing
650 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
651 /// due to lifetime errors.
652 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
653 impl core::fmt::Display for OptionalFromDebugger<'_> {
654         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
655                 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
656         }
657 }
658
659 /// A function used to filter out local or private addresses
660 /// https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml
661 /// https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
662 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
663         match ip_address{
664                 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
665                 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
666                 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
667                 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
668                 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
669                 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
670                 // For IPv4 range       127.0.0.0 - 127.255.255.255 (127/8)
671                 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
672                 // For IPv4 range       169.254.0.0 - 169.254.255.255 (169.254/16)
673                 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
674                 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
675                 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
676                 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
677                 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
678                 // For IPv4 range 192.88.99.0 - 192.88.99.255  (192.88.99/24)
679                 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
680                 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
681                 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
682                 // For remaining addresses
683                 Some(NetAddress::IPv6{addr: _, port: _}) => None,
684                 Some(..) => ip_address,
685                 None => None,
686         }
687 }
688
689 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH> where
690                 CM::Target: ChannelMessageHandler,
691                 RM::Target: RoutingMessageHandler,
692                 OM::Target: OnionMessageHandler,
693                 L::Target: Logger,
694                 CMH::Target: CustomMessageHandler {
695         /// Constructs a new PeerManager with the given message handlers and node_id secret key
696         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
697         /// cryptographically secure random bytes.
698         ///
699         /// `current_time` is used as an always-increasing counter that survives across restarts and is
700         /// incremented irregularly internally. In general it is best to simply use the current UNIX
701         /// timestamp, however if it is not available a persistent counter that increases once per
702         /// minute should suffice.
703         pub fn new(message_handler: MessageHandler<CM, RM, OM>, our_node_secret: SecretKey, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
704                 let mut ephemeral_key_midstate = Sha256::engine();
705                 ephemeral_key_midstate.input(ephemeral_random_data);
706
707                 let mut secp_ctx = Secp256k1::signing_only();
708                 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
709                 secp_ctx.seeded_randomize(&ephemeral_hash);
710
711                 PeerManager {
712                         message_handler,
713                         peers: FairRwLock::new(HashMap::new()),
714                         node_id_to_descriptor: Mutex::new(HashMap::new()),
715                         event_processing_lock: Mutex::new(()),
716                         blocked_event_processors: AtomicBool::new(false),
717                         our_node_secret,
718                         ephemeral_key_midstate,
719                         peer_counter: AtomicCounter::new(),
720                         last_node_announcement_serial: AtomicU32::new(current_time),
721                         logger,
722                         custom_message_handler,
723                         secp_ctx,
724                 }
725         }
726
727         /// Get the list of node ids for peers which have completed the initial handshake.
728         ///
729         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
730         /// new_outbound_connection, however entries will only appear once the initial handshake has
731         /// completed and we are sure the remote peer has the private key for the given node_id.
732         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
733                 let peers = self.peers.read().unwrap();
734                 peers.values().filter_map(|peer_mutex| {
735                         let p = peer_mutex.lock().unwrap();
736                         if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
737                                 return None;
738                         }
739                         p.their_node_id
740                 }).collect()
741         }
742
743         fn get_ephemeral_key(&self) -> SecretKey {
744                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
745                 let counter = self.peer_counter.get_increment();
746                 ephemeral_hash.input(&counter.to_le_bytes());
747                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
748         }
749
750         /// Indicates a new outbound connection has been established to a node with the given node_id
751         /// and an optional remote network address.
752         ///
753         /// The remote network address adds the option to report a remote IP address back to a connecting
754         /// peer using the init message.
755         /// The user should pass the remote network address of the host they are connected to.
756         ///
757         /// If an `Err` is returned here you must disconnect the connection immediately.
758         ///
759         /// Returns a small number of bytes to send to the remote node (currently always 50).
760         ///
761         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
762         /// [`socket_disconnected()`].
763         ///
764         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
765         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
766                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
767                 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
768                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
769
770                 let mut peers = self.peers.write().unwrap();
771                 if peers.insert(descriptor, Mutex::new(Peer {
772                         channel_encryptor: peer_encryptor,
773                         their_node_id: None,
774                         their_features: None,
775                         their_net_address: remote_network_address,
776
777                         pending_outbound_buffer: LinkedList::new(),
778                         pending_outbound_buffer_first_msg_offset: 0,
779                         gossip_broadcast_buffer: LinkedList::new(),
780                         awaiting_write_event: false,
781
782                         pending_read_buffer,
783                         pending_read_buffer_pos: 0,
784                         pending_read_is_header: false,
785
786                         sync_status: InitSyncTracker::NoSyncRequested,
787
788                         msgs_sent_since_pong: 0,
789                         awaiting_pong_timer_tick_intervals: 0,
790                         received_message_since_timer_tick: false,
791                         sent_gossip_timestamp_filter: false,
792                 })).is_some() {
793                         panic!("PeerManager driver duplicated descriptors!");
794                 };
795                 Ok(res)
796         }
797
798         /// Indicates a new inbound connection has been established to a node with an optional remote
799         /// network address.
800         ///
801         /// The remote network address adds the option to report a remote IP address back to a connecting
802         /// peer using the init message.
803         /// The user should pass the remote network address of the host they are connected to.
804         ///
805         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
806         /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
807         /// the connection immediately.
808         ///
809         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
810         /// [`socket_disconnected()`].
811         ///
812         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
813         pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
814                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret, &self.secp_ctx);
815                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
816
817                 let mut peers = self.peers.write().unwrap();
818                 if peers.insert(descriptor, Mutex::new(Peer {
819                         channel_encryptor: peer_encryptor,
820                         their_node_id: None,
821                         their_features: None,
822                         their_net_address: remote_network_address,
823
824                         pending_outbound_buffer: LinkedList::new(),
825                         pending_outbound_buffer_first_msg_offset: 0,
826                         gossip_broadcast_buffer: LinkedList::new(),
827                         awaiting_write_event: false,
828
829                         pending_read_buffer,
830                         pending_read_buffer_pos: 0,
831                         pending_read_is_header: false,
832
833                         sync_status: InitSyncTracker::NoSyncRequested,
834
835                         msgs_sent_since_pong: 0,
836                         awaiting_pong_timer_tick_intervals: 0,
837                         received_message_since_timer_tick: false,
838                         sent_gossip_timestamp_filter: false,
839                 })).is_some() {
840                         panic!("PeerManager driver duplicated descriptors!");
841                 };
842                 Ok(())
843         }
844
845         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
846                 while !peer.awaiting_write_event {
847                         if peer.should_buffer_onion_message() {
848                                 if let Some(peer_node_id) = peer.their_node_id {
849                                         if let Some(next_onion_message) =
850                                                 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
851                                                         self.enqueue_message(peer, &next_onion_message);
852                                         }
853                                 }
854                         }
855                         if peer.should_buffer_gossip_broadcast() {
856                                 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
857                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..]));
858                                 }
859                         }
860                         if peer.should_buffer_gossip_backfill() {
861                                 match peer.sync_status {
862                                         InitSyncTracker::NoSyncRequested => {},
863                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
864                                                 if let Some((announce, update_a_option, update_b_option)) =
865                                                         self.message_handler.route_handler.get_next_channel_announcement(c)
866                                                 {
867                                                         self.enqueue_message(peer, &announce);
868                                                         if let Some(update_a) = update_a_option {
869                                                                 self.enqueue_message(peer, &update_a);
870                                                         }
871                                                         if let Some(update_b) = update_b_option {
872                                                                 self.enqueue_message(peer, &update_b);
873                                                         }
874                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
875                                                 } else {
876                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
877                                                 }
878                                         },
879                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
880                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
881                                                         self.enqueue_message(peer, &msg);
882                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
883                                                 } else {
884                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
885                                                 }
886                                         },
887                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
888                                         InitSyncTracker::NodesSyncing(key) => {
889                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&key)) {
890                                                         self.enqueue_message(peer, &msg);
891                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
892                                                 } else {
893                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
894                                                 }
895                                         },
896                                 }
897                         }
898                         if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
899                                 self.maybe_send_extra_ping(peer);
900                         }
901
902                         let next_buff = match peer.pending_outbound_buffer.front() {
903                                 None => return,
904                                 Some(buff) => buff,
905                         };
906
907                         let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
908                         let data_sent = descriptor.send_data(pending, peer.should_read());
909                         peer.pending_outbound_buffer_first_msg_offset += data_sent;
910                         if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
911                                 peer.pending_outbound_buffer_first_msg_offset = 0;
912                                 peer.pending_outbound_buffer.pop_front();
913                         } else {
914                                 peer.awaiting_write_event = true;
915                         }
916                 }
917         }
918
919         /// Indicates that there is room to write data to the given socket descriptor.
920         ///
921         /// May return an Err to indicate that the connection should be closed.
922         ///
923         /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
924         /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
925         /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
926         /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
927         /// sufficient!
928         ///
929         /// [`send_data`]: SocketDescriptor::send_data
930         /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
931         pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
932                 let peers = self.peers.read().unwrap();
933                 match peers.get(descriptor) {
934                         None => {
935                                 // This is most likely a simple race condition where the user found that the socket
936                                 // was writeable, then we told the user to `disconnect_socket()`, then they called
937                                 // this method. Return an error to make sure we get disconnected.
938                                 return Err(PeerHandleError { no_connection_possible: false });
939                         },
940                         Some(peer_mutex) => {
941                                 let mut peer = peer_mutex.lock().unwrap();
942                                 peer.awaiting_write_event = false;
943                                 self.do_attempt_write_data(descriptor, &mut peer);
944                         }
945                 };
946                 Ok(())
947         }
948
949         /// Indicates that data was read from the given socket descriptor.
950         ///
951         /// May return an Err to indicate that the connection should be closed.
952         ///
953         /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
954         /// Thus, however, you should call [`process_events`] after any `read_event` to generate
955         /// [`send_data`] calls to handle responses.
956         ///
957         /// If `Ok(true)` is returned, further read_events should not be triggered until a
958         /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
959         /// send buffer).
960         ///
961         /// [`send_data`]: SocketDescriptor::send_data
962         /// [`process_events`]: PeerManager::process_events
963         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
964                 match self.do_read_event(peer_descriptor, data) {
965                         Ok(res) => Ok(res),
966                         Err(e) => {
967                                 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
968                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
969                                 Err(e)
970                         }
971                 }
972         }
973
974         /// Append a message to a peer's pending outbound/write buffer
975         fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
976                 if is_gossip_msg(message.type_id()) {
977                         log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
978                 } else {
979                         log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
980                 }
981                 peer.msgs_sent_since_pong += 1;
982                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
983         }
984
985         /// Append a message to a peer's pending outbound/write gossip broadcast buffer
986         fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: Vec<u8>) {
987                 peer.msgs_sent_since_pong += 1;
988                 peer.gossip_broadcast_buffer.push_back(encoded_message);
989         }
990
991         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
992                 let mut pause_read = false;
993                 let peers = self.peers.read().unwrap();
994                 let mut msgs_to_forward = Vec::new();
995                 let mut peer_node_id = None;
996                 match peers.get(peer_descriptor) {
997                         None => {
998                                 // This is most likely a simple race condition where the user read some bytes
999                                 // from the socket, then we told the user to `disconnect_socket()`, then they
1000                                 // called this method. Return an error to make sure we get disconnected.
1001                                 return Err(PeerHandleError { no_connection_possible: false });
1002                         },
1003                         Some(peer_mutex) => {
1004                                 let mut read_pos = 0;
1005                                 while read_pos < data.len() {
1006                                         macro_rules! try_potential_handleerror {
1007                                                 ($peer: expr, $thing: expr) => {
1008                                                         match $thing {
1009                                                                 Ok(x) => x,
1010                                                                 Err(e) => {
1011                                                                         match e.action {
1012                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
1013                                                                                         //TODO: Try to push msg
1014                                                                                         log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1015                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
1016                                                                                 },
1017                                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
1018                                                                                         log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1019                                                                                         continue
1020                                                                                 },
1021                                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1022                                                                                 msgs::ErrorAction::IgnoreError => {
1023                                                                                         log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1024                                                                                         continue;
1025                                                                                 },
1026                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
1027                                                                                         log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1028                                                                                         self.enqueue_message($peer, &msg);
1029                                                                                         continue;
1030                                                                                 },
1031                                                                                 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1032                                                                                         log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1033                                                                                         self.enqueue_message($peer, &msg);
1034                                                                                         continue;
1035                                                                                 },
1036                                                                         }
1037                                                                 }
1038                                                         }
1039                                                 }
1040                                         }
1041
1042                                         let mut peer_lock = peer_mutex.lock().unwrap();
1043                                         let peer = &mut *peer_lock;
1044                                         let mut msg_to_handle = None;
1045                                         if peer_node_id.is_none() {
1046                                                 peer_node_id = peer.their_node_id.clone();
1047                                         }
1048
1049                                         assert!(peer.pending_read_buffer.len() > 0);
1050                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1051
1052                                         {
1053                                                 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1054                                                 peer.pending_read_buffer[peer.pending_read_buffer_pos..peer.pending_read_buffer_pos + data_to_copy].copy_from_slice(&data[read_pos..read_pos + data_to_copy]);
1055                                                 read_pos += data_to_copy;
1056                                                 peer.pending_read_buffer_pos += data_to_copy;
1057                                         }
1058
1059                                         if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1060                                                 peer.pending_read_buffer_pos = 0;
1061
1062                                                 macro_rules! insert_node_id {
1063                                                         () => {
1064                                                                 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap()) {
1065                                                                         hash_map::Entry::Occupied(_) => {
1066                                                                                 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
1067                                                                                 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1068                                                                                 return Err(PeerHandleError{ no_connection_possible: false })
1069                                                                         },
1070                                                                         hash_map::Entry::Vacant(entry) => {
1071                                                                                 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
1072                                                                                 entry.insert(peer_descriptor.clone())
1073                                                                         },
1074                                                                 };
1075                                                         }
1076                                                 }
1077
1078                                                 let next_step = peer.channel_encryptor.get_noise_step();
1079                                                 match next_step {
1080                                                         NextNoiseStep::ActOne => {
1081                                                                 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1082                                                                         .process_act_one_with_keys(&peer.pending_read_buffer[..],
1083                                                                                 &self.our_node_secret, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1084                                                                 peer.pending_outbound_buffer.push_back(act_two);
1085                                                                 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1086                                                         },
1087                                                         NextNoiseStep::ActTwo => {
1088                                                                 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1089                                                                         peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1090                                                                                 &self.our_node_secret, &self.secp_ctx));
1091                                                                 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1092                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1093                                                                 peer.pending_read_is_header = true;
1094
1095                                                                 peer.their_node_id = Some(their_node_id);
1096                                                                 insert_node_id!();
1097                                                                 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1098                                                                         .or(self.message_handler.route_handler.provided_init_features(&their_node_id))
1099                                                                         .or(self.message_handler.onion_message_handler.provided_init_features(&their_node_id));
1100                                                                 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1101                                                                 self.enqueue_message(peer, &resp);
1102                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1103                                                         },
1104                                                         NextNoiseStep::ActThree => {
1105                                                                 let their_node_id = try_potential_handleerror!(peer,
1106                                                                         peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1107                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1108                                                                 peer.pending_read_is_header = true;
1109                                                                 peer.their_node_id = Some(their_node_id);
1110                                                                 insert_node_id!();
1111                                                                 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1112                                                                         .or(self.message_handler.route_handler.provided_init_features(&their_node_id))
1113                                                                         .or(self.message_handler.onion_message_handler.provided_init_features(&their_node_id));
1114                                                                 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1115                                                                 self.enqueue_message(peer, &resp);
1116                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1117                                                         },
1118                                                         NextNoiseStep::NoiseComplete => {
1119                                                                 if peer.pending_read_is_header {
1120                                                                         let msg_len = try_potential_handleerror!(peer,
1121                                                                                 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1122                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1123                                                                         peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1124                                                                         if msg_len < 2 { // Need at least the message type tag
1125                                                                                 return Err(PeerHandleError{ no_connection_possible: false });
1126                                                                         }
1127                                                                         peer.pending_read_is_header = false;
1128                                                                 } else {
1129                                                                         let msg_data = try_potential_handleerror!(peer,
1130                                                                                 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1131                                                                         assert!(msg_data.len() >= 2);
1132
1133                                                                         // Reset read buffer
1134                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1135                                                                         peer.pending_read_buffer.resize(18, 0);
1136                                                                         peer.pending_read_is_header = true;
1137
1138                                                                         let mut reader = io::Cursor::new(&msg_data[..]);
1139                                                                         let message_result = wire::read(&mut reader, &*self.custom_message_handler);
1140                                                                         let message = match message_result {
1141                                                                                 Ok(x) => x,
1142                                                                                 Err(e) => {
1143                                                                                         match e {
1144                                                                                                 // Note that to avoid recursion we never call
1145                                                                                                 // `do_attempt_write_data` from here, causing
1146                                                                                                 // the messages enqueued here to not actually
1147                                                                                                 // be sent before the peer is disconnected.
1148                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1149                                                                                                         log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1150                                                                                                         continue;
1151                                                                                                 }
1152                                                                                                 (msgs::DecodeError::UnsupportedCompression, _) => {
1153                                                                                                         log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1154                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1155                                                                                                         continue;
1156                                                                                                 }
1157                                                                                                 (_, Some(ty)) if is_gossip_msg(ty) => {
1158                                                                                                         log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1159                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage {
1160                                                                                                                 channel_id: [0; 32],
1161                                                                                                                 data: format!("Unreadable/bogus gossip message of type {}", ty),
1162                                                                                                         });
1163                                                                                                         continue;
1164                                                                                                 }
1165                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, ty) => {
1166                                                                                                         log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1167                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
1168                                                                                                         return Err(PeerHandleError { no_connection_possible: false });
1169                                                                                                 }
1170                                                                                                 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }),
1171                                                                                                 (msgs::DecodeError::InvalidValue, _) => {
1172                                                                                                         log_debug!(self.logger, "Got an invalid value while deserializing message");
1173                                                                                                         return Err(PeerHandleError { no_connection_possible: false });
1174                                                                                                 }
1175                                                                                                 (msgs::DecodeError::ShortRead, _) => {
1176                                                                                                         log_debug!(self.logger, "Deserialization failed due to shortness of message");
1177                                                                                                         return Err(PeerHandleError { no_connection_possible: false });
1178                                                                                                 }
1179                                                                                                 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }),
1180                                                                                                 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }),
1181                                                                                         }
1182                                                                                 }
1183                                                                         };
1184
1185                                                                         msg_to_handle = Some(message);
1186                                                                 }
1187                                                         }
1188                                                 }
1189                                         }
1190                                         pause_read = !peer.should_read();
1191
1192                                         if let Some(message) = msg_to_handle {
1193                                                 match self.handle_message(&peer_mutex, peer_lock, message) {
1194                                                         Err(handling_error) => match handling_error {
1195                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1196                                                                 MessageHandlingError::LightningError(e) => {
1197                                                                         try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1198                                                                 },
1199                                                         },
1200                                                         Ok(Some(msg)) => {
1201                                                                 msgs_to_forward.push(msg);
1202                                                         },
1203                                                         Ok(None) => {},
1204                                                 }
1205                                         }
1206                                 }
1207                         }
1208                 }
1209
1210                 for msg in msgs_to_forward.drain(..) {
1211                         self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref());
1212                 }
1213
1214                 Ok(pause_read)
1215         }
1216
1217         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1218         /// Returns the message back if it needs to be broadcasted to all other peers.
1219         fn handle_message(
1220                 &self,
1221                 peer_mutex: &Mutex<Peer>,
1222                 mut peer_lock: MutexGuard<Peer>,
1223                 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1224         ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1225                 let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages");
1226                 peer_lock.received_message_since_timer_tick = true;
1227
1228                 // Need an Init as first message
1229                 if let wire::Message::Init(msg) = message {
1230                         if msg.features.requires_unknown_bits() {
1231                                 log_debug!(self.logger, "Peer features required unknown version bits");
1232                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1233                         }
1234                         if peer_lock.their_features.is_some() {
1235                                 return Err(PeerHandleError{ no_connection_possible: false }.into());
1236                         }
1237
1238                         log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1239
1240                         // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1241                         if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1242                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1243                         }
1244
1245                         if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg) {
1246                                 log_debug!(self.logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1247                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1248                         }
1249                         if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg) {
1250                                 log_debug!(self.logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1251                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1252                         }
1253                         if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg) {
1254                                 log_debug!(self.logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1255                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1256                         }
1257
1258                         peer_lock.their_features = Some(msg.features);
1259                         return Ok(None);
1260                 } else if peer_lock.their_features.is_none() {
1261                         log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1262                         return Err(PeerHandleError{ no_connection_possible: false }.into());
1263                 }
1264
1265                 if let wire::Message::GossipTimestampFilter(_msg) = message {
1266                         // When supporting gossip messages, start inital gossip sync only after we receive
1267                         // a GossipTimestampFilter
1268                         if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1269                                 !peer_lock.sent_gossip_timestamp_filter {
1270                                 peer_lock.sent_gossip_timestamp_filter = true;
1271                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1272                         }
1273                         return Ok(None);
1274                 }
1275
1276                 let their_features = peer_lock.their_features.clone();
1277                 mem::drop(peer_lock);
1278
1279                 if is_gossip_msg(message.type_id()) {
1280                         log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1281                 } else {
1282                         log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1283                 }
1284
1285                 let mut should_forward = None;
1286
1287                 match message {
1288                         // Setup and Control messages:
1289                         wire::Message::Init(_) => {
1290                                 // Handled above
1291                         },
1292                         wire::Message::GossipTimestampFilter(_) => {
1293                                 // Handled above
1294                         },
1295                         wire::Message::Error(msg) => {
1296                                 let mut data_is_printable = true;
1297                                 for b in msg.data.bytes() {
1298                                         if b < 32 || b > 126 {
1299                                                 data_is_printable = false;
1300                                                 break;
1301                                         }
1302                                 }
1303
1304                                 if data_is_printable {
1305                                         log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1306                                 } else {
1307                                         log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1308                                 }
1309                                 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1310                                 if msg.channel_id == [0; 32] {
1311                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
1312                                 }
1313                         },
1314                         wire::Message::Warning(msg) => {
1315                                 let mut data_is_printable = true;
1316                                 for b in msg.data.bytes() {
1317                                         if b < 32 || b > 126 {
1318                                                 data_is_printable = false;
1319                                                 break;
1320                                         }
1321                                 }
1322
1323                                 if data_is_printable {
1324                                         log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1325                                 } else {
1326                                         log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1327                                 }
1328                         },
1329
1330                         wire::Message::Ping(msg) => {
1331                                 if msg.ponglen < 65532 {
1332                                         let resp = msgs::Pong { byteslen: msg.ponglen };
1333                                         self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1334                                 }
1335                         },
1336                         wire::Message::Pong(_msg) => {
1337                                 let mut peer_lock = peer_mutex.lock().unwrap();
1338                                 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1339                                 peer_lock.msgs_sent_since_pong = 0;
1340                         },
1341
1342                         // Channel messages:
1343                         wire::Message::OpenChannel(msg) => {
1344                                 self.message_handler.chan_handler.handle_open_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1345                         },
1346                         wire::Message::AcceptChannel(msg) => {
1347                                 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1348                         },
1349
1350                         wire::Message::FundingCreated(msg) => {
1351                                 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1352                         },
1353                         wire::Message::FundingSigned(msg) => {
1354                                 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1355                         },
1356                         wire::Message::ChannelReady(msg) => {
1357                                 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1358                         },
1359
1360                         wire::Message::Shutdown(msg) => {
1361                                 self.message_handler.chan_handler.handle_shutdown(&their_node_id, their_features.as_ref().unwrap(), &msg);
1362                         },
1363                         wire::Message::ClosingSigned(msg) => {
1364                                 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1365                         },
1366
1367                         // Commitment messages:
1368                         wire::Message::UpdateAddHTLC(msg) => {
1369                                 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1370                         },
1371                         wire::Message::UpdateFulfillHTLC(msg) => {
1372                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1373                         },
1374                         wire::Message::UpdateFailHTLC(msg) => {
1375                                 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1376                         },
1377                         wire::Message::UpdateFailMalformedHTLC(msg) => {
1378                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1379                         },
1380
1381                         wire::Message::CommitmentSigned(msg) => {
1382                                 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1383                         },
1384                         wire::Message::RevokeAndACK(msg) => {
1385                                 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1386                         },
1387                         wire::Message::UpdateFee(msg) => {
1388                                 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1389                         },
1390                         wire::Message::ChannelReestablish(msg) => {
1391                                 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1392                         },
1393
1394                         // Routing messages:
1395                         wire::Message::AnnouncementSignatures(msg) => {
1396                                 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1397                         },
1398                         wire::Message::ChannelAnnouncement(msg) => {
1399                                 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1400                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1401                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1402                                 }
1403                         },
1404                         wire::Message::NodeAnnouncement(msg) => {
1405                                 if self.message_handler.route_handler.handle_node_announcement(&msg)
1406                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1407                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
1408                                 }
1409                         },
1410                         wire::Message::ChannelUpdate(msg) => {
1411                                 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1412                                 if self.message_handler.route_handler.handle_channel_update(&msg)
1413                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1414                                         should_forward = Some(wire::Message::ChannelUpdate(msg));
1415                                 }
1416                         },
1417                         wire::Message::QueryShortChannelIds(msg) => {
1418                                 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1419                         },
1420                         wire::Message::ReplyShortChannelIdsEnd(msg) => {
1421                                 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1422                         },
1423                         wire::Message::QueryChannelRange(msg) => {
1424                                 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1425                         },
1426                         wire::Message::ReplyChannelRange(msg) => {
1427                                 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1428                         },
1429
1430                         // Onion message:
1431                         wire::Message::OnionMessage(msg) => {
1432                                 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1433                         },
1434
1435                         // Unknown messages:
1436                         wire::Message::Unknown(type_id) if message.is_even() => {
1437                                 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1438                                 // Fail the channel if message is an even, unknown type as per BOLT #1.
1439                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1440                         },
1441                         wire::Message::Unknown(type_id) => {
1442                                 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1443                         },
1444                         wire::Message::Custom(custom) => {
1445                                 self.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1446                         },
1447                 };
1448                 Ok(should_forward)
1449         }
1450
1451         fn forward_broadcast_msg(&self, peers: &HashMap<Descriptor, Mutex<Peer>>, msg: &wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>, except_node: Option<&PublicKey>) {
1452                 match msg {
1453                         wire::Message::ChannelAnnouncement(ref msg) => {
1454                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1455                                 let encoded_msg = encode_msg!(msg);
1456
1457                                 for (_, peer_mutex) in peers.iter() {
1458                                         let mut peer = peer_mutex.lock().unwrap();
1459                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1460                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1461                                                 continue
1462                                         }
1463                                         if peer.buffer_full_drop_gossip_broadcast() {
1464                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1465                                                 continue;
1466                                         }
1467                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1468                                            peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1469                                                 continue;
1470                                         }
1471                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1472                                                 continue;
1473                                         }
1474                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1475                                 }
1476                         },
1477                         wire::Message::NodeAnnouncement(ref msg) => {
1478                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1479                                 let encoded_msg = encode_msg!(msg);
1480
1481                                 for (_, peer_mutex) in peers.iter() {
1482                                         let mut peer = peer_mutex.lock().unwrap();
1483                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1484                                                         !peer.should_forward_node_announcement(msg.contents.node_id) {
1485                                                 continue
1486                                         }
1487                                         if peer.buffer_full_drop_gossip_broadcast() {
1488                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1489                                                 continue;
1490                                         }
1491                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1492                                                 continue;
1493                                         }
1494                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1495                                                 continue;
1496                                         }
1497                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1498                                 }
1499                         },
1500                         wire::Message::ChannelUpdate(ref msg) => {
1501                                 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1502                                 let encoded_msg = encode_msg!(msg);
1503
1504                                 for (_, peer_mutex) in peers.iter() {
1505                                         let mut peer = peer_mutex.lock().unwrap();
1506                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1507                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1508                                                 continue
1509                                         }
1510                                         if peer.buffer_full_drop_gossip_broadcast() {
1511                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1512                                                 continue;
1513                                         }
1514                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1515                                                 continue;
1516                                         }
1517                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1518                                 }
1519                         },
1520                         _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1521                 }
1522         }
1523
1524         /// Checks for any events generated by our handlers and processes them. Includes sending most
1525         /// response messages as well as messages generated by calls to handler functions directly (eg
1526         /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1527         ///
1528         /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1529         /// issues!
1530         ///
1531         /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1532         /// or one of the other clients provided in our language bindings.
1533         ///
1534         /// Note that if there are any other calls to this function waiting on lock(s) this may return
1535         /// without doing any work. All available events that need handling will be handled before the
1536         /// other calls return.
1537         ///
1538         /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1539         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1540         /// [`send_data`]: SocketDescriptor::send_data
1541         pub fn process_events(&self) {
1542                 let mut _single_processor_lock = self.event_processing_lock.try_lock();
1543                 if _single_processor_lock.is_err() {
1544                         // While we could wake the older sleeper here with a CV and make more even waiting
1545                         // times, that would be a lot of overengineering for a simple "reduce total waiter
1546                         // count" goal.
1547                         match self.blocked_event_processors.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) {
1548                                 Err(val) => {
1549                                         debug_assert!(val, "compare_exchange failed spuriously?");
1550                                         return;
1551                                 },
1552                                 Ok(val) => {
1553                                         debug_assert!(!val, "compare_exchange succeeded spuriously?");
1554                                         // We're the only waiter, as the running process_events may have emptied the
1555                                         // pending events "long" ago and there are new events for us to process, wait until
1556                                         // its done and process any leftover events before returning.
1557                                         _single_processor_lock = Ok(self.event_processing_lock.lock().unwrap());
1558                                         self.blocked_event_processors.store(false, Ordering::Release);
1559                                 }
1560                         }
1561                 }
1562
1563                 let mut peers_to_disconnect = HashMap::new();
1564                 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1565                 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1566
1567                 {
1568                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
1569                         // buffer by doing things like announcing channels on another node. We should be willing to
1570                         // drop optional-ish messages when send buffers get full!
1571
1572                         let peers_lock = self.peers.read().unwrap();
1573                         let peers = &*peers_lock;
1574                         macro_rules! get_peer_for_forwarding {
1575                                 ($node_id: expr) => {
1576                                         {
1577                                                 if peers_to_disconnect.get($node_id).is_some() {
1578                                                         // If we've "disconnected" this peer, do not send to it.
1579                                                         continue;
1580                                                 }
1581                                                 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1582                                                 match descriptor_opt {
1583                                                         Some(descriptor) => match peers.get(&descriptor) {
1584                                                                 Some(peer_mutex) => {
1585                                                                         let peer_lock = peer_mutex.lock().unwrap();
1586                                                                         if peer_lock.their_features.is_none() {
1587                                                                                 continue;
1588                                                                         }
1589                                                                         peer_lock
1590                                                                 },
1591                                                                 None => {
1592                                                                         debug_assert!(false, "Inconsistent peers set state!");
1593                                                                         continue;
1594                                                                 }
1595                                                         },
1596                                                         None => {
1597                                                                 continue;
1598                                                         },
1599                                                 }
1600                                         }
1601                                 }
1602                         }
1603                         for event in events_generated.drain(..) {
1604                                 match event {
1605                                         MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1606                                                 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1607                                                                 log_pubkey!(node_id),
1608                                                                 log_bytes!(msg.temporary_channel_id));
1609                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1610                                         },
1611                                         MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1612                                                 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1613                                                                 log_pubkey!(node_id),
1614                                                                 log_bytes!(msg.temporary_channel_id));
1615                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1616                                         },
1617                                         MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1618                                                 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1619                                                                 log_pubkey!(node_id),
1620                                                                 log_bytes!(msg.temporary_channel_id),
1621                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1622                                                 // TODO: If the peer is gone we should generate a DiscardFunding event
1623                                                 // indicating to the wallet that they should just throw away this funding transaction
1624                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1625                                         },
1626                                         MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1627                                                 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1628                                                                 log_pubkey!(node_id),
1629                                                                 log_bytes!(msg.channel_id));
1630                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1631                                         },
1632                                         MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1633                                                 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1634                                                                 log_pubkey!(node_id),
1635                                                                 log_bytes!(msg.channel_id));
1636                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1637                                         },
1638                                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1639                                                 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1640                                                                 log_pubkey!(node_id),
1641                                                                 log_bytes!(msg.channel_id));
1642                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1643                                         },
1644                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1645                                                 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1646                                                                 log_pubkey!(node_id),
1647                                                                 update_add_htlcs.len(),
1648                                                                 update_fulfill_htlcs.len(),
1649                                                                 update_fail_htlcs.len(),
1650                                                                 log_bytes!(commitment_signed.channel_id));
1651                                                 let mut peer = get_peer_for_forwarding!(node_id);
1652                                                 for msg in update_add_htlcs {
1653                                                         self.enqueue_message(&mut *peer, msg);
1654                                                 }
1655                                                 for msg in update_fulfill_htlcs {
1656                                                         self.enqueue_message(&mut *peer, msg);
1657                                                 }
1658                                                 for msg in update_fail_htlcs {
1659                                                         self.enqueue_message(&mut *peer, msg);
1660                                                 }
1661                                                 for msg in update_fail_malformed_htlcs {
1662                                                         self.enqueue_message(&mut *peer, msg);
1663                                                 }
1664                                                 if let &Some(ref msg) = update_fee {
1665                                                         self.enqueue_message(&mut *peer, msg);
1666                                                 }
1667                                                 self.enqueue_message(&mut *peer, commitment_signed);
1668                                         },
1669                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1670                                                 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1671                                                                 log_pubkey!(node_id),
1672                                                                 log_bytes!(msg.channel_id));
1673                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1674                                         },
1675                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1676                                                 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1677                                                                 log_pubkey!(node_id),
1678                                                                 log_bytes!(msg.channel_id));
1679                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1680                                         },
1681                                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1682                                                 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1683                                                                 log_pubkey!(node_id),
1684                                                                 log_bytes!(msg.channel_id));
1685                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1686                                         },
1687                                         MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1688                                                 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1689                                                                 log_pubkey!(node_id),
1690                                                                 log_bytes!(msg.channel_id));
1691                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1692                                         },
1693                                         MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
1694                                                 log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
1695                                                                 log_pubkey!(node_id),
1696                                                                 msg.contents.short_channel_id);
1697                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1698                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
1699                                         },
1700                                         MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1701                                                 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1702                                                 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1703                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1704                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1705                                                         _ => {},
1706                                                 }
1707                                                 match self.message_handler.route_handler.handle_channel_update(&update_msg) {
1708                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1709                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None),
1710                                                         _ => {},
1711                                                 }
1712                                         },
1713                                         MessageSendEvent::BroadcastChannelUpdate { msg } => {
1714                                                 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1715                                                 match self.message_handler.route_handler.handle_channel_update(&msg) {
1716                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1717                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1718                                                         _ => {},
1719                                                 }
1720                                         },
1721                                         MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1722                                                 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1723                                                                 log_pubkey!(node_id), msg.contents.short_channel_id);
1724                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1725                                         },
1726                                         MessageSendEvent::HandleError { ref node_id, ref action } => {
1727                                                 match *action {
1728                                                         msgs::ErrorAction::DisconnectPeer { ref msg } => {
1729                                                                 // We do not have the peers write lock, so we just store that we're
1730                                                                 // about to disconenct the peer and do it after we finish
1731                                                                 // processing most messages.
1732                                                                 peers_to_disconnect.insert(*node_id, msg.clone());
1733                                                         },
1734                                                         msgs::ErrorAction::IgnoreAndLog(level) => {
1735                                                                 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1736                                                         },
1737                                                         msgs::ErrorAction::IgnoreDuplicateGossip => {},
1738                                                         msgs::ErrorAction::IgnoreError => {
1739                                                                 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1740                                                         },
1741                                                         msgs::ErrorAction::SendErrorMessage { ref msg } => {
1742                                                                 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1743                                                                                 log_pubkey!(node_id),
1744                                                                                 msg.data);
1745                                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1746                                                         },
1747                                                         msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1748                                                                 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1749                                                                                 log_pubkey!(node_id),
1750                                                                                 msg.data);
1751                                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1752                                                         },
1753                                                 }
1754                                         },
1755                                         MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1756                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1757                                         },
1758                                         MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1759                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1760                                         }
1761                                         MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1762                                                 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1763                                                         log_pubkey!(node_id),
1764                                                         msg.short_channel_ids.len(),
1765                                                         msg.first_blocknum,
1766                                                         msg.number_of_blocks,
1767                                                         msg.sync_complete);
1768                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1769                                         }
1770                                         MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
1771                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1772                                         }
1773                                 }
1774                         }
1775
1776                         for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1777                                 if peers_to_disconnect.get(&node_id).is_some() { continue; }
1778                                 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
1779                         }
1780
1781                         for (descriptor, peer_mutex) in peers.iter() {
1782                                 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer_mutex.lock().unwrap());
1783                         }
1784                 }
1785                 if !peers_to_disconnect.is_empty() {
1786                         let mut peers_lock = self.peers.write().unwrap();
1787                         let peers = &mut *peers_lock;
1788                         for (node_id, msg) in peers_to_disconnect.drain() {
1789                                 // Note that since we are holding the peers *write* lock we can
1790                                 // remove from node_id_to_descriptor immediately (as no other
1791                                 // thread can be holding the peer lock if we have the global write
1792                                 // lock).
1793
1794                                 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1795                                         if let Some(peer_mutex) = peers.remove(&descriptor) {
1796                                                 if let Some(msg) = msg {
1797                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1798                                                                         log_pubkey!(node_id),
1799                                                                         msg.data);
1800                                                         let mut peer = peer_mutex.lock().unwrap();
1801                                                         self.enqueue_message(&mut *peer, &msg);
1802                                                         // This isn't guaranteed to work, but if there is enough free
1803                                                         // room in the send buffer, put the error message there...
1804                                                         self.do_attempt_write_data(&mut descriptor, &mut *peer);
1805                                                 } else {
1806                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1807                                                 }
1808                                         }
1809                                         descriptor.disconnect_socket();
1810                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1811                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1812                                 }
1813                         }
1814                 }
1815         }
1816
1817         /// Indicates that the given socket descriptor's connection is now closed.
1818         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1819                 self.disconnect_event_internal(descriptor, false);
1820         }
1821
1822         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1823                 let mut peers = self.peers.write().unwrap();
1824                 let peer_option = peers.remove(descriptor);
1825                 match peer_option {
1826                         None => {
1827                                 // This is most likely a simple race condition where the user found that the socket
1828                                 // was disconnected, then we told the user to `disconnect_socket()`, then they
1829                                 // called this method. Either way we're disconnected, return.
1830                         },
1831                         Some(peer_lock) => {
1832                                 let peer = peer_lock.lock().unwrap();
1833                                 if let Some(node_id) = peer.their_node_id {
1834                                         log_trace!(self.logger,
1835                                                 "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1836                                                 log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1837                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1838                                         self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1839                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1840                                 }
1841                         }
1842                 };
1843         }
1844
1845         /// Disconnect a peer given its node id.
1846         ///
1847         /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1848         /// force-closing any channels we have with it.
1849         ///
1850         /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1851         /// peer. Thus, be very careful about reentrancy issues.
1852         ///
1853         /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1854         pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1855                 let mut peers_lock = self.peers.write().unwrap();
1856                 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1857                         log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1858                         peers_lock.remove(&descriptor);
1859                         self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1860                         self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1861                         descriptor.disconnect_socket();
1862                 }
1863         }
1864
1865         /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1866         /// an indication that TCP sockets have stalled even if we weren't around to time them out
1867         /// using regular ping/pongs.
1868         pub fn disconnect_all_peers(&self) {
1869                 let mut peers_lock = self.peers.write().unwrap();
1870                 self.node_id_to_descriptor.lock().unwrap().clear();
1871                 let peers = &mut *peers_lock;
1872                 for (mut descriptor, peer) in peers.drain() {
1873                         if let Some(node_id) = peer.lock().unwrap().their_node_id {
1874                                 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1875                                 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1876                                 self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1877                         }
1878                         descriptor.disconnect_socket();
1879                 }
1880         }
1881
1882         /// This is called when we're blocked on sending additional gossip messages until we receive a
1883         /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1884         /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1885         fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1886                 if peer.awaiting_pong_timer_tick_intervals == 0 {
1887                         peer.awaiting_pong_timer_tick_intervals = -1;
1888                         let ping = msgs::Ping {
1889                                 ponglen: 0,
1890                                 byteslen: 64,
1891                         };
1892                         self.enqueue_message(peer, &ping);
1893                 }
1894         }
1895
1896         /// Send pings to each peer and disconnect those which did not respond to the last round of
1897         /// pings.
1898         ///
1899         /// This may be called on any timescale you want, however, roughly once every ten seconds is
1900         /// preferred. The call rate determines both how often we send a ping to our peers and how much
1901         /// time they have to respond before we disconnect them.
1902         ///
1903         /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1904         /// issues!
1905         ///
1906         /// [`send_data`]: SocketDescriptor::send_data
1907         pub fn timer_tick_occurred(&self) {
1908                 let mut descriptors_needing_disconnect = Vec::new();
1909                 {
1910                         let peers_lock = self.peers.read().unwrap();
1911
1912                         for (descriptor, peer_mutex) in peers_lock.iter() {
1913                                 let mut peer = peer_mutex.lock().unwrap();
1914                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1915                                         // The peer needs to complete its handshake before we can exchange messages. We
1916                                         // give peers one timer tick to complete handshake, reusing
1917                                         // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1918                                         // for handshake completion.
1919                                         if peer.awaiting_pong_timer_tick_intervals != 0 {
1920                                                 descriptors_needing_disconnect.push(descriptor.clone());
1921                                         } else {
1922                                                 peer.awaiting_pong_timer_tick_intervals = 1;
1923                                         }
1924                                         continue;
1925                                 }
1926
1927                                 if peer.awaiting_pong_timer_tick_intervals == -1 {
1928                                         // Magic value set in `maybe_send_extra_ping`.
1929                                         peer.awaiting_pong_timer_tick_intervals = 1;
1930                                         peer.received_message_since_timer_tick = false;
1931                                         continue;
1932                                 }
1933
1934                                 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1935                                         || peer.awaiting_pong_timer_tick_intervals as u64 >
1936                                                 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
1937                                 {
1938                                         descriptors_needing_disconnect.push(descriptor.clone());
1939                                         continue;
1940                                 }
1941                                 peer.received_message_since_timer_tick = false;
1942
1943                                 if peer.awaiting_pong_timer_tick_intervals > 0 {
1944                                         peer.awaiting_pong_timer_tick_intervals += 1;
1945                                         continue;
1946                                 }
1947
1948                                 peer.awaiting_pong_timer_tick_intervals = 1;
1949                                 let ping = msgs::Ping {
1950                                         ponglen: 0,
1951                                         byteslen: 64,
1952                                 };
1953                                 self.enqueue_message(&mut *peer, &ping);
1954                                 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1955                         }
1956                 }
1957
1958                 if !descriptors_needing_disconnect.is_empty() {
1959                         {
1960                                 let mut peers_lock = self.peers.write().unwrap();
1961                                 for descriptor in descriptors_needing_disconnect.iter() {
1962                                         if let Some(peer) = peers_lock.remove(descriptor) {
1963                                                 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1964                                                         log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1965                                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1966                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1967                                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1968                                                 }
1969                                         }
1970                                 }
1971                         }
1972
1973                         for mut descriptor in descriptors_needing_disconnect.drain(..) {
1974                                 descriptor.disconnect_socket();
1975                         }
1976                 }
1977         }
1978
1979         #[allow(dead_code)]
1980         // Messages of up to 64KB should never end up more than half full with addresses, as that would
1981         // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
1982         // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1983         // message...
1984         const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1985         #[deny(const_err)]
1986         #[allow(dead_code)]
1987         // ...by failing to compile if the number of addresses that would be half of a message is
1988         // smaller than 100:
1989         const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
1990
1991         /// Generates a signed node_announcement from the given arguments, sending it to all connected
1992         /// peers. Note that peers will likely ignore this message unless we have at least one public
1993         /// channel which has at least six confirmations on-chain.
1994         ///
1995         /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
1996         /// node to humans. They carry no in-protocol meaning.
1997         ///
1998         /// `addresses` represent the set (possibly empty) of socket addresses on which this node
1999         /// accepts incoming connections. These will be included in the node_announcement, publicly
2000         /// tying these addresses together and to this node. If you wish to preserve user privacy,
2001         /// addresses should likely contain only Tor Onion addresses.
2002         ///
2003         /// Panics if `addresses` is absurdly large (more than 100).
2004         ///
2005         /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2006         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
2007                 if addresses.len() > 100 {
2008                         panic!("More than half the message size was taken up by public addresses!");
2009                 }
2010
2011                 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2012                 // addresses be sorted for future compatibility.
2013                 addresses.sort_by_key(|addr| addr.get_id());
2014
2015                 let features = self.message_handler.chan_handler.provided_node_features()
2016                         .or(self.message_handler.route_handler.provided_node_features())
2017                         .or(self.message_handler.onion_message_handler.provided_node_features());
2018                 let announcement = msgs::UnsignedNodeAnnouncement {
2019                         features,
2020                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2021                         node_id: PublicKey::from_secret_key(&self.secp_ctx, &self.our_node_secret),
2022                         rgb, alias, addresses,
2023                         excess_address_data: Vec::new(),
2024                         excess_data: Vec::new(),
2025                 };
2026                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2027                 let node_announce_sig = sign(&self.secp_ctx, &msghash, &self.our_node_secret);
2028
2029                 let msg = msgs::NodeAnnouncement {
2030                         signature: node_announce_sig,
2031                         contents: announcement
2032                 };
2033
2034                 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2035                 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2036                 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2037         }
2038 }
2039
2040 fn is_gossip_msg(type_id: u16) -> bool {
2041         match type_id {
2042                 msgs::ChannelAnnouncement::TYPE |
2043                 msgs::ChannelUpdate::TYPE |
2044                 msgs::NodeAnnouncement::TYPE |
2045                 msgs::QueryChannelRange::TYPE |
2046                 msgs::ReplyChannelRange::TYPE |
2047                 msgs::QueryShortChannelIds::TYPE |
2048                 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2049                 _ => false
2050         }
2051 }
2052
2053 #[cfg(test)]
2054 mod tests {
2055         use crate::ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2056         use crate::ln::{msgs, wire};
2057         use crate::ln::msgs::NetAddress;
2058         use crate::util::events;
2059         use crate::util::test_utils;
2060
2061         use bitcoin::secp256k1::Secp256k1;
2062         use bitcoin::secp256k1::{SecretKey, PublicKey};
2063
2064         use crate::prelude::*;
2065         use crate::sync::{Arc, Mutex};
2066         use core::sync::atomic::Ordering;
2067
2068         #[derive(Clone)]
2069         struct FileDescriptor {
2070                 fd: u16,
2071                 outbound_data: Arc<Mutex<Vec<u8>>>,
2072         }
2073         impl PartialEq for FileDescriptor {
2074                 fn eq(&self, other: &Self) -> bool {
2075                         self.fd == other.fd
2076                 }
2077         }
2078         impl Eq for FileDescriptor { }
2079         impl core::hash::Hash for FileDescriptor {
2080                 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2081                         self.fd.hash(hasher)
2082                 }
2083         }
2084
2085         impl SocketDescriptor for FileDescriptor {
2086                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2087                         self.outbound_data.lock().unwrap().extend_from_slice(data);
2088                         data.len()
2089                 }
2090
2091                 fn disconnect_socket(&mut self) {}
2092         }
2093
2094         struct PeerManagerCfg {
2095                 chan_handler: test_utils::TestChannelMessageHandler,
2096                 routing_handler: test_utils::TestRoutingMessageHandler,
2097                 logger: test_utils::TestLogger,
2098         }
2099
2100         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2101                 let mut cfgs = Vec::new();
2102                 for _ in 0..peer_count {
2103                         cfgs.push(
2104                                 PeerManagerCfg{
2105                                         chan_handler: test_utils::TestChannelMessageHandler::new(),
2106                                         logger: test_utils::TestLogger::new(),
2107                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2108                                 }
2109                         );
2110                 }
2111
2112                 cfgs
2113         }
2114
2115         fn create_network<'a>(peer_count: usize, cfgs: &'a Vec<PeerManagerCfg>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>> {
2116                 let mut peers = Vec::new();
2117                 for i in 0..peer_count {
2118                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2119                         let ephemeral_bytes = [i as u8; 32];
2120                         let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler, onion_message_handler: IgnoringMessageHandler {} };
2121                         let peer = PeerManager::new(msg_handler, node_secret, 0, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
2122                         peers.push(peer);
2123                 }
2124
2125                 peers
2126         }
2127
2128         fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>) -> (FileDescriptor, FileDescriptor) {
2129                 let secp_ctx = Secp256k1::new();
2130                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
2131                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2132                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2133                 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2134                 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
2135                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2136                 peer_a.process_events();
2137
2138                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2139                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2140
2141                 peer_b.process_events();
2142                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2143                 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2144
2145                 peer_a.process_events();
2146                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2147                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2148
2149                 (fd_a.clone(), fd_b.clone())
2150         }
2151
2152         #[test]
2153         fn test_disconnect_peer() {
2154                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2155                 // push a DisconnectPeer event to remove the node flagged by id
2156                 let cfgs = create_peermgr_cfgs(2);
2157                 let chan_handler = test_utils::TestChannelMessageHandler::new();
2158                 let mut peers = create_network(2, &cfgs);
2159                 establish_connection(&peers[0], &peers[1]);
2160                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2161
2162                 let secp_ctx = Secp256k1::new();
2163                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2164
2165                 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2166                         node_id: their_id,
2167                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
2168                 });
2169                 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
2170                 peers[0].message_handler.chan_handler = &chan_handler;
2171
2172                 peers[0].process_events();
2173                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2174         }
2175
2176         #[test]
2177         fn test_send_simple_msg() {
2178                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2179                 // push a message from one peer to another.
2180                 let cfgs = create_peermgr_cfgs(2);
2181                 let a_chan_handler = test_utils::TestChannelMessageHandler::new();
2182                 let b_chan_handler = test_utils::TestChannelMessageHandler::new();
2183                 let mut peers = create_network(2, &cfgs);
2184                 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2185                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2186
2187                 let secp_ctx = Secp256k1::new();
2188                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2189
2190                 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2191                 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2192                         node_id: their_id, msg: msg.clone()
2193                 });
2194                 peers[0].message_handler.chan_handler = &a_chan_handler;
2195
2196                 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2197                 peers[1].message_handler.chan_handler = &b_chan_handler;
2198
2199                 peers[0].process_events();
2200
2201                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2202                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2203         }
2204
2205         #[test]
2206         fn test_disconnect_all_peer() {
2207                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2208                 // then calls disconnect_all_peers
2209                 let cfgs = create_peermgr_cfgs(2);
2210                 let peers = create_network(2, &cfgs);
2211                 establish_connection(&peers[0], &peers[1]);
2212                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2213
2214                 peers[0].disconnect_all_peers();
2215                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2216         }
2217
2218         #[test]
2219         fn test_timer_tick_occurred() {
2220                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2221                 let cfgs = create_peermgr_cfgs(2);
2222                 let peers = create_network(2, &cfgs);
2223                 establish_connection(&peers[0], &peers[1]);
2224                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2225
2226                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2227                 peers[0].timer_tick_occurred();
2228                 peers[0].process_events();
2229                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2230
2231                 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2232                 peers[0].timer_tick_occurred();
2233                 peers[0].process_events();
2234                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2235         }
2236
2237         #[test]
2238         fn test_do_attempt_write_data() {
2239                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2240                 let cfgs = create_peermgr_cfgs(2);
2241                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2242                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2243                 let peers = create_network(2, &cfgs);
2244
2245                 // By calling establish_connect, we trigger do_attempt_write_data between
2246                 // the peers. Previously this function would mistakenly enter an infinite loop
2247                 // when there were more channel messages available than could fit into a peer's
2248                 // buffer. This issue would now be detected by this test (because we use custom
2249                 // RoutingMessageHandlers that intentionally return more channel messages
2250                 // than can fit into a peer's buffer).
2251                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2252
2253                 // Make each peer to read the messages that the other peer just wrote to them. Note that
2254                 // due to the max-message-before-ping limits this may take a few iterations to complete.
2255                 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2256                         peers[1].process_events();
2257                         let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2258                         assert!(!a_read_data.is_empty());
2259
2260                         peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2261                         peers[0].process_events();
2262
2263                         let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2264                         assert!(!b_read_data.is_empty());
2265                         peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2266
2267                         peers[0].process_events();
2268                         assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2269                 }
2270
2271                 // Check that each peer has received the expected number of channel updates and channel
2272                 // announcements.
2273                 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2274                 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2275                 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2276                 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2277         }
2278
2279         #[test]
2280         fn test_handshake_timeout() {
2281                 // Tests that we time out a peer still waiting on handshake completion after a full timer
2282                 // tick.
2283                 let cfgs = create_peermgr_cfgs(2);
2284                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2285                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2286                 let peers = create_network(2, &cfgs);
2287
2288                 let secp_ctx = Secp256k1::new();
2289                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
2290                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2291                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2292                 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2293                 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
2294
2295                 // If we get a single timer tick before completion, that's fine
2296                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2297                 peers[0].timer_tick_occurred();
2298                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2299
2300                 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
2301                 peers[0].process_events();
2302                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2303                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2304                 peers[1].process_events();
2305
2306                 // ...but if we get a second timer tick, we should disconnect the peer
2307                 peers[0].timer_tick_occurred();
2308                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2309
2310                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2311                 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
2312         }
2313
2314         #[test]
2315         fn test_filter_addresses(){
2316                 // Tests the filter_addresses function.
2317
2318                 // For (10/8)
2319                 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
2320                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2321                 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
2322                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2323                 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
2324                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2325
2326                 // For (0/8)
2327                 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
2328                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2329                 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
2330                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2331                 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
2332                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2333
2334                 // For (100.64/10)
2335                 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
2336                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2337                 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
2338                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2339                 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
2340                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2341
2342                 // For (127/8)
2343                 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
2344                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2345                 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
2346                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2347                 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
2348                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2349
2350                 // For (169.254/16)
2351                 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
2352                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2353                 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2354                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2355                 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2356                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2357
2358                 // For (172.16/12)
2359                 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2360                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2361                 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2362                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2363                 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2364                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2365
2366                 // For (192.168/16)
2367                 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2368                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2369                 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2370                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2371                 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2372                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2373
2374                 // For (192.88.99/24)
2375                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2376                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2377                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2378                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2379                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2380                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2381
2382                 // For other IPv4 addresses
2383                 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2384                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2385                 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2386                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2387                 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2388                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2389
2390                 // For (2000::/3)
2391                 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2392                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2393                 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2394                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2395                 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2396                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2397
2398                 // For other IPv6 addresses
2399                 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2400                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2401                 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2402                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2403                 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2404                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2405
2406                 // For (None)
2407                 assert_eq!(filter_addresses(None), None);
2408         }
2409 }