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