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