Merge pull request #2637 from Sharmalm/2348
[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::blockdata::constants::ChainHash;
19 use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
20
21 use crate::sign::{KeysManager, NodeSigner, Recipient};
22 use crate::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
23 use crate::ln::ChannelId;
24 use crate::ln::features::{InitFeatures, NodeFeatures};
25 use crate::ln::msgs;
26 use crate::ln::msgs::{ChannelMessageHandler, LightningError, SocketAddress, OnionMessageHandler, RoutingMessageHandler};
27 #[cfg(not(c_bindings))]
28 use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
29 use crate::util::ser::{VecWriter, Writeable, Writer};
30 use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor, NextNoiseStep, MessageBuf, MSG_BUF_ALLOC_SIZE};
31 use crate::ln::wire;
32 use crate::ln::wire::{Encode, Type};
33 #[cfg(not(c_bindings))]
34 use crate::onion_message::{SimpleArcOnionMessenger, SimpleRefOnionMessenger};
35 use crate::onion_message::{CustomOnionMessageHandler, OffersMessage, OffersMessageHandler, OnionMessageContents, PendingOnionMessage};
36 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, NodeAlias};
37 use crate::util::atomic_counter::AtomicCounter;
38 use crate::util::logger::{Logger, WithContext};
39 use crate::util::string::PrintableString;
40
41 use crate::prelude::*;
42 use crate::io;
43 use alloc::collections::VecDeque;
44 use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock};
45 use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering};
46 use core::{cmp, hash, fmt, mem};
47 use core::ops::Deref;
48 use core::convert::Infallible;
49 #[cfg(feature = "std")] use std::error;
50
51 use bitcoin::hashes::sha256::Hash as Sha256;
52 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
53 use bitcoin::hashes::{HashEngine, Hash};
54
55 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
56 ///
57 /// [BOLT 1] specifies a custom message type range for use with experimental or application-specific
58 /// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the
59 /// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler.
60 ///
61 /// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
62 /// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message
63 pub trait CustomMessageHandler: wire::CustomMessageReader {
64         /// Handles the given message sent from `sender_node_id`, possibly producing messages for
65         /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`]
66         /// to send.
67         fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
68
69         /// Returns the list of pending messages that were generated by the handler, clearing the list
70         /// in the process. Each message is paired with the node id of the intended recipient. If no
71         /// connection to the node exists, then the message is simply not sent.
72         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
73
74         /// Gets the node feature flags which this handler itself supports. All available handlers are
75         /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
76         /// which are broadcasted in our [`NodeAnnouncement`] message.
77         ///
78         /// [`NodeAnnouncement`]: crate::ln::msgs::NodeAnnouncement
79         fn provided_node_features(&self) -> NodeFeatures;
80
81         /// Gets the init feature flags which should be sent to the given peer. All available handlers
82         /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
83         /// which are sent in our [`Init`] message.
84         ///
85         /// [`Init`]: crate::ln::msgs::Init
86         fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
87 }
88
89 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
90 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
91 pub struct IgnoringMessageHandler{}
92 impl EventsProvider for IgnoringMessageHandler {
93         fn process_pending_events<H: Deref>(&self, _handler: H) where H::Target: EventHandler {}
94 }
95 impl MessageSendEventsProvider for IgnoringMessageHandler {
96         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
97 }
98 impl RoutingMessageHandler for IgnoringMessageHandler {
99         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
100         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
101         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
102         fn get_next_channel_announcement(&self, _starting_point: u64) ->
103                 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
104         fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
105         fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
106         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
107         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
108         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
109         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
110         fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
111         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
112                 InitFeatures::empty()
113         }
114         fn processing_queue_high(&self) -> bool { false }
115 }
116 impl OnionMessageHandler for IgnoringMessageHandler {
117         fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
118         fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
119         fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
120         fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
121         fn timer_tick_occurred(&self) {}
122         fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
123         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
124                 InitFeatures::empty()
125         }
126 }
127 impl OffersMessageHandler for IgnoringMessageHandler {
128         fn handle_message(&self, _msg: OffersMessage) -> Option<OffersMessage> { None }
129 }
130 impl CustomOnionMessageHandler for IgnoringMessageHandler {
131         type CustomMessage = Infallible;
132         fn handle_custom_message(&self, _msg: Infallible) -> Option<Infallible> {
133                 // Since we always return `None` in the read the handle method should never be called.
134                 unreachable!();
135         }
136         fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
137                 Ok(None)
138         }
139         fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Infallible>> {
140                 vec![]
141         }
142 }
143
144 impl OnionMessageContents for Infallible {
145         fn tlv_type(&self) -> u64 { unreachable!(); }
146 }
147
148 impl Deref for IgnoringMessageHandler {
149         type Target = IgnoringMessageHandler;
150         fn deref(&self) -> &Self { self }
151 }
152
153 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
154 // method that takes self for it.
155 impl wire::Type for Infallible {
156         fn type_id(&self) -> u16 {
157                 unreachable!();
158         }
159 }
160 impl Writeable for Infallible {
161         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
162                 unreachable!();
163         }
164 }
165
166 impl wire::CustomMessageReader for IgnoringMessageHandler {
167         type CustomMessage = Infallible;
168         fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
169                 Ok(None)
170         }
171 }
172
173 impl CustomMessageHandler for IgnoringMessageHandler {
174         fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
175                 // Since we always return `None` in the read the handle method should never be called.
176                 unreachable!();
177         }
178
179         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
180
181         fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
182
183         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
184                 InitFeatures::empty()
185         }
186 }
187
188 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
189 /// You can provide one of these as the route_handler in a MessageHandler.
190 pub struct ErroringMessageHandler {
191         message_queue: Mutex<Vec<MessageSendEvent>>
192 }
193 impl ErroringMessageHandler {
194         /// Constructs a new ErroringMessageHandler
195         pub fn new() -> Self {
196                 Self { message_queue: Mutex::new(Vec::new()) }
197         }
198         fn push_error(&self, node_id: &PublicKey, channel_id: ChannelId) {
199                 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
200                         action: msgs::ErrorAction::SendErrorMessage {
201                                 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
202                         },
203                         node_id: node_id.clone(),
204                 });
205         }
206 }
207 impl MessageSendEventsProvider for ErroringMessageHandler {
208         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
209                 let mut res = Vec::new();
210                 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
211                 res
212         }
213 }
214 impl ChannelMessageHandler for ErroringMessageHandler {
215         // Any messages which are related to a specific channel generate an error message to let the
216         // peer know we don't care about channels.
217         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
218                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
219         }
220         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
221                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
222         }
223         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
224                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
225         }
226         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
227                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
228         }
229         fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
230                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
231         }
232         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
233                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
234         }
235         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
236                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
237         }
238         fn handle_stfu(&self, their_node_id: &PublicKey, msg: &msgs::Stfu) {
239                 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
240         }
241         fn handle_splice(&self, their_node_id: &PublicKey, msg: &msgs::Splice) {
242                 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
243         }
244         fn handle_splice_ack(&self, their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
245                 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
246         }
247         fn handle_splice_locked(&self, their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
248                 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
249         }
250         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
251                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
252         }
253         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
254                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
255         }
256         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
257                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
258         }
259         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
260                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
261         }
262         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
263                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
264         }
265         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
266                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
267         }
268         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
269                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
270         }
271         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
272                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
273         }
274         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
275                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
276         }
277         // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
278         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
279         fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
280         fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
281         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
282         fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
283         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
284                 // Set a number of features which various nodes may require to talk to us. It's totally
285                 // reasonable to indicate we "support" all kinds of channel features...we just reject all
286                 // channels.
287                 let mut features = InitFeatures::empty();
288                 features.set_data_loss_protect_optional();
289                 features.set_upfront_shutdown_script_optional();
290                 features.set_variable_length_onion_optional();
291                 features.set_static_remote_key_optional();
292                 features.set_payment_secret_optional();
293                 features.set_basic_mpp_optional();
294                 features.set_wumbo_optional();
295                 features.set_shutdown_any_segwit_optional();
296                 features.set_channel_type_optional();
297                 features.set_scid_privacy_optional();
298                 features.set_zero_conf_optional();
299                 features
300         }
301
302         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
303                 // We don't enforce any chains upon peer connection for `ErroringMessageHandler` and leave it up
304                 // to users of `ErroringMessageHandler` to make decisions on network compatiblility.
305                 // There's not really any way to pull in specific networks here, and hardcoding can cause breakages.
306                 None
307         }
308
309         fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
310                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
311         }
312
313         fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
314                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
315         }
316
317         fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
318                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
319         }
320
321         fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
322                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
323         }
324
325         fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
326                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
327         }
328
329         fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
330                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
331         }
332
333         fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &msgs::TxComplete) {
334                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
335         }
336
337         fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
338                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
339         }
340
341         fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
342                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
343         }
344
345         fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
346                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
347         }
348
349         fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &msgs::TxAbort) {
350                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
351         }
352 }
353
354 impl Deref for ErroringMessageHandler {
355         type Target = ErroringMessageHandler;
356         fn deref(&self) -> &Self { self }
357 }
358
359 /// Provides references to trait impls which handle different types of messages.
360 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref, CustomM: Deref> where
361         CM::Target: ChannelMessageHandler,
362         RM::Target: RoutingMessageHandler,
363         OM::Target: OnionMessageHandler,
364         CustomM::Target: CustomMessageHandler,
365 {
366         /// A message handler which handles messages specific to channels. Usually this is just a
367         /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
368         ///
369         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
370         pub chan_handler: CM,
371         /// A message handler which handles messages updating our knowledge of the network channel
372         /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
373         ///
374         /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
375         pub route_handler: RM,
376
377         /// A message handler which handles onion messages. This should generally be an
378         /// [`OnionMessenger`], but can also be an [`IgnoringMessageHandler`].
379         ///
380         /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
381         pub onion_message_handler: OM,
382
383         /// A message handler which handles custom messages. The only LDK-provided implementation is
384         /// [`IgnoringMessageHandler`].
385         pub custom_message_handler: CustomM,
386 }
387
388 /// Provides an object which can be used to send data to and which uniquely identifies a connection
389 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
390 /// implement Hash to meet the PeerManager API.
391 ///
392 /// For efficiency, [`Clone`] should be relatively cheap for this type.
393 ///
394 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
395 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
396 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
397 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
398 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
399 /// to simply use another value which is guaranteed to be globally unique instead.
400 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
401         /// Attempts to send some data from the given slice to the peer.
402         ///
403         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
404         /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
405         /// called and further write attempts may occur until that time.
406         ///
407         /// If the returned size is smaller than `data.len()`, a
408         /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
409         /// written. Additionally, until a `send_data` event completes fully, no further
410         /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
411         /// prevent denial-of-service issues, you should not read or buffer any data from the socket
412         /// until then.
413         ///
414         /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
415         /// (indicating that read events should be paused to prevent DoS in the send buffer),
416         /// `resume_read` may be set indicating that read events on this descriptor should resume. A
417         /// `resume_read` of false carries no meaning, and should not cause any action.
418         fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
419         /// Disconnect the socket pointed to by this SocketDescriptor.
420         ///
421         /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
422         /// call (doing so is a noop).
423         fn disconnect_socket(&mut self);
424 }
425
426 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
427 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
428 /// descriptor.
429 #[derive(Clone)]
430 pub struct PeerHandleError { }
431 impl fmt::Debug for PeerHandleError {
432         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
433                 formatter.write_str("Peer Sent Invalid Data")
434         }
435 }
436 impl fmt::Display for PeerHandleError {
437         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
438                 formatter.write_str("Peer Sent Invalid Data")
439         }
440 }
441
442 #[cfg(feature = "std")]
443 impl error::Error for PeerHandleError {
444         fn description(&self) -> &str {
445                 "Peer Sent Invalid Data"
446         }
447 }
448
449 enum InitSyncTracker{
450         NoSyncRequested,
451         ChannelsSyncing(u64),
452         NodesSyncing(NodeId),
453 }
454
455 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
456 /// forwarding gossip messages to peers altogether.
457 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
458
459 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
460 /// we have fewer than this many messages in the outbound buffer again.
461 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
462 /// refilled as we send bytes.
463 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
464 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
465 /// the peer.
466 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
467
468 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
469 /// the socket receive buffer before receiving the ping.
470 ///
471 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
472 /// including any network delays, outbound traffic, or the same for messages from other peers.
473 ///
474 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
475 /// per connected peer to respond to a ping, as long as they send us at least one message during
476 /// each tick, ensuring we aren't actually just disconnected.
477 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
478 /// peer.
479 ///
480 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
481 /// two connected peers, assuming most LDK-running systems have at least two cores.
482 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
483
484 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
485 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
486 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
487 /// process before the next ping.
488 ///
489 /// Note that we continue responding to other messages even after we've sent this many messages, so
490 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
491 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
492 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
493
494 struct Peer {
495         channel_encryptor: PeerChannelEncryptor,
496         /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
497         /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
498         their_node_id: Option<(PublicKey, NodeId)>,
499         /// The features provided in the peer's [`msgs::Init`] message.
500         ///
501         /// This is set only after we've processed the [`msgs::Init`] message and called relevant
502         /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
503         /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
504         /// check this.
505         their_features: Option<InitFeatures>,
506         their_socket_address: Option<SocketAddress>,
507
508         pending_outbound_buffer: VecDeque<Vec<u8>>,
509         pending_outbound_buffer_first_msg_offset: usize,
510         /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
511         /// prioritize channel messages over them.
512         ///
513         /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
514         gossip_broadcast_buffer: VecDeque<MessageBuf>,
515         awaiting_write_event: bool,
516
517         pending_read_buffer: Vec<u8>,
518         pending_read_buffer_pos: usize,
519         pending_read_is_header: bool,
520
521         sync_status: InitSyncTracker,
522
523         msgs_sent_since_pong: usize,
524         awaiting_pong_timer_tick_intervals: i64,
525         received_message_since_timer_tick: bool,
526         sent_gossip_timestamp_filter: bool,
527
528         /// Indicates we've received a `channel_announcement` since the last time we had
529         /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
530         /// `channel_announcement` at all - we set this unconditionally but unset it every time we
531         /// check if we're gossip-processing-backlogged).
532         received_channel_announce_since_backlogged: bool,
533
534         inbound_connection: bool,
535 }
536
537 impl Peer {
538         /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
539         /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
540         /// normally.
541         fn handshake_complete(&self) -> bool {
542                 self.their_features.is_some()
543         }
544
545         /// Returns true if the channel announcements/updates for the given channel should be
546         /// forwarded to this peer.
547         /// If we are sending our routing table to this peer and we have not yet sent channel
548         /// announcements/updates for the given channel_id then we will send it when we get to that
549         /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
550         /// sent the old versions, we should send the update, and so return true here.
551         fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
552                 if !self.handshake_complete() { return false; }
553                 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
554                         !self.sent_gossip_timestamp_filter {
555                                 return false;
556                         }
557                 match self.sync_status {
558                         InitSyncTracker::NoSyncRequested => true,
559                         InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
560                         InitSyncTracker::NodesSyncing(_) => true,
561                 }
562         }
563
564         /// Similar to the above, but for node announcements indexed by node_id.
565         fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
566                 if !self.handshake_complete() { return false; }
567                 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
568                         !self.sent_gossip_timestamp_filter {
569                                 return false;
570                         }
571                 match self.sync_status {
572                         InitSyncTracker::NoSyncRequested => true,
573                         InitSyncTracker::ChannelsSyncing(_) => false,
574                         InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
575                 }
576         }
577
578         /// Returns whether we should be reading bytes from this peer, based on whether its outbound
579         /// buffer still has space and we don't need to pause reads to get some writes out.
580         fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
581                 if !gossip_processing_backlogged {
582                         self.received_channel_announce_since_backlogged = false;
583                 }
584                 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
585                         (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
586         }
587
588         /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
589         /// outbound buffer. This is checked every time the peer's buffer may have been drained.
590         fn should_buffer_gossip_backfill(&self) -> bool {
591                 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
592                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
593                         && self.handshake_complete()
594         }
595
596         /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
597         /// every time the peer's buffer may have been drained.
598         fn should_buffer_onion_message(&self) -> bool {
599                 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
600                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
601         }
602
603         /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
604         /// buffer. This is checked every time the peer's buffer may have been drained.
605         fn should_buffer_gossip_broadcast(&self) -> bool {
606                 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
607                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
608         }
609
610         /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
611         fn buffer_full_drop_gossip_broadcast(&self) -> bool {
612                 let total_outbound_buffered =
613                         self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
614
615                 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
616                         self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
617         }
618
619         fn set_their_node_id(&mut self, node_id: PublicKey) {
620                 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
621         }
622 }
623
624 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
625 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
626 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
627 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
628 /// issues such as overly long function definitions.
629 ///
630 /// This is not exported to bindings users as type aliases aren't supported in most languages.
631 #[cfg(not(c_bindings))]
632 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<
633         SD,
634         Arc<SimpleArcChannelManager<M, T, F, L>>,
635         Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, C, Arc<L>>>,
636         Arc<SimpleArcOnionMessenger<M, T, F, L>>,
637         Arc<L>,
638         IgnoringMessageHandler,
639         Arc<KeysManager>
640 >;
641
642 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
643 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
644 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
645 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
646 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
647 /// helps with issues such as long function definitions.
648 ///
649 /// This is not exported to bindings users as type aliases aren't supported in most languages.
650 #[cfg(not(c_bindings))]
651 pub type SimpleRefPeerManager<
652         'a, 'b, 'c, 'd, 'e, 'f, 'logger, 'h, 'i, 'j, 'graph, 'k, SD, M, T, F, C, L
653 > = PeerManager<
654         SD,
655         &'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, M, T, F, L>,
656         &'f P2PGossipSync<&'graph NetworkGraph<&'logger L>, C, &'logger L>,
657         &'h SimpleRefOnionMessenger<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, 'j, 'k, M, T, F, L>,
658         &'logger L,
659         IgnoringMessageHandler,
660         &'c KeysManager
661 >;
662
663
664 /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or
665 /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather
666 /// than the full set of bounds on [`PeerManager`] itself.
667 ///
668 /// This is not exported to bindings users as general cover traits aren't useful in other
669 /// languages.
670 #[allow(missing_docs)]
671 pub trait APeerManager {
672         type Descriptor: SocketDescriptor;
673         type CMT: ChannelMessageHandler + ?Sized;
674         type CM: Deref<Target=Self::CMT>;
675         type RMT: RoutingMessageHandler + ?Sized;
676         type RM: Deref<Target=Self::RMT>;
677         type OMT: OnionMessageHandler + ?Sized;
678         type OM: Deref<Target=Self::OMT>;
679         type LT: Logger + ?Sized;
680         type L: Deref<Target=Self::LT>;
681         type CMHT: CustomMessageHandler + ?Sized;
682         type CMH: Deref<Target=Self::CMHT>;
683         type NST: NodeSigner + ?Sized;
684         type NS: Deref<Target=Self::NST>;
685         /// Gets a reference to the underlying [`PeerManager`].
686         fn as_ref(&self) -> &PeerManager<Self::Descriptor, Self::CM, Self::RM, Self::OM, Self::L, Self::CMH, Self::NS>;
687         /// Returns the peer manager's [`OnionMessageHandler`].
688         fn onion_message_handler(&self) -> &Self::OMT;
689 }
690
691 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref>
692 APeerManager for PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
693         CM::Target: ChannelMessageHandler,
694         RM::Target: RoutingMessageHandler,
695         OM::Target: OnionMessageHandler,
696         L::Target: Logger,
697         CMH::Target: CustomMessageHandler,
698         NS::Target: NodeSigner,
699 {
700         type Descriptor = Descriptor;
701         type CMT = <CM as Deref>::Target;
702         type CM = CM;
703         type RMT = <RM as Deref>::Target;
704         type RM = RM;
705         type OMT = <OM as Deref>::Target;
706         type OM = OM;
707         type LT = <L as Deref>::Target;
708         type L = L;
709         type CMHT = <CMH as Deref>::Target;
710         type CMH = CMH;
711         type NST = <NS as Deref>::Target;
712         type NS = NS;
713         fn as_ref(&self) -> &PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> { self }
714         fn onion_message_handler(&self) -> &Self::OMT {
715                 self.message_handler.onion_message_handler.deref()
716         }
717 }
718
719 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
720 /// socket events into messages which it passes on to its [`MessageHandler`].
721 ///
722 /// Locks are taken internally, so you must never assume that reentrancy from a
723 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
724 ///
725 /// Calls to [`read_event`] will decode relevant messages and pass them to the
726 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
727 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
728 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
729 /// calls only after previous ones have returned.
730 ///
731 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
732 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
733 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
734 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
735 /// you're using lightning-net-tokio.
736 ///
737 /// [`read_event`]: PeerManager::read_event
738 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
739                 CM::Target: ChannelMessageHandler,
740                 RM::Target: RoutingMessageHandler,
741                 OM::Target: OnionMessageHandler,
742                 L::Target: Logger,
743                 CMH::Target: CustomMessageHandler,
744                 NS::Target: NodeSigner {
745         message_handler: MessageHandler<CM, RM, OM, CMH>,
746         /// Connection state for each connected peer - we have an outer read-write lock which is taken
747         /// as read while we're doing processing for a peer and taken write when a peer is being added
748         /// or removed.
749         ///
750         /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
751         /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
752         /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
753         /// the `MessageHandler`s for a given peer is already guaranteed.
754         peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
755         /// Only add to this set when noise completes.
756         /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
757         /// lock held. Entries may be added with only the `peers` read lock held (though the
758         /// `Descriptor` value must already exist in `peers`).
759         node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
760         /// We can only have one thread processing events at once, but if a second call to
761         /// `process_events` happens while a first call is in progress, one of the two calls needs to
762         /// start from the top to ensure any new messages are also handled.
763         ///
764         /// Because the event handler calls into user code which may block, we don't want to block a
765         /// second thread waiting for another thread to handle events which is then blocked on user
766         /// code, so we store an atomic counter here:
767         ///  * 0 indicates no event processor is running
768         ///  * 1 indicates an event processor is running
769         ///  * > 1 indicates an event processor is running but needs to start again from the top once
770         ///        it finishes as another thread tried to start processing events but returned early.
771         event_processing_state: AtomicI32,
772
773         /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
774         /// value increases strictly since we don't assume access to a time source.
775         last_node_announcement_serial: AtomicU32,
776
777         ephemeral_key_midstate: Sha256Engine,
778
779         peer_counter: AtomicCounter,
780
781         gossip_processing_backlogged: AtomicBool,
782         gossip_processing_backlog_lifted: AtomicBool,
783
784         node_signer: NS,
785
786         logger: L,
787         secp_ctx: Secp256k1<secp256k1::SignOnly>
788 }
789
790 enum MessageHandlingError {
791         PeerHandleError(PeerHandleError),
792         LightningError(LightningError),
793 }
794
795 impl From<PeerHandleError> for MessageHandlingError {
796         fn from(error: PeerHandleError) -> Self {
797                 MessageHandlingError::PeerHandleError(error)
798         }
799 }
800
801 impl From<LightningError> for MessageHandlingError {
802         fn from(error: LightningError) -> Self {
803                 MessageHandlingError::LightningError(error)
804         }
805 }
806
807 macro_rules! encode_msg {
808         ($msg: expr) => {{
809                 let mut buffer = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
810                 wire::write($msg, &mut buffer).unwrap();
811                 buffer.0
812         }}
813 }
814
815 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
816                 CM::Target: ChannelMessageHandler,
817                 OM::Target: OnionMessageHandler,
818                 L::Target: Logger,
819                 NS::Target: NodeSigner {
820         /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
821         /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
822         /// ignored.
823         ///
824         /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
825         /// cryptographically secure random bytes.
826         ///
827         /// `current_time` is used as an always-increasing counter that survives across restarts and is
828         /// incremented irregularly internally. In general it is best to simply use the current UNIX
829         /// timestamp, however if it is not available a persistent counter that increases once per
830         /// minute should suffice.
831         ///
832         /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
833         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 {
834                 Self::new(MessageHandler {
835                         chan_handler: channel_message_handler,
836                         route_handler: IgnoringMessageHandler{},
837                         onion_message_handler,
838                         custom_message_handler: IgnoringMessageHandler{},
839                 }, current_time, ephemeral_random_data, logger, node_signer)
840         }
841 }
842
843 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
844                 RM::Target: RoutingMessageHandler,
845                 L::Target: Logger,
846                 NS::Target: NodeSigner {
847         /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
848         /// handler or onion message handler is used and onion and channel messages will be ignored (or
849         /// generate error messages). Note that some other lightning implementations time-out connections
850         /// after some time if no channel is built with the peer.
851         ///
852         /// `current_time` is used as an always-increasing counter that survives across restarts and is
853         /// incremented irregularly internally. In general it is best to simply use the current UNIX
854         /// timestamp, however if it is not available a persistent counter that increases once per
855         /// minute should suffice.
856         ///
857         /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
858         /// cryptographically secure random bytes.
859         ///
860         /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
861         pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
862                 Self::new(MessageHandler {
863                         chan_handler: ErroringMessageHandler::new(),
864                         route_handler: routing_message_handler,
865                         onion_message_handler: IgnoringMessageHandler{},
866                         custom_message_handler: IgnoringMessageHandler{},
867                 }, current_time, ephemeral_random_data, logger, node_signer)
868         }
869 }
870
871 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
872 /// This works around `format!()` taking a reference to each argument, preventing
873 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
874 /// due to lifetime errors.
875 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
876 impl core::fmt::Display for OptionalFromDebugger<'_> {
877         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
878                 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
879         }
880 }
881
882 /// A function used to filter out local or private addresses
883 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
884 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
885 fn filter_addresses(ip_address: Option<SocketAddress>) -> Option<SocketAddress> {
886         match ip_address{
887                 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
888                 Some(SocketAddress::TcpIpV4{addr: [10, _, _, _], port: _}) => None,
889                 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
890                 Some(SocketAddress::TcpIpV4{addr: [0, _, _, _], port: _}) => None,
891                 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
892                 Some(SocketAddress::TcpIpV4{addr: [100, 64..=127, _, _], port: _}) => None,
893                 // For IPv4 range       127.0.0.0 - 127.255.255.255 (127/8)
894                 Some(SocketAddress::TcpIpV4{addr: [127, _, _, _], port: _}) => None,
895                 // For IPv4 range       169.254.0.0 - 169.254.255.255 (169.254/16)
896                 Some(SocketAddress::TcpIpV4{addr: [169, 254, _, _], port: _}) => None,
897                 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
898                 Some(SocketAddress::TcpIpV4{addr: [172, 16..=31, _, _], port: _}) => None,
899                 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
900                 Some(SocketAddress::TcpIpV4{addr: [192, 168, _, _], port: _}) => None,
901                 // For IPv4 range 192.88.99.0 - 192.88.99.255  (192.88.99/24)
902                 Some(SocketAddress::TcpIpV4{addr: [192, 88, 99, _], port: _}) => None,
903                 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
904                 Some(SocketAddress::TcpIpV6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
905                 // For remaining addresses
906                 Some(SocketAddress::TcpIpV6{addr: _, port: _}) => None,
907                 Some(..) => ip_address,
908                 None => None,
909         }
910 }
911
912 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
913                 CM::Target: ChannelMessageHandler,
914                 RM::Target: RoutingMessageHandler,
915                 OM::Target: OnionMessageHandler,
916                 L::Target: Logger,
917                 CMH::Target: CustomMessageHandler,
918                 NS::Target: NodeSigner
919 {
920         /// Constructs a new `PeerManager` with the given message handlers.
921         ///
922         /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
923         /// cryptographically secure random bytes.
924         ///
925         /// `current_time` is used as an always-increasing counter that survives across restarts and is
926         /// incremented irregularly internally. In general it is best to simply use the current UNIX
927         /// timestamp, however if it is not available a persistent counter that increases once per
928         /// minute should suffice.
929         pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
930                 let mut ephemeral_key_midstate = Sha256::engine();
931                 ephemeral_key_midstate.input(ephemeral_random_data);
932
933                 let mut secp_ctx = Secp256k1::signing_only();
934                 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).to_byte_array();
935                 secp_ctx.seeded_randomize(&ephemeral_hash);
936
937                 PeerManager {
938                         message_handler,
939                         peers: FairRwLock::new(HashMap::new()),
940                         node_id_to_descriptor: Mutex::new(HashMap::new()),
941                         event_processing_state: AtomicI32::new(0),
942                         ephemeral_key_midstate,
943                         peer_counter: AtomicCounter::new(),
944                         gossip_processing_backlogged: AtomicBool::new(false),
945                         gossip_processing_backlog_lifted: AtomicBool::new(false),
946                         last_node_announcement_serial: AtomicU32::new(current_time),
947                         logger,
948                         node_signer,
949                         secp_ctx,
950                 }
951         }
952
953         /// Get a list of tuples mapping from node id to network addresses for peers which have
954         /// completed the initial handshake.
955         ///
956         /// For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter
957         /// passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial
958         /// handshake has completed and we are sure the remote peer has the private key for the given
959         /// [`PublicKey`].
960         ///
961         /// The returned `Option`s will only be `Some` if an address had been previously given via
962         /// [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`].
963         pub fn get_peer_node_ids(&self) -> Vec<(PublicKey, Option<SocketAddress>)> {
964                 let peers = self.peers.read().unwrap();
965                 peers.values().filter_map(|peer_mutex| {
966                         let p = peer_mutex.lock().unwrap();
967                         if !p.handshake_complete() {
968                                 return None;
969                         }
970                         Some((p.their_node_id.unwrap().0, p.their_socket_address.clone()))
971                 }).collect()
972         }
973
974         fn get_ephemeral_key(&self) -> SecretKey {
975                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
976                 let counter = self.peer_counter.get_increment();
977                 ephemeral_hash.input(&counter.to_le_bytes());
978                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).to_byte_array()).expect("You broke SHA-256!")
979         }
980
981         fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
982                 self.message_handler.chan_handler.provided_init_features(their_node_id)
983                         | self.message_handler.route_handler.provided_init_features(their_node_id)
984                         | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
985                         | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
986         }
987
988         /// Indicates a new outbound connection has been established to a node with the given `node_id`
989         /// and an optional remote network address.
990         ///
991         /// The remote network address adds the option to report a remote IP address back to a connecting
992         /// peer using the init message.
993         /// The user should pass the remote network address of the host they are connected to.
994         ///
995         /// If an `Err` is returned here you must disconnect the connection immediately.
996         ///
997         /// Returns a small number of bytes to send to the remote node (currently always 50).
998         ///
999         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1000         /// [`socket_disconnected`].
1001         ///
1002         /// [`socket_disconnected`]: PeerManager::socket_disconnected
1003         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<Vec<u8>, PeerHandleError> {
1004                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
1005                 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
1006                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
1007
1008                 let mut peers = self.peers.write().unwrap();
1009                 match peers.entry(descriptor) {
1010                         hash_map::Entry::Occupied(_) => {
1011                                 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1012                                 Err(PeerHandleError {})
1013                         },
1014                         hash_map::Entry::Vacant(e) => {
1015                                 e.insert(Mutex::new(Peer {
1016                                         channel_encryptor: peer_encryptor,
1017                                         their_node_id: None,
1018                                         their_features: None,
1019                                         their_socket_address: remote_network_address,
1020
1021                                         pending_outbound_buffer: VecDeque::new(),
1022                                         pending_outbound_buffer_first_msg_offset: 0,
1023                                         gossip_broadcast_buffer: VecDeque::new(),
1024                                         awaiting_write_event: false,
1025
1026                                         pending_read_buffer,
1027                                         pending_read_buffer_pos: 0,
1028                                         pending_read_is_header: false,
1029
1030                                         sync_status: InitSyncTracker::NoSyncRequested,
1031
1032                                         msgs_sent_since_pong: 0,
1033                                         awaiting_pong_timer_tick_intervals: 0,
1034                                         received_message_since_timer_tick: false,
1035                                         sent_gossip_timestamp_filter: false,
1036
1037                                         received_channel_announce_since_backlogged: false,
1038                                         inbound_connection: false,
1039                                 }));
1040                                 Ok(res)
1041                         }
1042                 }
1043         }
1044
1045         /// Indicates a new inbound connection has been established to a node with an optional remote
1046         /// network address.
1047         ///
1048         /// The remote network address adds the option to report a remote IP address back to a connecting
1049         /// peer using the init message.
1050         /// The user should pass the remote network address of the host they are connected to.
1051         ///
1052         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
1053         /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
1054         /// the connection immediately.
1055         ///
1056         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1057         /// [`socket_disconnected`].
1058         ///
1059         /// [`socket_disconnected`]: PeerManager::socket_disconnected
1060         pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<(), PeerHandleError> {
1061                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1062                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1063
1064                 let mut peers = self.peers.write().unwrap();
1065                 match peers.entry(descriptor) {
1066                         hash_map::Entry::Occupied(_) => {
1067                                 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1068                                 Err(PeerHandleError {})
1069                         },
1070                         hash_map::Entry::Vacant(e) => {
1071                                 e.insert(Mutex::new(Peer {
1072                                         channel_encryptor: peer_encryptor,
1073                                         their_node_id: None,
1074                                         their_features: None,
1075                                         their_socket_address: remote_network_address,
1076
1077                                         pending_outbound_buffer: VecDeque::new(),
1078                                         pending_outbound_buffer_first_msg_offset: 0,
1079                                         gossip_broadcast_buffer: VecDeque::new(),
1080                                         awaiting_write_event: false,
1081
1082                                         pending_read_buffer,
1083                                         pending_read_buffer_pos: 0,
1084                                         pending_read_is_header: false,
1085
1086                                         sync_status: InitSyncTracker::NoSyncRequested,
1087
1088                                         msgs_sent_since_pong: 0,
1089                                         awaiting_pong_timer_tick_intervals: 0,
1090                                         received_message_since_timer_tick: false,
1091                                         sent_gossip_timestamp_filter: false,
1092
1093                                         received_channel_announce_since_backlogged: false,
1094                                         inbound_connection: true,
1095                                 }));
1096                                 Ok(())
1097                         }
1098                 }
1099         }
1100
1101         fn peer_should_read(&self, peer: &mut Peer) -> bool {
1102                 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1103         }
1104
1105         fn update_gossip_backlogged(&self) {
1106                 let new_state = self.message_handler.route_handler.processing_queue_high();
1107                 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1108                 if prev_state && !new_state {
1109                         self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1110                 }
1111         }
1112
1113         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1114                 let mut have_written = false;
1115                 while !peer.awaiting_write_event {
1116                         if peer.should_buffer_onion_message() {
1117                                 if let Some((peer_node_id, _)) = peer.their_node_id {
1118                                         if let Some(next_onion_message) =
1119                                                 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1120                                                         self.enqueue_message(peer, &next_onion_message);
1121                                         }
1122                                 }
1123                         }
1124                         if peer.should_buffer_gossip_broadcast() {
1125                                 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1126                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(msg));
1127                                 }
1128                         }
1129                         if peer.should_buffer_gossip_backfill() {
1130                                 match peer.sync_status {
1131                                         InitSyncTracker::NoSyncRequested => {},
1132                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1133                                                 if let Some((announce, update_a_option, update_b_option)) =
1134                                                         self.message_handler.route_handler.get_next_channel_announcement(c)
1135                                                 {
1136                                                         self.enqueue_message(peer, &announce);
1137                                                         if let Some(update_a) = update_a_option {
1138                                                                 self.enqueue_message(peer, &update_a);
1139                                                         }
1140                                                         if let Some(update_b) = update_b_option {
1141                                                                 self.enqueue_message(peer, &update_b);
1142                                                         }
1143                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1144                                                 } else {
1145                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1146                                                 }
1147                                         },
1148                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1149                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1150                                                         self.enqueue_message(peer, &msg);
1151                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1152                                                 } else {
1153                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
1154                                                 }
1155                                         },
1156                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1157                                         InitSyncTracker::NodesSyncing(sync_node_id) => {
1158                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1159                                                         self.enqueue_message(peer, &msg);
1160                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1161                                                 } else {
1162                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
1163                                                 }
1164                                         },
1165                                 }
1166                         }
1167                         if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1168                                 self.maybe_send_extra_ping(peer);
1169                         }
1170
1171                         let should_read = self.peer_should_read(peer);
1172                         let next_buff = match peer.pending_outbound_buffer.front() {
1173                                 None => {
1174                                         if force_one_write && !have_written {
1175                                                 if should_read {
1176                                                         let data_sent = descriptor.send_data(&[], should_read);
1177                                                         debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1178                                                 }
1179                                         }
1180                                         return
1181                                 },
1182                                 Some(buff) => buff,
1183                         };
1184
1185                         let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1186                         let data_sent = descriptor.send_data(pending, should_read);
1187                         have_written = true;
1188                         peer.pending_outbound_buffer_first_msg_offset += data_sent;
1189                         if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1190                                 peer.pending_outbound_buffer_first_msg_offset = 0;
1191                                 peer.pending_outbound_buffer.pop_front();
1192                                 const VEC_SIZE: usize = ::core::mem::size_of::<Vec<u8>>();
1193                                 let large_capacity = peer.pending_outbound_buffer.capacity() > 4096 / VEC_SIZE;
1194                                 let lots_of_slack = peer.pending_outbound_buffer.len()
1195                                         < peer.pending_outbound_buffer.capacity() / 2;
1196                                 if large_capacity && lots_of_slack {
1197                                         peer.pending_outbound_buffer.shrink_to_fit();
1198                                 }
1199                         } else {
1200                                 peer.awaiting_write_event = true;
1201                         }
1202                 }
1203         }
1204
1205         /// Indicates that there is room to write data to the given socket descriptor.
1206         ///
1207         /// May return an Err to indicate that the connection should be closed.
1208         ///
1209         /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1210         /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1211         /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1212         /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1213         /// sufficient!
1214         ///
1215         /// [`send_data`]: SocketDescriptor::send_data
1216         /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1217         pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1218                 let peers = self.peers.read().unwrap();
1219                 match peers.get(descriptor) {
1220                         None => {
1221                                 // This is most likely a simple race condition where the user found that the socket
1222                                 // was writeable, then we told the user to `disconnect_socket()`, then they called
1223                                 // this method. Return an error to make sure we get disconnected.
1224                                 return Err(PeerHandleError { });
1225                         },
1226                         Some(peer_mutex) => {
1227                                 let mut peer = peer_mutex.lock().unwrap();
1228                                 peer.awaiting_write_event = false;
1229                                 self.do_attempt_write_data(descriptor, &mut peer, false);
1230                         }
1231                 };
1232                 Ok(())
1233         }
1234
1235         /// Indicates that data was read from the given socket descriptor.
1236         ///
1237         /// May return an Err to indicate that the connection should be closed.
1238         ///
1239         /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1240         /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1241         /// [`send_data`] calls to handle responses.
1242         ///
1243         /// If `Ok(true)` is returned, further read_events should not be triggered until a
1244         /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1245         /// send buffer).
1246         ///
1247         /// In order to avoid processing too many messages at once per peer, `data` should be on the
1248         /// order of 4KiB.
1249         ///
1250         /// [`send_data`]: SocketDescriptor::send_data
1251         /// [`process_events`]: PeerManager::process_events
1252         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1253                 match self.do_read_event(peer_descriptor, data) {
1254                         Ok(res) => Ok(res),
1255                         Err(e) => {
1256                                 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1257                                 self.disconnect_event_internal(peer_descriptor);
1258                                 Err(e)
1259                         }
1260                 }
1261         }
1262
1263         /// Append a message to a peer's pending outbound/write buffer
1264         fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1265                 let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1266                 if is_gossip_msg(message.type_id()) {
1267                         log_gossip!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1268                 } else {
1269                         log_trace!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1270                 }
1271                 peer.msgs_sent_since_pong += 1;
1272                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1273         }
1274
1275         /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1276         fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: MessageBuf) {
1277                 peer.msgs_sent_since_pong += 1;
1278                 debug_assert!(peer.gossip_broadcast_buffer.len() <= OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP);
1279                 peer.gossip_broadcast_buffer.push_back(encoded_message);
1280         }
1281
1282         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1283                 let mut pause_read = false;
1284                 let peers = self.peers.read().unwrap();
1285                 let mut msgs_to_forward = Vec::new();
1286                 let mut peer_node_id = None;
1287                 match peers.get(peer_descriptor) {
1288                         None => {
1289                                 // This is most likely a simple race condition where the user read some bytes
1290                                 // from the socket, then we told the user to `disconnect_socket()`, then they
1291                                 // called this method. Return an error to make sure we get disconnected.
1292                                 return Err(PeerHandleError { });
1293                         },
1294                         Some(peer_mutex) => {
1295                                 let mut read_pos = 0;
1296                                 while read_pos < data.len() {
1297                                         macro_rules! try_potential_handleerror {
1298                                                 ($peer: expr, $thing: expr) => {{
1299                                                         let res = $thing;
1300                                                         let logger = WithContext::from(&self.logger, peer_node_id.map(|(id, _)| id), None);
1301                                                         match res {
1302                                                                 Ok(x) => x,
1303                                                                 Err(e) => {
1304                                                                         match e.action {
1305                                                                                 msgs::ErrorAction::DisconnectPeer { .. } => {
1306                                                                                         // We may have an `ErrorMessage` to send to the peer,
1307                                                                                         // but writing to the socket while reading can lead to
1308                                                                                         // re-entrant code and possibly unexpected behavior. The
1309                                                                                         // message send is optimistic anyway, and in this case
1310                                                                                         // we immediately disconnect the peer.
1311                                                                                         log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1312                                                                                         return Err(PeerHandleError { });
1313                                                                                 },
1314                                                                                 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1315                                                                                         // We have a `WarningMessage` to send to the peer, but
1316                                                                                         // writing to the socket while reading can lead to
1317                                                                                         // re-entrant code and possibly unexpected behavior. The
1318                                                                                         // message send is optimistic anyway, and in this case
1319                                                                                         // we immediately disconnect the peer.
1320                                                                                         log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1321                                                                                         return Err(PeerHandleError { });
1322                                                                                 },
1323                                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
1324                                                                                         log_given_level!(logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1325                                                                                         continue
1326                                                                                 },
1327                                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1328                                                                                 msgs::ErrorAction::IgnoreError => {
1329                                                                                         log_debug!(logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1330                                                                                         continue;
1331                                                                                 },
1332                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
1333                                                                                         log_debug!(logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1334                                                                                         self.enqueue_message($peer, &msg);
1335                                                                                         continue;
1336                                                                                 },
1337                                                                                 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1338                                                                                         log_given_level!(logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1339                                                                                         self.enqueue_message($peer, &msg);
1340                                                                                         continue;
1341                                                                                 },
1342                                                                         }
1343                                                                 }
1344                                                         }
1345                                                 }}
1346                                         }
1347
1348                                         let mut peer_lock = peer_mutex.lock().unwrap();
1349                                         let peer = &mut *peer_lock;
1350                                         let mut msg_to_handle = None;
1351                                         if peer_node_id.is_none() {
1352                                                 peer_node_id = peer.their_node_id.clone();
1353                                         }
1354
1355                                         assert!(peer.pending_read_buffer.len() > 0);
1356                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1357
1358                                         {
1359                                                 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1360                                                 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]);
1361                                                 read_pos += data_to_copy;
1362                                                 peer.pending_read_buffer_pos += data_to_copy;
1363                                         }
1364
1365                                         if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1366                                                 peer.pending_read_buffer_pos = 0;
1367
1368                                                 macro_rules! insert_node_id {
1369                                                         () => {
1370                                                                 let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1371                                                                 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1372                                                                         hash_map::Entry::Occupied(e) => {
1373                                                                                 log_trace!(logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1374                                                                                 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1375                                                                                 // Check that the peers map is consistent with the
1376                                                                                 // node_id_to_descriptor map, as this has been broken
1377                                                                                 // before.
1378                                                                                 debug_assert!(peers.get(e.get()).is_some());
1379                                                                                 return Err(PeerHandleError { })
1380                                                                         },
1381                                                                         hash_map::Entry::Vacant(entry) => {
1382                                                                                 log_debug!(logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1383                                                                                 entry.insert(peer_descriptor.clone())
1384                                                                         },
1385                                                                 };
1386                                                         }
1387                                                 }
1388
1389                                                 let next_step = peer.channel_encryptor.get_noise_step();
1390                                                 match next_step {
1391                                                         NextNoiseStep::ActOne => {
1392                                                                 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1393                                                                         .process_act_one_with_keys(&peer.pending_read_buffer[..],
1394                                                                                 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1395                                                                 peer.pending_outbound_buffer.push_back(act_two);
1396                                                                 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1397                                                         },
1398                                                         NextNoiseStep::ActTwo => {
1399                                                                 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1400                                                                         peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1401                                                                                 &self.node_signer));
1402                                                                 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1403                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1404                                                                 peer.pending_read_is_header = true;
1405
1406                                                                 peer.set_their_node_id(their_node_id);
1407                                                                 insert_node_id!();
1408                                                                 let features = self.init_features(&their_node_id);
1409                                                                 let networks = self.message_handler.chan_handler.get_chain_hashes();
1410                                                                 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1411                                                                 self.enqueue_message(peer, &resp);
1412                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1413                                                         },
1414                                                         NextNoiseStep::ActThree => {
1415                                                                 let their_node_id = try_potential_handleerror!(peer,
1416                                                                         peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1417                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1418                                                                 peer.pending_read_is_header = true;
1419                                                                 peer.set_their_node_id(their_node_id);
1420                                                                 insert_node_id!();
1421                                                                 let features = self.init_features(&their_node_id);
1422                                                                 let networks = self.message_handler.chan_handler.get_chain_hashes();
1423                                                                 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1424                                                                 self.enqueue_message(peer, &resp);
1425                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1426                                                         },
1427                                                         NextNoiseStep::NoiseComplete => {
1428                                                                 if peer.pending_read_is_header {
1429                                                                         let msg_len = try_potential_handleerror!(peer,
1430                                                                                 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1431                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1432                                                                         peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1433                                                                         if msg_len < 2 { // Need at least the message type tag
1434                                                                                 return Err(PeerHandleError { });
1435                                                                         }
1436                                                                         peer.pending_read_is_header = false;
1437                                                                 } else {
1438                                                                         debug_assert!(peer.pending_read_buffer.len() >= 2 + 16);
1439                                                                         try_potential_handleerror!(peer,
1440                                                                                 peer.channel_encryptor.decrypt_message(&mut peer.pending_read_buffer[..]));
1441
1442                                                                         let mut reader = io::Cursor::new(&peer.pending_read_buffer[..peer.pending_read_buffer.len() - 16]);
1443                                                                         let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1444
1445                                                                         // Reset read buffer
1446                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1447                                                                         peer.pending_read_buffer.resize(18, 0);
1448                                                                         peer.pending_read_is_header = true;
1449
1450                                                                         let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1451                                                                         let message = match message_result {
1452                                                                                 Ok(x) => x,
1453                                                                                 Err(e) => {
1454                                                                                         match e {
1455                                                                                                 // Note that to avoid re-entrancy we never call
1456                                                                                                 // `do_attempt_write_data` from here, causing
1457                                                                                                 // the messages enqueued here to not actually
1458                                                                                                 // be sent before the peer is disconnected.
1459                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1460                                                                                                         log_gossip!(logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1461                                                                                                         continue;
1462                                                                                                 }
1463                                                                                                 (msgs::DecodeError::UnsupportedCompression, _) => {
1464                                                                                                         log_gossip!(logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1465                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: ChannelId::new_zero(), data: "Unsupported message compression: zlib".to_owned() });
1466                                                                                                         continue;
1467                                                                                                 }
1468                                                                                                 (_, Some(ty)) if is_gossip_msg(ty) => {
1469                                                                                                         log_gossip!(logger, "Got an invalid value while deserializing a gossip message");
1470                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage {
1471                                                                                                                 channel_id: ChannelId::new_zero(),
1472                                                                                                                 data: format!("Unreadable/bogus gossip message of type {}", ty),
1473                                                                                                         });
1474                                                                                                         continue;
1475                                                                                                 }
1476                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1477                                                                                                         log_debug!(logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1478                                                                                                         return Err(PeerHandleError { });
1479                                                                                                 }
1480                                                                                                 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1481                                                                                                 (msgs::DecodeError::InvalidValue, _) => {
1482                                                                                                         log_debug!(logger, "Got an invalid value while deserializing message");
1483                                                                                                         return Err(PeerHandleError { });
1484                                                                                                 }
1485                                                                                                 (msgs::DecodeError::ShortRead, _) => {
1486                                                                                                         log_debug!(logger, "Deserialization failed due to shortness of message");
1487                                                                                                         return Err(PeerHandleError { });
1488                                                                                                 }
1489                                                                                                 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1490                                                                                                 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1491                                                                                         }
1492                                                                                 }
1493                                                                         };
1494
1495                                                                         msg_to_handle = Some(message);
1496                                                                 }
1497                                                         }
1498                                                 }
1499                                         }
1500                                         pause_read = !self.peer_should_read(peer);
1501
1502                                         if let Some(message) = msg_to_handle {
1503                                                 match self.handle_message(&peer_mutex, peer_lock, message) {
1504                                                         Err(handling_error) => match handling_error {
1505                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1506                                                                 MessageHandlingError::LightningError(e) => {
1507                                                                         try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1508                                                                 },
1509                                                         },
1510                                                         Ok(Some(msg)) => {
1511                                                                 msgs_to_forward.push(msg);
1512                                                         },
1513                                                         Ok(None) => {},
1514                                                 }
1515                                         }
1516                                 }
1517                         }
1518                 }
1519
1520                 for msg in msgs_to_forward.drain(..) {
1521                         self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1522                 }
1523
1524                 Ok(pause_read)
1525         }
1526
1527         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1528         /// Returns the message back if it needs to be broadcasted to all other peers.
1529         fn handle_message(
1530                 &self,
1531                 peer_mutex: &Mutex<Peer>,
1532                 mut peer_lock: MutexGuard<Peer>,
1533                 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1534         ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1535                 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;
1536                 let logger = WithContext::from(&self.logger, Some(their_node_id), None);
1537                 peer_lock.received_message_since_timer_tick = true;
1538
1539                 // Need an Init as first message
1540                 if let wire::Message::Init(msg) = message {
1541                         // Check if we have any compatible chains if the `networks` field is specified.
1542                         if let Some(networks) = &msg.networks {
1543                                 if let Some(our_chains) = self.message_handler.chan_handler.get_chain_hashes() {
1544                                         let mut have_compatible_chains = false;
1545                                         'our_chains: for our_chain in our_chains.iter() {
1546                                                 for their_chain in networks {
1547                                                         if our_chain == their_chain {
1548                                                                 have_compatible_chains = true;
1549                                                                 break 'our_chains;
1550                                                         }
1551                                                 }
1552                                         }
1553                                         if !have_compatible_chains {
1554                                                 log_debug!(logger, "Peer does not support any of our supported chains");
1555                                                 return Err(PeerHandleError { }.into());
1556                                         }
1557                                 }
1558                         }
1559
1560                         let our_features = self.init_features(&their_node_id);
1561                         if msg.features.requires_unknown_bits_from(&our_features) {
1562                                 log_debug!(logger, "Peer requires features unknown to us");
1563                                 return Err(PeerHandleError { }.into());
1564                         }
1565
1566                         if our_features.requires_unknown_bits_from(&msg.features) {
1567                                 log_debug!(logger, "We require features unknown to our peer");
1568                                 return Err(PeerHandleError { }.into());
1569                         }
1570
1571                         if peer_lock.their_features.is_some() {
1572                                 return Err(PeerHandleError { }.into());
1573                         }
1574
1575                         log_info!(logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1576
1577                         // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1578                         if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1579                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1580                         }
1581
1582                         if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1583                                 log_debug!(logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1584                                 return Err(PeerHandleError { }.into());
1585                         }
1586                         if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1587                                 log_debug!(logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1588                                 return Err(PeerHandleError { }.into());
1589                         }
1590                         if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1591                                 log_debug!(logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1592                                 return Err(PeerHandleError { }.into());
1593                         }
1594
1595                         peer_lock.their_features = Some(msg.features);
1596                         return Ok(None);
1597                 } else if peer_lock.their_features.is_none() {
1598                         log_debug!(logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1599                         return Err(PeerHandleError { }.into());
1600                 }
1601
1602                 if let wire::Message::GossipTimestampFilter(_msg) = message {
1603                         // When supporting gossip messages, start inital gossip sync only after we receive
1604                         // a GossipTimestampFilter
1605                         if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1606                                 !peer_lock.sent_gossip_timestamp_filter {
1607                                 peer_lock.sent_gossip_timestamp_filter = true;
1608                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1609                         }
1610                         return Ok(None);
1611                 }
1612
1613                 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1614                         peer_lock.received_channel_announce_since_backlogged = true;
1615                 }
1616
1617                 mem::drop(peer_lock);
1618
1619                 if is_gossip_msg(message.type_id()) {
1620                         log_gossip!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1621                 } else {
1622                         log_trace!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1623                 }
1624
1625                 let mut should_forward = None;
1626
1627                 match message {
1628                         // Setup and Control messages:
1629                         wire::Message::Init(_) => {
1630                                 // Handled above
1631                         },
1632                         wire::Message::GossipTimestampFilter(_) => {
1633                                 // Handled above
1634                         },
1635                         wire::Message::Error(msg) => {
1636                                 log_debug!(logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1637                                 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1638                                 if msg.channel_id.is_zero() {
1639                                         return Err(PeerHandleError { }.into());
1640                                 }
1641                         },
1642                         wire::Message::Warning(msg) => {
1643                                 log_debug!(logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1644                         },
1645
1646                         wire::Message::Ping(msg) => {
1647                                 if msg.ponglen < 65532 {
1648                                         let resp = msgs::Pong { byteslen: msg.ponglen };
1649                                         self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1650                                 }
1651                         },
1652                         wire::Message::Pong(_msg) => {
1653                                 let mut peer_lock = peer_mutex.lock().unwrap();
1654                                 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1655                                 peer_lock.msgs_sent_since_pong = 0;
1656                         },
1657
1658                         // Channel messages:
1659                         wire::Message::OpenChannel(msg) => {
1660                                 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1661                         },
1662                         wire::Message::OpenChannelV2(msg) => {
1663                                 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1664                         },
1665                         wire::Message::AcceptChannel(msg) => {
1666                                 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1667                         },
1668                         wire::Message::AcceptChannelV2(msg) => {
1669                                 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1670                         },
1671
1672                         wire::Message::FundingCreated(msg) => {
1673                                 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1674                         },
1675                         wire::Message::FundingSigned(msg) => {
1676                                 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1677                         },
1678                         wire::Message::ChannelReady(msg) => {
1679                                 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1680                         },
1681
1682                         // Quiescence messages:
1683                         wire::Message::Stfu(msg) => {
1684                                 self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
1685                         }
1686
1687                         // Splicing messages:
1688                         wire::Message::Splice(msg) => {
1689                                 self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
1690                         }
1691                         wire::Message::SpliceAck(msg) => {
1692                                 self.message_handler.chan_handler.handle_splice_ack(&their_node_id, &msg);
1693                         }
1694                         wire::Message::SpliceLocked(msg) => {
1695                                 self.message_handler.chan_handler.handle_splice_locked(&their_node_id, &msg);
1696                         }
1697
1698                         // Interactive transaction construction messages:
1699                         wire::Message::TxAddInput(msg) => {
1700                                 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1701                         },
1702                         wire::Message::TxAddOutput(msg) => {
1703                                 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1704                         },
1705                         wire::Message::TxRemoveInput(msg) => {
1706                                 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1707                         },
1708                         wire::Message::TxRemoveOutput(msg) => {
1709                                 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1710                         },
1711                         wire::Message::TxComplete(msg) => {
1712                                 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1713                         },
1714                         wire::Message::TxSignatures(msg) => {
1715                                 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1716                         },
1717                         wire::Message::TxInitRbf(msg) => {
1718                                 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1719                         },
1720                         wire::Message::TxAckRbf(msg) => {
1721                                 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1722                         },
1723                         wire::Message::TxAbort(msg) => {
1724                                 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1725                         }
1726
1727                         wire::Message::Shutdown(msg) => {
1728                                 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1729                         },
1730                         wire::Message::ClosingSigned(msg) => {
1731                                 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1732                         },
1733
1734                         // Commitment messages:
1735                         wire::Message::UpdateAddHTLC(msg) => {
1736                                 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1737                         },
1738                         wire::Message::UpdateFulfillHTLC(msg) => {
1739                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1740                         },
1741                         wire::Message::UpdateFailHTLC(msg) => {
1742                                 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1743                         },
1744                         wire::Message::UpdateFailMalformedHTLC(msg) => {
1745                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1746                         },
1747
1748                         wire::Message::CommitmentSigned(msg) => {
1749                                 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1750                         },
1751                         wire::Message::RevokeAndACK(msg) => {
1752                                 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1753                         },
1754                         wire::Message::UpdateFee(msg) => {
1755                                 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1756                         },
1757                         wire::Message::ChannelReestablish(msg) => {
1758                                 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1759                         },
1760
1761                         // Routing messages:
1762                         wire::Message::AnnouncementSignatures(msg) => {
1763                                 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1764                         },
1765                         wire::Message::ChannelAnnouncement(msg) => {
1766                                 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1767                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1768                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1769                                 }
1770                                 self.update_gossip_backlogged();
1771                         },
1772                         wire::Message::NodeAnnouncement(msg) => {
1773                                 if self.message_handler.route_handler.handle_node_announcement(&msg)
1774                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1775                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
1776                                 }
1777                                 self.update_gossip_backlogged();
1778                         },
1779                         wire::Message::ChannelUpdate(msg) => {
1780                                 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1781                                 if self.message_handler.route_handler.handle_channel_update(&msg)
1782                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1783                                         should_forward = Some(wire::Message::ChannelUpdate(msg));
1784                                 }
1785                                 self.update_gossip_backlogged();
1786                         },
1787                         wire::Message::QueryShortChannelIds(msg) => {
1788                                 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1789                         },
1790                         wire::Message::ReplyShortChannelIdsEnd(msg) => {
1791                                 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1792                         },
1793                         wire::Message::QueryChannelRange(msg) => {
1794                                 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1795                         },
1796                         wire::Message::ReplyChannelRange(msg) => {
1797                                 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1798                         },
1799
1800                         // Onion message:
1801                         wire::Message::OnionMessage(msg) => {
1802                                 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1803                         },
1804
1805                         // Unknown messages:
1806                         wire::Message::Unknown(type_id) if message.is_even() => {
1807                                 log_debug!(logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1808                                 return Err(PeerHandleError { }.into());
1809                         },
1810                         wire::Message::Unknown(type_id) => {
1811                                 log_trace!(logger, "Received unknown odd message of type {}, ignoring", type_id);
1812                         },
1813                         wire::Message::Custom(custom) => {
1814                                 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1815                         },
1816                 };
1817                 Ok(should_forward)
1818         }
1819
1820         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>) {
1821                 match msg {
1822                         wire::Message::ChannelAnnouncement(ref msg) => {
1823                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1824                                 let encoded_msg = encode_msg!(msg);
1825
1826                                 for (_, peer_mutex) in peers.iter() {
1827                                         let mut peer = peer_mutex.lock().unwrap();
1828                                         let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1829                                         if !peer.handshake_complete() ||
1830                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1831                                                 continue
1832                                         }
1833                                         debug_assert!(peer.their_node_id.is_some());
1834                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1835                                         if peer.buffer_full_drop_gossip_broadcast() {
1836                                                 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1837                                                 continue;
1838                                         }
1839                                         if let Some((_, their_node_id)) = peer.their_node_id {
1840                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1841                                                         continue;
1842                                                 }
1843                                         }
1844                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1845                                                 continue;
1846                                         }
1847                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1848                                 }
1849                         },
1850                         wire::Message::NodeAnnouncement(ref msg) => {
1851                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1852                                 let encoded_msg = encode_msg!(msg);
1853
1854                                 for (_, peer_mutex) in peers.iter() {
1855                                         let mut peer = peer_mutex.lock().unwrap();
1856                                         let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1857                                         if !peer.handshake_complete() ||
1858                                                         !peer.should_forward_node_announcement(msg.contents.node_id) {
1859                                                 continue
1860                                         }
1861                                         debug_assert!(peer.their_node_id.is_some());
1862                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1863                                         if peer.buffer_full_drop_gossip_broadcast() {
1864                                                 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1865                                                 continue;
1866                                         }
1867                                         if let Some((_, their_node_id)) = peer.their_node_id {
1868                                                 if their_node_id == msg.contents.node_id {
1869                                                         continue;
1870                                                 }
1871                                         }
1872                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1873                                                 continue;
1874                                         }
1875                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1876                                 }
1877                         },
1878                         wire::Message::ChannelUpdate(ref msg) => {
1879                                 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1880                                 let encoded_msg = encode_msg!(msg);
1881
1882                                 for (_, peer_mutex) in peers.iter() {
1883                                         let mut peer = peer_mutex.lock().unwrap();
1884                                         let logger = WithContext::from(&self.logger, Some(peer.their_node_id.unwrap().0), None);
1885                                         if !peer.handshake_complete() ||
1886                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1887                                                 continue
1888                                         }
1889                                         debug_assert!(peer.their_node_id.is_some());
1890                                         debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1891                                         if peer.buffer_full_drop_gossip_broadcast() {
1892                                                 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1893                                                 continue;
1894                                         }
1895                                         if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1896                                                 continue;
1897                                         }
1898                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1899                                 }
1900                         },
1901                         _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1902                 }
1903         }
1904
1905         /// Checks for any events generated by our handlers and processes them. Includes sending most
1906         /// response messages as well as messages generated by calls to handler functions directly (eg
1907         /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1908         ///
1909         /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1910         /// issues!
1911         ///
1912         /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1913         /// or one of the other clients provided in our language bindings.
1914         ///
1915         /// Note that if there are any other calls to this function waiting on lock(s) this may return
1916         /// without doing any work. All available events that need handling will be handled before the
1917         /// other calls return.
1918         ///
1919         /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1920         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1921         /// [`send_data`]: SocketDescriptor::send_data
1922         pub fn process_events(&self) {
1923                 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
1924                         // If we're not the first event processor to get here, just return early, the increment
1925                         // we just did will be treated as "go around again" at the end.
1926                         return;
1927                 }
1928
1929                 loop {
1930                         self.update_gossip_backlogged();
1931                         let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
1932
1933                         let mut peers_to_disconnect = HashMap::new();
1934
1935                         {
1936                                 let peers_lock = self.peers.read().unwrap();
1937
1938                                 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1939                                 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1940
1941                                 let peers = &*peers_lock;
1942                                 macro_rules! get_peer_for_forwarding {
1943                                         ($node_id: expr) => {
1944                                                 {
1945                                                         if peers_to_disconnect.get($node_id).is_some() {
1946                                                                 // If we've "disconnected" this peer, do not send to it.
1947                                                                 continue;
1948                                                         }
1949                                                         let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1950                                                         match descriptor_opt {
1951                                                                 Some(descriptor) => match peers.get(&descriptor) {
1952                                                                         Some(peer_mutex) => {
1953                                                                                 let peer_lock = peer_mutex.lock().unwrap();
1954                                                                                 if !peer_lock.handshake_complete() {
1955                                                                                         continue;
1956                                                                                 }
1957                                                                                 peer_lock
1958                                                                         },
1959                                                                         None => {
1960                                                                                 debug_assert!(false, "Inconsistent peers set state!");
1961                                                                                 continue;
1962                                                                         }
1963                                                                 },
1964                                                                 None => {
1965                                                                         continue;
1966                                                                 },
1967                                                         }
1968                                                 }
1969                                         }
1970                                 }
1971                                 for event in events_generated.drain(..) {
1972                                         match event {
1973                                                 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1974                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1975                                                                         log_pubkey!(node_id),
1976                                                                         &msg.temporary_channel_id);
1977                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1978                                                 },
1979                                                 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
1980                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
1981                                                                         log_pubkey!(node_id),
1982                                                                         &msg.temporary_channel_id);
1983                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1984                                                 },
1985                                                 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1986                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1987                                                                         log_pubkey!(node_id),
1988                                                                         &msg.temporary_channel_id);
1989                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1990                                                 },
1991                                                 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
1992                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}",
1993                                                                         log_pubkey!(node_id),
1994                                                                         &msg.temporary_channel_id);
1995                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1996                                                 },
1997                                                 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1998                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1999                                                                         log_pubkey!(node_id),
2000                                                                         &msg.temporary_channel_id,
2001                                                                         log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
2002                                                         // TODO: If the peer is gone we should generate a DiscardFunding event
2003                                                         // indicating to the wallet that they should just throw away this funding transaction
2004                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2005                                                 },
2006                                                 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
2007                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
2008                                                                         log_pubkey!(node_id),
2009                                                                         &msg.channel_id);
2010                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2011                                                 },
2012                                                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
2013                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReady event in peer_handler for node {} for channel {}",
2014                                                                         log_pubkey!(node_id),
2015                                                                         &msg.channel_id);
2016                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2017                                                 },
2018                                                 MessageSendEvent::SendStfu { ref node_id, ref msg} => {
2019                                                         let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2020                                                         log_debug!(logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
2021                                                                         log_pubkey!(node_id),
2022                                                                         &msg.channel_id);
2023                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2024                                                 }
2025                                                 MessageSendEvent::SendSplice { ref node_id, ref msg} => {
2026                                                         let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2027                                                         log_debug!(logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
2028                                                                         log_pubkey!(node_id),
2029                                                                         &msg.channel_id);
2030                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2031                                                 }
2032                                                 MessageSendEvent::SendSpliceAck { ref node_id, ref msg} => {
2033                                                         let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2034                                                         log_debug!(logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}",
2035                                                                         log_pubkey!(node_id),
2036                                                                         &msg.channel_id);
2037                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2038                                                 }
2039                                                 MessageSendEvent::SendSpliceLocked { ref node_id, ref msg} => {
2040                                                         let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2041                                                         log_debug!(logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}",
2042                                                                         log_pubkey!(node_id),
2043                                                                         &msg.channel_id);
2044                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2045                                                 }
2046                                                 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
2047                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
2048                                                                         log_pubkey!(node_id),
2049                                                                         &msg.channel_id);
2050                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2051                                                 },
2052                                                 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
2053                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddOutput event in peer_handler for node {} for channel {}",
2054                                                                         log_pubkey!(node_id),
2055                                                                         &msg.channel_id);
2056                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2057                                                 },
2058                                                 MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => {
2059                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
2060                                                                         log_pubkey!(node_id),
2061                                                                         &msg.channel_id);
2062                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2063                                                 },
2064                                                 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
2065                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
2066                                                                         log_pubkey!(node_id),
2067                                                                         &msg.channel_id);
2068                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2069                                                 },
2070                                                 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
2071                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxComplete event in peer_handler for node {} for channel {}",
2072                                                                         log_pubkey!(node_id),
2073                                                                         &msg.channel_id);
2074                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2075                                                 },
2076                                                 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
2077                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
2078                                                                         log_pubkey!(node_id),
2079                                                                         &msg.channel_id);
2080                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2081                                                 },
2082                                                 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
2083                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
2084                                                                         log_pubkey!(node_id),
2085                                                                         &msg.channel_id);
2086                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2087                                                 },
2088                                                 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2089                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2090                                                                         log_pubkey!(node_id),
2091                                                                         &msg.channel_id);
2092                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2093                                                 },
2094                                                 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2095                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2096                                                                         log_pubkey!(node_id),
2097                                                                         &msg.channel_id);
2098                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2099                                                 },
2100                                                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2101                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2102                                                                         log_pubkey!(node_id),
2103                                                                         &msg.channel_id);
2104                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2105                                                 },
2106                                                 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 } } => {
2107                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(commitment_signed.channel_id)), "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
2108                                                                         log_pubkey!(node_id),
2109                                                                         update_add_htlcs.len(),
2110                                                                         update_fulfill_htlcs.len(),
2111                                                                         update_fail_htlcs.len(),
2112                                                                         &commitment_signed.channel_id);
2113                                                         let mut peer = get_peer_for_forwarding!(node_id);
2114                                                         for msg in update_add_htlcs {
2115                                                                 self.enqueue_message(&mut *peer, msg);
2116                                                         }
2117                                                         for msg in update_fulfill_htlcs {
2118                                                                 self.enqueue_message(&mut *peer, msg);
2119                                                         }
2120                                                         for msg in update_fail_htlcs {
2121                                                                 self.enqueue_message(&mut *peer, msg);
2122                                                         }
2123                                                         for msg in update_fail_malformed_htlcs {
2124                                                                 self.enqueue_message(&mut *peer, msg);
2125                                                         }
2126                                                         if let &Some(ref msg) = update_fee {
2127                                                                 self.enqueue_message(&mut *peer, msg);
2128                                                         }
2129                                                         self.enqueue_message(&mut *peer, commitment_signed);
2130                                                 },
2131                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2132                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2133                                                                         log_pubkey!(node_id),
2134                                                                         &msg.channel_id);
2135                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2136                                                 },
2137                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2138                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2139                                                                         log_pubkey!(node_id),
2140                                                                         &msg.channel_id);
2141                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2142                                                 },
2143                                                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2144                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling Shutdown event in peer_handler for node {} for channel {}",
2145                                                                         log_pubkey!(node_id),
2146                                                                         &msg.channel_id);
2147                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2148                                                 },
2149                                                 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2150                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2151                                                                         log_pubkey!(node_id),
2152                                                                         &msg.channel_id);
2153                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2154                                                 },
2155                                                 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2156                                                         log_debug!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2157                                                                         log_pubkey!(node_id),
2158                                                                         msg.contents.short_channel_id);
2159                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2160                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2161                                                 },
2162                                                 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2163                                                         log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2164                                                         match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2165                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2166                                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2167                                                                 _ => {},
2168                                                         }
2169                                                         if let Some(msg) = update_msg {
2170                                                                 match self.message_handler.route_handler.handle_channel_update(&msg) {
2171                                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2172                                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2173                                                                         _ => {},
2174                                                                 }
2175                                                         }
2176                                                 },
2177                                                 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2178                                                         log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents);
2179                                                         match self.message_handler.route_handler.handle_channel_update(&msg) {
2180                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2181                                                                         self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2182                                                                 _ => {},
2183                                                         }
2184                                                 },
2185                                                 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2186                                                         log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2187                                                         match self.message_handler.route_handler.handle_node_announcement(&msg) {
2188                                                                 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2189                                                                         self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2190                                                                 _ => {},
2191                                                         }
2192                                                 },
2193                                                 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2194                                                         log_trace!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2195                                                                         log_pubkey!(node_id), msg.contents.short_channel_id);
2196                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2197                                                 },
2198                                                 MessageSendEvent::HandleError { node_id, action } => {
2199                                                         let logger = WithContext::from(&self.logger, Some(node_id), None);
2200                                                         match action {
2201                                                                 msgs::ErrorAction::DisconnectPeer { msg } => {
2202                                                                         if let Some(msg) = msg.as_ref() {
2203                                                                                 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2204                                                                                         log_pubkey!(node_id), msg.data);
2205                                                                         } else {
2206                                                                                 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2207                                                                                         log_pubkey!(node_id));
2208                                                                         }
2209                                                                         // We do not have the peers write lock, so we just store that we're
2210                                                                         // about to disconenct the peer and do it after we finish
2211                                                                         // processing most messages.
2212                                                                         let msg = msg.map(|msg| wire::Message::<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2213                                                                         peers_to_disconnect.insert(node_id, msg);
2214                                                                 },
2215                                                                 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2216                                                                         log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2217                                                                                 log_pubkey!(node_id), msg.data);
2218                                                                         // We do not have the peers write lock, so we just store that we're
2219                                                                         // about to disconenct the peer and do it after we finish
2220                                                                         // processing most messages.
2221                                                                         peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2222                                                                 },
2223                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
2224                                                                         log_given_level!(logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2225                                                                 },
2226                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2227                                                                 msgs::ErrorAction::IgnoreError => {
2228                                                                                 log_debug!(logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2229                                                                         },
2230                                                                 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2231                                                                         log_trace!(logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2232                                                                                         log_pubkey!(node_id),
2233                                                                                         msg.data);
2234                                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2235                                                                 },
2236                                                                 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2237                                                                         log_given_level!(logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2238                                                                                         log_pubkey!(node_id),
2239                                                                                         msg.data);
2240                                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2241                                                                 },
2242                                                         }
2243                                                 },
2244                                                 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2245                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2246                                                 },
2247                                                 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2248                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2249                                                 }
2250                                                 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2251                                                         log_gossip!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
2252                                                                 log_pubkey!(node_id),
2253                                                                 msg.short_channel_ids.len(),
2254                                                                 msg.first_blocknum,
2255                                                                 msg.number_of_blocks,
2256                                                                 msg.sync_complete);
2257                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2258                                                 }
2259                                                 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2260                                                         self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2261                                                 }
2262                                         }
2263                                 }
2264
2265                                 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2266                                         if peers_to_disconnect.get(&node_id).is_some() { continue; }
2267                                         self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2268                                 }
2269
2270                                 for (descriptor, peer_mutex) in peers.iter() {
2271                                         let mut peer = peer_mutex.lock().unwrap();
2272                                         if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2273                                         self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2274                                 }
2275                         }
2276                         if !peers_to_disconnect.is_empty() {
2277                                 let mut peers_lock = self.peers.write().unwrap();
2278                                 let peers = &mut *peers_lock;
2279                                 for (node_id, msg) in peers_to_disconnect.drain() {
2280                                         // Note that since we are holding the peers *write* lock we can
2281                                         // remove from node_id_to_descriptor immediately (as no other
2282                                         // thread can be holding the peer lock if we have the global write
2283                                         // lock).
2284
2285                                         let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2286                                         if let Some(mut descriptor) = descriptor_opt {
2287                                                 if let Some(peer_mutex) = peers.remove(&descriptor) {
2288                                                         let mut peer = peer_mutex.lock().unwrap();
2289                                                         if let Some(msg) = msg {
2290                                                                 self.enqueue_message(&mut *peer, &msg);
2291                                                                 // This isn't guaranteed to work, but if there is enough free
2292                                                                 // room in the send buffer, put the error message there...
2293                                                                 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2294                                                         }
2295                                                         self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2296                                                 } else { debug_assert!(false, "Missing connection for peer"); }
2297                                         }
2298                                 }
2299                         }
2300
2301                         if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2302                                 // If another thread incremented the state while we were running we should go
2303                                 // around again, but only once.
2304                                 self.event_processing_state.store(1, Ordering::Release);
2305                                 continue;
2306                         }
2307                         break;
2308                 }
2309         }
2310
2311         /// Indicates that the given socket descriptor's connection is now closed.
2312         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2313                 self.disconnect_event_internal(descriptor);
2314         }
2315
2316         fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2317                 if !peer.handshake_complete() {
2318                         log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2319                         descriptor.disconnect_socket();
2320                         return;
2321                 }
2322
2323                 debug_assert!(peer.their_node_id.is_some());
2324                 if let Some((node_id, _)) = peer.their_node_id {
2325                         log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Disconnecting peer with id {} due to {}", node_id, reason);
2326                         self.message_handler.chan_handler.peer_disconnected(&node_id);
2327                         self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2328                 }
2329                 descriptor.disconnect_socket();
2330         }
2331
2332         fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2333                 let mut peers = self.peers.write().unwrap();
2334                 let peer_option = peers.remove(descriptor);
2335                 match peer_option {
2336                         None => {
2337                                 // This is most likely a simple race condition where the user found that the socket
2338                                 // was disconnected, then we told the user to `disconnect_socket()`, then they
2339                                 // called this method. Either way we're disconnected, return.
2340                         },
2341                         Some(peer_lock) => {
2342                                 let peer = peer_lock.lock().unwrap();
2343                                 if let Some((node_id, _)) = peer.their_node_id {
2344                                         log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Handling disconnection of peer {}", log_pubkey!(node_id));
2345                                         let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2346                                         debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2347                                         if !peer.handshake_complete() { return; }
2348                                         self.message_handler.chan_handler.peer_disconnected(&node_id);
2349                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2350                                 }
2351                         }
2352                 };
2353         }
2354
2355         /// Disconnect a peer given its node id.
2356         ///
2357         /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2358         /// peer. Thus, be very careful about reentrancy issues.
2359         ///
2360         /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2361         pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2362                 let mut peers_lock = self.peers.write().unwrap();
2363                 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2364                         let peer_opt = peers_lock.remove(&descriptor);
2365                         if let Some(peer_mutex) = peer_opt {
2366                                 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2367                         } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2368                 }
2369         }
2370
2371         /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2372         /// an indication that TCP sockets have stalled even if we weren't around to time them out
2373         /// using regular ping/pongs.
2374         pub fn disconnect_all_peers(&self) {
2375                 let mut peers_lock = self.peers.write().unwrap();
2376                 self.node_id_to_descriptor.lock().unwrap().clear();
2377                 let peers = &mut *peers_lock;
2378                 for (descriptor, peer_mutex) in peers.drain() {
2379                         self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2380                 }
2381         }
2382
2383         /// This is called when we're blocked on sending additional gossip messages until we receive a
2384         /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2385         /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2386         fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2387                 if peer.awaiting_pong_timer_tick_intervals == 0 {
2388                         peer.awaiting_pong_timer_tick_intervals = -1;
2389                         let ping = msgs::Ping {
2390                                 ponglen: 0,
2391                                 byteslen: 64,
2392                         };
2393                         self.enqueue_message(peer, &ping);
2394                 }
2395         }
2396
2397         /// Send pings to each peer and disconnect those which did not respond to the last round of
2398         /// pings.
2399         ///
2400         /// This may be called on any timescale you want, however, roughly once every ten seconds is
2401         /// preferred. The call rate determines both how often we send a ping to our peers and how much
2402         /// time they have to respond before we disconnect them.
2403         ///
2404         /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2405         /// issues!
2406         ///
2407         /// [`send_data`]: SocketDescriptor::send_data
2408         pub fn timer_tick_occurred(&self) {
2409                 let mut descriptors_needing_disconnect = Vec::new();
2410                 {
2411                         let peers_lock = self.peers.read().unwrap();
2412
2413                         self.update_gossip_backlogged();
2414                         let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2415
2416                         for (descriptor, peer_mutex) in peers_lock.iter() {
2417                                 let mut peer = peer_mutex.lock().unwrap();
2418                                 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2419
2420                                 if !peer.handshake_complete() {
2421                                         // The peer needs to complete its handshake before we can exchange messages. We
2422                                         // give peers one timer tick to complete handshake, reusing
2423                                         // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2424                                         // for handshake completion.
2425                                         if peer.awaiting_pong_timer_tick_intervals != 0 {
2426                                                 descriptors_needing_disconnect.push(descriptor.clone());
2427                                         } else {
2428                                                 peer.awaiting_pong_timer_tick_intervals = 1;
2429                                         }
2430                                         continue;
2431                                 }
2432                                 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2433                                 debug_assert!(peer.their_node_id.is_some());
2434
2435                                 loop { // Used as a `goto` to skip writing a Ping message.
2436                                         if peer.awaiting_pong_timer_tick_intervals == -1 {
2437                                                 // Magic value set in `maybe_send_extra_ping`.
2438                                                 peer.awaiting_pong_timer_tick_intervals = 1;
2439                                                 peer.received_message_since_timer_tick = false;
2440                                                 break;
2441                                         }
2442
2443                                         if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2444                                                 || peer.awaiting_pong_timer_tick_intervals as u64 >
2445                                                         MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2446                                         {
2447                                                 descriptors_needing_disconnect.push(descriptor.clone());
2448                                                 break;
2449                                         }
2450                                         peer.received_message_since_timer_tick = false;
2451
2452                                         if peer.awaiting_pong_timer_tick_intervals > 0 {
2453                                                 peer.awaiting_pong_timer_tick_intervals += 1;
2454                                                 break;
2455                                         }
2456
2457                                         peer.awaiting_pong_timer_tick_intervals = 1;
2458                                         let ping = msgs::Ping {
2459                                                 ponglen: 0,
2460                                                 byteslen: 64,
2461                                         };
2462                                         self.enqueue_message(&mut *peer, &ping);
2463                                         break;
2464                                 }
2465                                 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2466                         }
2467                 }
2468
2469                 if !descriptors_needing_disconnect.is_empty() {
2470                         {
2471                                 let mut peers_lock = self.peers.write().unwrap();
2472                                 for descriptor in descriptors_needing_disconnect {
2473                                         if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2474                                                 let peer = peer_mutex.lock().unwrap();
2475                                                 if let Some((node_id, _)) = peer.their_node_id {
2476                                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2477                                                 }
2478                                                 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2479                                         }
2480                                 }
2481                         }
2482                 }
2483         }
2484
2485         #[allow(dead_code)]
2486         // Messages of up to 64KB should never end up more than half full with addresses, as that would
2487         // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2488         // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2489         // message...
2490         const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (SocketAddress::MAX_LEN as u32 + 1) / 2;
2491         #[allow(dead_code)]
2492         // ...by failing to compile if the number of addresses that would be half of a message is
2493         // smaller than 100:
2494         const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2495
2496         /// Generates a signed node_announcement from the given arguments, sending it to all connected
2497         /// peers. Note that peers will likely ignore this message unless we have at least one public
2498         /// channel which has at least six confirmations on-chain.
2499         ///
2500         /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2501         /// node to humans. They carry no in-protocol meaning.
2502         ///
2503         /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2504         /// accepts incoming connections. These will be included in the node_announcement, publicly
2505         /// tying these addresses together and to this node. If you wish to preserve user privacy,
2506         /// addresses should likely contain only Tor Onion addresses.
2507         ///
2508         /// Panics if `addresses` is absurdly large (more than 100).
2509         ///
2510         /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2511         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<SocketAddress>) {
2512                 if addresses.len() > 100 {
2513                         panic!("More than half the message size was taken up by public addresses!");
2514                 }
2515
2516                 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2517                 // addresses be sorted for future compatibility.
2518                 addresses.sort_by_key(|addr| addr.get_id());
2519
2520                 let features = self.message_handler.chan_handler.provided_node_features()
2521                         | self.message_handler.route_handler.provided_node_features()
2522                         | self.message_handler.onion_message_handler.provided_node_features()
2523                         | self.message_handler.custom_message_handler.provided_node_features();
2524                 let announcement = msgs::UnsignedNodeAnnouncement {
2525                         features,
2526                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2527                         node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2528                         rgb,
2529                         alias: NodeAlias(alias),
2530                         addresses,
2531                         excess_address_data: Vec::new(),
2532                         excess_data: Vec::new(),
2533                 };
2534                 let node_announce_sig = match self.node_signer.sign_gossip_message(
2535                         msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2536                 ) {
2537                         Ok(sig) => sig,
2538                         Err(_) => {
2539                                 log_error!(self.logger, "Failed to generate signature for node_announcement");
2540                                 return;
2541                         },
2542                 };
2543
2544                 let msg = msgs::NodeAnnouncement {
2545                         signature: node_announce_sig,
2546                         contents: announcement
2547                 };
2548
2549                 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2550                 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2551                 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2552         }
2553 }
2554
2555 fn is_gossip_msg(type_id: u16) -> bool {
2556         match type_id {
2557                 msgs::ChannelAnnouncement::TYPE |
2558                 msgs::ChannelUpdate::TYPE |
2559                 msgs::NodeAnnouncement::TYPE |
2560                 msgs::QueryChannelRange::TYPE |
2561                 msgs::ReplyChannelRange::TYPE |
2562                 msgs::QueryShortChannelIds::TYPE |
2563                 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2564                 _ => false
2565         }
2566 }
2567
2568 #[cfg(test)]
2569 mod tests {
2570         use crate::sign::{NodeSigner, Recipient};
2571         use crate::events;
2572         use crate::io;
2573         use crate::ln::ChannelId;
2574         use crate::ln::features::{InitFeatures, NodeFeatures};
2575         use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2576         use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2577         use crate::ln::{msgs, wire};
2578         use crate::ln::msgs::{LightningError, SocketAddress};
2579         use crate::util::test_utils;
2580
2581         use bitcoin::Network;
2582         use bitcoin::blockdata::constants::ChainHash;
2583         use bitcoin::secp256k1::{PublicKey, SecretKey};
2584
2585         use crate::prelude::*;
2586         use crate::sync::{Arc, Mutex};
2587         use core::convert::Infallible;
2588         use core::sync::atomic::{AtomicBool, Ordering};
2589
2590         #[derive(Clone)]
2591         struct FileDescriptor {
2592                 fd: u16,
2593                 outbound_data: Arc<Mutex<Vec<u8>>>,
2594                 disconnect: Arc<AtomicBool>,
2595         }
2596         impl PartialEq for FileDescriptor {
2597                 fn eq(&self, other: &Self) -> bool {
2598                         self.fd == other.fd
2599                 }
2600         }
2601         impl Eq for FileDescriptor { }
2602         impl core::hash::Hash for FileDescriptor {
2603                 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2604                         self.fd.hash(hasher)
2605                 }
2606         }
2607
2608         impl SocketDescriptor for FileDescriptor {
2609                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2610                         self.outbound_data.lock().unwrap().extend_from_slice(data);
2611                         data.len()
2612                 }
2613
2614                 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2615         }
2616
2617         struct PeerManagerCfg {
2618                 chan_handler: test_utils::TestChannelMessageHandler,
2619                 routing_handler: test_utils::TestRoutingMessageHandler,
2620                 custom_handler: TestCustomMessageHandler,
2621                 logger: test_utils::TestLogger,
2622                 node_signer: test_utils::TestNodeSigner,
2623         }
2624
2625         struct TestCustomMessageHandler {
2626                 features: InitFeatures,
2627         }
2628
2629         impl wire::CustomMessageReader for TestCustomMessageHandler {
2630                 type CustomMessage = Infallible;
2631                 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2632                         Ok(None)
2633                 }
2634         }
2635
2636         impl CustomMessageHandler for TestCustomMessageHandler {
2637                 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2638                         unreachable!();
2639                 }
2640
2641                 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2642
2643                 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2644
2645                 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2646                         self.features.clone()
2647                 }
2648         }
2649
2650         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2651                 let mut cfgs = Vec::new();
2652                 for i in 0..peer_count {
2653                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2654                         let features = {
2655                                 let mut feature_bits = vec![0u8; 33];
2656                                 feature_bits[32] = 0b00000001;
2657                                 InitFeatures::from_le_bytes(feature_bits)
2658                         };
2659                         cfgs.push(
2660                                 PeerManagerCfg{
2661                                         chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2662                                         logger: test_utils::TestLogger::new(),
2663                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2664                                         custom_handler: TestCustomMessageHandler { features },
2665                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2666                                 }
2667                         );
2668                 }
2669
2670                 cfgs
2671         }
2672
2673         fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2674                 let mut cfgs = Vec::new();
2675                 for i in 0..peer_count {
2676                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2677                         let features = {
2678                                 let mut feature_bits = vec![0u8; 33 + i + 1];
2679                                 feature_bits[33 + i] = 0b00000001;
2680                                 InitFeatures::from_le_bytes(feature_bits)
2681                         };
2682                         cfgs.push(
2683                                 PeerManagerCfg{
2684                                         chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2685                                         logger: test_utils::TestLogger::new(),
2686                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2687                                         custom_handler: TestCustomMessageHandler { features },
2688                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2689                                 }
2690                         );
2691                 }
2692
2693                 cfgs
2694         }
2695
2696         fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2697                 let mut cfgs = Vec::new();
2698                 for i in 0..peer_count {
2699                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2700                         let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2701                         let network = ChainHash::from(&[i as u8; 32]);
2702                         cfgs.push(
2703                                 PeerManagerCfg{
2704                                         chan_handler: test_utils::TestChannelMessageHandler::new(network),
2705                                         logger: test_utils::TestLogger::new(),
2706                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2707                                         custom_handler: TestCustomMessageHandler { features },
2708                                         node_signer: test_utils::TestNodeSigner::new(node_secret),
2709                                 }
2710                         );
2711                 }
2712
2713                 cfgs
2714         }
2715
2716         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, &'a TestCustomMessageHandler, &'a test_utils::TestNodeSigner>> {
2717                 let mut peers = Vec::new();
2718                 for i in 0..peer_count {
2719                         let ephemeral_bytes = [i as u8; 32];
2720                         let msg_handler = MessageHandler {
2721                                 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2722                                 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2723                         };
2724                         let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2725                         peers.push(peer);
2726                 }
2727
2728                 peers
2729         }
2730
2731         fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, &'a TestCustomMessageHandler, &'a test_utils::TestNodeSigner>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, &'a TestCustomMessageHandler, &'a test_utils::TestNodeSigner>) -> (FileDescriptor, FileDescriptor) {
2732                 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2733                 let mut fd_a = FileDescriptor {
2734                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2735                         disconnect: Arc::new(AtomicBool::new(false)),
2736                 };
2737                 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2738                 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2739                 let mut fd_b = FileDescriptor {
2740                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2741                         disconnect: Arc::new(AtomicBool::new(false)),
2742                 };
2743                 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2744                 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2745                 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2746                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2747                 peer_a.process_events();
2748
2749                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2750                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2751
2752                 peer_b.process_events();
2753                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2754                 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2755
2756                 peer_a.process_events();
2757                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2758                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2759
2760                 assert!(peer_a.get_peer_node_ids().contains(&(id_b, Some(addr_b))));
2761                 assert!(peer_b.get_peer_node_ids().contains(&(id_a, Some(addr_a))));
2762
2763                 (fd_a.clone(), fd_b.clone())
2764         }
2765
2766         #[test]
2767         #[cfg(feature = "std")]
2768         fn fuzz_threaded_connections() {
2769                 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2770                 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2771                 // with our internal map consistency, and is a generally good smoke test of disconnection.
2772                 let cfgs = Arc::new(create_peermgr_cfgs(2));
2773                 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2774                 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2775
2776                 let start_time = std::time::Instant::now();
2777                 macro_rules! spawn_thread { ($id: expr) => { {
2778                         let peers = Arc::clone(&peers);
2779                         let cfgs = Arc::clone(&cfgs);
2780                         std::thread::spawn(move || {
2781                                 let mut ctr = 0;
2782                                 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2783                                         let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2784                                         let mut fd_a = FileDescriptor {
2785                                                 fd: $id  + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2786                                                 disconnect: Arc::new(AtomicBool::new(false)),
2787                                         };
2788                                         let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2789                                         let mut fd_b = FileDescriptor {
2790                                                 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2791                                                 disconnect: Arc::new(AtomicBool::new(false)),
2792                                         };
2793                                         let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2794                                         let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2795                                         peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2796                                         if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2797
2798                                         while start_time.elapsed() < std::time::Duration::from_secs(1) {
2799                                                 peers[0].process_events();
2800                                                 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2801                                                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2802                                                 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2803
2804                                                 peers[1].process_events();
2805                                                 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2806                                                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2807                                                 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2808
2809                                                 cfgs[0].chan_handler.pending_events.lock().unwrap()
2810                                                         .push(crate::events::MessageSendEvent::SendShutdown {
2811                                                                 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2812                                                                 msg: msgs::Shutdown {
2813                                                                         channel_id: ChannelId::new_zero(),
2814                                                                         scriptpubkey: bitcoin::ScriptBuf::new(),
2815                                                                 },
2816                                                         });
2817                                                 cfgs[1].chan_handler.pending_events.lock().unwrap()
2818                                                         .push(crate::events::MessageSendEvent::SendShutdown {
2819                                                                 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2820                                                                 msg: msgs::Shutdown {
2821                                                                         channel_id: ChannelId::new_zero(),
2822                                                                         scriptpubkey: bitcoin::ScriptBuf::new(),
2823                                                                 },
2824                                                         });
2825
2826                                                 if ctr % 2 == 0 {
2827                                                         peers[0].timer_tick_occurred();
2828                                                         peers[1].timer_tick_occurred();
2829                                                 }
2830                                         }
2831
2832                                         peers[0].socket_disconnected(&fd_a);
2833                                         peers[1].socket_disconnected(&fd_b);
2834                                         ctr += 1;
2835                                         std::thread::sleep(std::time::Duration::from_micros(1));
2836                                 }
2837                         })
2838                 } } }
2839                 let thrd_a = spawn_thread!(1);
2840                 let thrd_b = spawn_thread!(2);
2841
2842                 thrd_a.join().unwrap();
2843                 thrd_b.join().unwrap();
2844         }
2845
2846         #[test]
2847         fn test_feature_incompatible_peers() {
2848                 let cfgs = create_peermgr_cfgs(2);
2849                 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2850
2851                 let peers = create_network(2, &cfgs);
2852                 let incompatible_peers = create_network(2, &incompatible_cfgs);
2853                 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2854                 for (peer_a, peer_b) in peer_pairs.iter() {
2855                         let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2856                         let mut fd_a = FileDescriptor {
2857                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2858                                 disconnect: Arc::new(AtomicBool::new(false)),
2859                         };
2860                         let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2861                         let mut fd_b = FileDescriptor {
2862                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2863                                 disconnect: Arc::new(AtomicBool::new(false)),
2864                         };
2865                         let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2866                         let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2867                         peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2868                         assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2869                         peer_a.process_events();
2870
2871                         let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2872                         assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2873
2874                         peer_b.process_events();
2875                         let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2876
2877                         // Should fail because of unknown required features
2878                         assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2879                 }
2880         }
2881
2882         #[test]
2883         fn test_chain_incompatible_peers() {
2884                 let cfgs = create_peermgr_cfgs(2);
2885                 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
2886
2887                 let peers = create_network(2, &cfgs);
2888                 let incompatible_peers = create_network(2, &incompatible_cfgs);
2889                 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2890                 for (peer_a, peer_b) in peer_pairs.iter() {
2891                         let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2892                         let mut fd_a = FileDescriptor {
2893                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2894                                 disconnect: Arc::new(AtomicBool::new(false)),
2895                         };
2896                         let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2897                         let mut fd_b = FileDescriptor {
2898                                 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2899                                 disconnect: Arc::new(AtomicBool::new(false)),
2900                         };
2901                         let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2902                         let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2903                         peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2904                         assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2905                         peer_a.process_events();
2906
2907                         let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2908                         assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2909
2910                         peer_b.process_events();
2911                         let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2912
2913                         // Should fail because of incompatible chains
2914                         assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2915                 }
2916         }
2917
2918         #[test]
2919         fn test_disconnect_peer() {
2920                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2921                 // push a DisconnectPeer event to remove the node flagged by id
2922                 let cfgs = create_peermgr_cfgs(2);
2923                 let peers = create_network(2, &cfgs);
2924                 establish_connection(&peers[0], &peers[1]);
2925                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2926
2927                 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2928                 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2929                         node_id: their_id,
2930                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
2931                 });
2932
2933                 peers[0].process_events();
2934                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2935         }
2936
2937         #[test]
2938         fn test_send_simple_msg() {
2939                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2940                 // push a message from one peer to another.
2941                 let cfgs = create_peermgr_cfgs(2);
2942                 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2943                 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2944                 let mut peers = create_network(2, &cfgs);
2945                 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2946                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2947
2948                 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2949
2950                 let msg = msgs::Shutdown { channel_id: ChannelId::from_bytes([42; 32]), scriptpubkey: bitcoin::ScriptBuf::new() };
2951                 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2952                         node_id: their_id, msg: msg.clone()
2953                 });
2954                 peers[0].message_handler.chan_handler = &a_chan_handler;
2955
2956                 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2957                 peers[1].message_handler.chan_handler = &b_chan_handler;
2958
2959                 peers[0].process_events();
2960
2961                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2962                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2963         }
2964
2965         #[test]
2966         fn test_non_init_first_msg() {
2967                 // Simple test of the first message received over a connection being something other than
2968                 // Init. This results in an immediate disconnection, which previously included a spurious
2969                 // peer_disconnected event handed to event handlers (which would panic in
2970                 // `TestChannelMessageHandler` here).
2971                 let cfgs = create_peermgr_cfgs(2);
2972                 let peers = create_network(2, &cfgs);
2973
2974                 let mut fd_dup = FileDescriptor {
2975                         fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2976                         disconnect: Arc::new(AtomicBool::new(false)),
2977                 };
2978                 let addr_dup = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1003};
2979                 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
2980                 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
2981
2982                 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
2983                 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
2984                 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
2985                 peers[0].process_events();
2986
2987                 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
2988                 let (act_three, _) =
2989                         dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
2990                 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
2991
2992                 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
2993                 let msg_bytes = dup_encryptor.encrypt_message(&not_init_msg);
2994                 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
2995         }
2996
2997         #[test]
2998         fn test_disconnect_all_peer() {
2999                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3000                 // then calls disconnect_all_peers
3001                 let cfgs = create_peermgr_cfgs(2);
3002                 let peers = create_network(2, &cfgs);
3003                 establish_connection(&peers[0], &peers[1]);
3004                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3005
3006                 peers[0].disconnect_all_peers();
3007                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3008         }
3009
3010         #[test]
3011         fn test_timer_tick_occurred() {
3012                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
3013                 let cfgs = create_peermgr_cfgs(2);
3014                 let peers = create_network(2, &cfgs);
3015                 establish_connection(&peers[0], &peers[1]);
3016                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3017
3018                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
3019                 peers[0].timer_tick_occurred();
3020                 peers[0].process_events();
3021                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3022
3023                 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
3024                 peers[0].timer_tick_occurred();
3025                 peers[0].process_events();
3026                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3027         }
3028
3029         #[test]
3030         fn test_do_attempt_write_data() {
3031                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
3032                 let cfgs = create_peermgr_cfgs(2);
3033                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3034                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3035                 let peers = create_network(2, &cfgs);
3036
3037                 // By calling establish_connect, we trigger do_attempt_write_data between
3038                 // the peers. Previously this function would mistakenly enter an infinite loop
3039                 // when there were more channel messages available than could fit into a peer's
3040                 // buffer. This issue would now be detected by this test (because we use custom
3041                 // RoutingMessageHandlers that intentionally return more channel messages
3042                 // than can fit into a peer's buffer).
3043                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3044
3045                 // Make each peer to read the messages that the other peer just wrote to them. Note that
3046                 // due to the max-message-before-ping limits this may take a few iterations to complete.
3047                 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
3048                         peers[1].process_events();
3049                         let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3050                         assert!(!a_read_data.is_empty());
3051
3052                         peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
3053                         peers[0].process_events();
3054
3055                         let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3056                         assert!(!b_read_data.is_empty());
3057                         peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
3058
3059                         peers[0].process_events();
3060                         assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
3061                 }
3062
3063                 // Check that each peer has received the expected number of channel updates and channel
3064                 // announcements.
3065                 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3066                 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3067                 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3068                 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3069         }
3070
3071         #[test]
3072         fn test_handshake_timeout() {
3073                 // Tests that we time out a peer still waiting on handshake completion after a full timer
3074                 // tick.
3075                 let cfgs = create_peermgr_cfgs(2);
3076                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3077                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3078                 let peers = create_network(2, &cfgs);
3079
3080                 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
3081                 let mut fd_a = FileDescriptor {
3082                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3083                         disconnect: Arc::new(AtomicBool::new(false)),
3084                 };
3085                 let mut fd_b = FileDescriptor {
3086                         fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3087                         disconnect: Arc::new(AtomicBool::new(false)),
3088                 };
3089                 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3090                 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3091
3092                 // If we get a single timer tick before completion, that's fine
3093                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3094                 peers[0].timer_tick_occurred();
3095                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3096
3097                 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3098                 peers[0].process_events();
3099                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3100                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3101                 peers[1].process_events();
3102
3103                 // ...but if we get a second timer tick, we should disconnect the peer
3104                 peers[0].timer_tick_occurred();
3105                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3106
3107                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3108                 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3109         }
3110
3111         #[test]
3112         fn test_filter_addresses(){
3113                 // Tests the filter_addresses function.
3114
3115                 // For (10/8)
3116                 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 0, 0], port: 1000};
3117                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3118                 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 255, 201], port: 1000};
3119                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3120                 let ip_address = SocketAddress::TcpIpV4{addr: [10, 255, 255, 255], port: 1000};
3121                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3122
3123                 // For (0/8)
3124                 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 0, 0], port: 1000};
3125                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3126                 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 255, 187], port: 1000};
3127                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3128                 let ip_address = SocketAddress::TcpIpV4{addr: [0, 255, 255, 255], port: 1000};
3129                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3130
3131                 // For (100.64/10)
3132                 let ip_address = SocketAddress::TcpIpV4{addr: [100, 64, 0, 0], port: 1000};
3133                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3134                 let ip_address = SocketAddress::TcpIpV4{addr: [100, 78, 255, 0], port: 1000};
3135                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3136                 let ip_address = SocketAddress::TcpIpV4{addr: [100, 127, 255, 255], port: 1000};
3137                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3138
3139                 // For (127/8)
3140                 let ip_address = SocketAddress::TcpIpV4{addr: [127, 0, 0, 0], port: 1000};
3141                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3142                 let ip_address = SocketAddress::TcpIpV4{addr: [127, 65, 73, 0], port: 1000};
3143                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3144                 let ip_address = SocketAddress::TcpIpV4{addr: [127, 255, 255, 255], port: 1000};
3145                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3146
3147                 // For (169.254/16)
3148                 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 0, 0], port: 1000};
3149                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3150                 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 221, 101], port: 1000};
3151                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3152                 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 255, 255], port: 1000};
3153                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3154
3155                 // For (172.16/12)
3156                 let ip_address = SocketAddress::TcpIpV4{addr: [172, 16, 0, 0], port: 1000};
3157                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3158                 let ip_address = SocketAddress::TcpIpV4{addr: [172, 27, 101, 23], port: 1000};
3159                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3160                 let ip_address = SocketAddress::TcpIpV4{addr: [172, 31, 255, 255], port: 1000};
3161                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3162
3163                 // For (192.168/16)
3164                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 0, 0], port: 1000};
3165                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3166                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 205, 159], port: 1000};
3167                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3168                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 255, 255], port: 1000};
3169                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3170
3171                 // For (192.88.99/24)
3172                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 0], port: 1000};
3173                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3174                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 140], port: 1000};
3175                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3176                 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 255], port: 1000};
3177                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3178
3179                 // For other IPv4 addresses
3180                 let ip_address = SocketAddress::TcpIpV4{addr: [188, 255, 99, 0], port: 1000};
3181                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3182                 let ip_address = SocketAddress::TcpIpV4{addr: [123, 8, 129, 14], port: 1000};
3183                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3184                 let ip_address = SocketAddress::TcpIpV4{addr: [2, 88, 9, 255], port: 1000};
3185                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3186
3187                 // For (2000::/3)
3188                 let ip_address = SocketAddress::TcpIpV6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3189                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3190                 let ip_address = SocketAddress::TcpIpV6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3191                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3192                 let ip_address = SocketAddress::TcpIpV6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3193                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3194
3195                 // For other IPv6 addresses
3196                 let ip_address = SocketAddress::TcpIpV6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3197                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3198                 let ip_address = SocketAddress::TcpIpV6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3199                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3200                 let ip_address = SocketAddress::TcpIpV6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3201                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3202
3203                 // For (None)
3204                 assert_eq!(filter_addresses(None), None);
3205         }
3206
3207         #[test]
3208         #[cfg(feature = "std")]
3209         fn test_process_events_multithreaded() {
3210                 use std::time::{Duration, Instant};
3211                 // Test that `process_events` getting called on multiple threads doesn't generate too many
3212                 // loop iterations.
3213                 // Each time `process_events` goes around the loop we call
3214                 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3215                 // Because the loop should go around once more after a call which fails to take the
3216                 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3217                 // should never observe there having been more than 2 loop iterations.
3218                 // Further, because the last thread to exit will call `process_events` before returning, we
3219                 // should always have at least one count at the end.
3220                 let cfg = Arc::new(create_peermgr_cfgs(1));
3221                 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3222                 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3223
3224                 let exit_flag = Arc::new(AtomicBool::new(false));
3225                 macro_rules! spawn_thread { () => { {
3226                         let thread_cfg = Arc::clone(&cfg);
3227                         let thread_peer = Arc::clone(&peer);
3228                         let thread_exit = Arc::clone(&exit_flag);
3229                         std::thread::spawn(move || {
3230                                 while !thread_exit.load(Ordering::Acquire) {
3231                                         thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3232                                         thread_peer.process_events();
3233                                         std::thread::sleep(Duration::from_micros(1));
3234                                 }
3235                         })
3236                 } } }
3237
3238                 let thread_a = spawn_thread!();
3239                 let thread_b = spawn_thread!();
3240                 let thread_c = spawn_thread!();
3241
3242                 let start_time = Instant::now();
3243                 while start_time.elapsed() < Duration::from_millis(100) {
3244                         let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3245                         assert!(val <= 2);
3246                         std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3247                 }
3248
3249                 exit_flag.store(true, Ordering::Release);
3250                 thread_a.join().unwrap();
3251                 thread_b.join().unwrap();
3252                 thread_c.join().unwrap();
3253                 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);
3254         }
3255 }