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