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