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