1 // This file is Copyright its original authors, visible in version control
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
10 //! Top level peer message handling and socket handling logic lives here.
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.
18 use bitcoin::blockdata::constants::ChainHash;
19 use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
21 use crate::sign::{NodeSigner, Recipient};
22 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
23 use crate::ln::types::ChannelId;
24 use crate::ln::features::{InitFeatures, NodeFeatures};
26 use crate::ln::msgs::{ChannelMessageHandler, Init, LightningError, SocketAddress, OnionMessageHandler, RoutingMessageHandler};
27 use crate::util::ser::{VecWriter, Writeable, Writer};
28 use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor, NextNoiseStep, MessageBuf, MSG_BUF_ALLOC_SIZE};
30 use crate::ln::wire::{Encode, Type};
31 use crate::onion_message::async_payments::{AsyncPaymentsMessageHandler, HeldHtlcAvailable, ReleaseHeldHtlc};
32 use crate::onion_message::messenger::{CustomOnionMessageHandler, PendingOnionMessage, Responder, ResponseInstruction};
33 use crate::onion_message::offers::{OffersMessage, OffersMessageHandler};
34 use crate::onion_message::packet::OnionMessageContents;
35 use crate::routing::gossip::{NodeId, NodeAlias};
36 use crate::util::atomic_counter::AtomicCounter;
37 use crate::util::logger::{Level, Logger, WithContext};
38 use crate::util::string::PrintableString;
40 #[allow(unused_imports)]
41 use crate::prelude::*;
44 use crate::sync::{Mutex, MutexGuard, FairRwLock};
45 use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering};
46 use core::{cmp, hash, fmt, mem};
48 use core::convert::Infallible;
49 #[cfg(feature = "std")]
51 #[cfg(not(c_bindings))]
53 crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager},
54 crate::onion_message::messenger::{SimpleArcOnionMessenger, SimpleRefOnionMessenger},
55 crate::routing::gossip::{NetworkGraph, P2PGossipSync},
56 crate::sign::KeysManager,
60 use bitcoin::hashes::sha256::Hash as Sha256;
61 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
62 use bitcoin::hashes::{HashEngine, Hash};
64 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
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.
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
72 pub 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`]
76 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
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)>;
83 /// Indicates a peer disconnected.
84 fn peer_disconnected(&self, their_node_id: &PublicKey);
86 /// Handle a peer connecting.
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 fn peer_connected(&self, their_node_id: &PublicKey, msg: &Init, inbound: bool) -> Result<(), ()>;
93 /// Gets the node feature flags which this handler itself supports. All available handlers are
94 /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
95 /// which are broadcasted in our [`NodeAnnouncement`] message.
97 /// [`NodeAnnouncement`]: crate::ln::msgs::NodeAnnouncement
98 fn provided_node_features(&self) -> NodeFeatures;
100 /// Gets the init feature flags which should be sent to the given peer. All available handlers
101 /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
102 /// which are sent in our [`Init`] message.
104 /// [`Init`]: crate::ln::msgs::Init
105 fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
108 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
109 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
110 pub struct IgnoringMessageHandler{}
111 impl MessageSendEventsProvider for IgnoringMessageHandler {
112 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
114 impl RoutingMessageHandler for IgnoringMessageHandler {
115 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
116 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
117 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
118 fn get_next_channel_announcement(&self, _starting_point: u64) ->
119 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
120 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
121 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
122 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
123 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
124 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
125 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
126 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
127 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
128 let mut features = InitFeatures::empty();
129 features.set_gossip_queries_optional();
132 fn processing_queue_high(&self) -> bool { false }
135 impl 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()
147 impl OffersMessageHandler for IgnoringMessageHandler {
148 fn handle_message(&self, _message: OffersMessage, _responder: Option<Responder>) -> ResponseInstruction<OffersMessage> {
149 ResponseInstruction::NoResponse
152 impl AsyncPaymentsMessageHandler for IgnoringMessageHandler {
153 fn held_htlc_available(
154 &self, _message: HeldHtlcAvailable, _responder: Option<Responder>,
155 ) -> ResponseInstruction<ReleaseHeldHtlc> {
156 ResponseInstruction::NoResponse
158 fn release_held_htlc(&self, _message: ReleaseHeldHtlc) {}
160 impl CustomOnionMessageHandler for IgnoringMessageHandler {
161 type CustomMessage = Infallible;
162 fn handle_custom_message(&self, _message: Self::CustomMessage, _responder: Option<Responder>) -> ResponseInstruction<Self::CustomMessage> {
163 // Since we always return `None` in the read the handle method should never be called.
166 fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
169 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Infallible>> {
174 impl OnionMessageContents for Infallible {
175 fn tlv_type(&self) -> u64 { unreachable!(); }
176 fn msg_type(&self) -> &'static str { unreachable!(); }
179 impl Deref for IgnoringMessageHandler {
180 type Target = IgnoringMessageHandler;
181 fn deref(&self) -> &Self { self }
184 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
185 // method that takes self for it.
186 impl wire::Type for Infallible {
187 fn type_id(&self) -> u16 {
191 impl Writeable for Infallible {
192 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
197 impl wire::CustomMessageReader for IgnoringMessageHandler {
198 type CustomMessage = Infallible;
199 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
204 impl CustomMessageHandler for IgnoringMessageHandler {
205 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
206 // Since we always return `None` in the read the handle method should never be called.
210 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
212 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
214 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
216 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
218 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
219 InitFeatures::empty()
223 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
224 /// You can provide one of these as the route_handler in a MessageHandler.
225 pub struct ErroringMessageHandler {
226 message_queue: Mutex<Vec<MessageSendEvent>>
228 impl ErroringMessageHandler {
229 /// Constructs a new ErroringMessageHandler
230 pub fn new() -> Self {
231 Self { message_queue: Mutex::new(Vec::new()) }
233 fn push_error(&self, node_id: &PublicKey, channel_id: ChannelId) {
234 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
235 action: msgs::ErrorAction::SendErrorMessage {
236 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
238 node_id: node_id.clone(),
242 impl MessageSendEventsProvider for ErroringMessageHandler {
243 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
244 let mut res = Vec::new();
245 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
249 impl ChannelMessageHandler for ErroringMessageHandler {
250 // Any messages which are related to a specific channel generate an error message to let the
251 // peer know we don't care about channels.
252 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
253 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
255 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
256 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
258 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
259 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
261 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
262 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
264 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
265 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
267 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
268 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
270 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
271 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
273 fn handle_stfu(&self, their_node_id: &PublicKey, msg: &msgs::Stfu) {
274 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
277 fn handle_splice(&self, their_node_id: &PublicKey, msg: &msgs::Splice) {
278 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
281 fn handle_splice_ack(&self, their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
282 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
285 fn handle_splice_locked(&self, their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
286 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
288 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
289 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
291 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
292 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
294 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
295 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
297 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
298 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
300 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
301 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
303 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
304 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
306 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
307 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
309 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
310 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
312 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
313 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
315 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
316 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
317 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
318 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
319 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
320 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
321 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
322 // Set a number of features which various nodes may require to talk to us. It's totally
323 // reasonable to indicate we "support" all kinds of channel features...we just reject all
325 let mut features = InitFeatures::empty();
326 features.set_data_loss_protect_optional();
327 features.set_upfront_shutdown_script_optional();
328 features.set_variable_length_onion_optional();
329 features.set_static_remote_key_optional();
330 features.set_payment_secret_optional();
331 features.set_basic_mpp_optional();
332 features.set_wumbo_optional();
333 features.set_shutdown_any_segwit_optional();
334 features.set_channel_type_optional();
335 features.set_scid_privacy_optional();
336 features.set_zero_conf_optional();
337 features.set_route_blinding_optional();
341 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
342 // We don't enforce any chains upon peer connection for `ErroringMessageHandler` and leave it up
343 // to users of `ErroringMessageHandler` to make decisions on network compatiblility.
344 // There's not really any way to pull in specific networks here, and hardcoding can cause breakages.
348 fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
349 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
352 fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
353 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
356 fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
357 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
360 fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
361 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
364 fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
365 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
368 fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
369 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
372 fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &msgs::TxComplete) {
373 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
376 fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
377 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
380 fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
381 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
384 fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
385 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
388 fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &msgs::TxAbort) {
389 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
393 impl Deref for ErroringMessageHandler {
394 type Target = ErroringMessageHandler;
395 fn deref(&self) -> &Self { self }
398 /// Provides references to trait impls which handle different types of messages.
399 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref, CustomM: Deref> where
400 CM::Target: ChannelMessageHandler,
401 RM::Target: RoutingMessageHandler,
402 OM::Target: OnionMessageHandler,
403 CustomM::Target: CustomMessageHandler,
405 /// A message handler which handles messages specific to channels. Usually this is just a
406 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
408 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
409 pub chan_handler: CM,
410 /// A message handler which handles messages updating our knowledge of the network channel
411 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
413 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
414 pub route_handler: RM,
416 /// A message handler which handles onion messages. This should generally be an
417 /// [`OnionMessenger`], but can also be an [`IgnoringMessageHandler`].
419 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
420 pub onion_message_handler: OM,
422 /// A message handler which handles custom messages. The only LDK-provided implementation is
423 /// [`IgnoringMessageHandler`].
424 pub custom_message_handler: CustomM,
427 /// Provides an object which can be used to send data to and which uniquely identifies a connection
428 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
429 /// implement Hash to meet the PeerManager API.
431 /// For efficiency, [`Clone`] should be relatively cheap for this type.
433 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
434 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
435 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
436 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
437 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
438 /// to simply use another value which is guaranteed to be globally unique instead.
439 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
440 /// Attempts to send some data from the given slice to the peer.
442 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
443 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
444 /// called and further write attempts may occur until that time.
446 /// If the returned size is smaller than `data.len()`, a
447 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
448 /// written. Additionally, until a `send_data` event completes fully, no further
449 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
450 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
453 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
454 /// (indicating that read events should be paused to prevent DoS in the send buffer),
455 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
456 /// `resume_read` of false carries no meaning, and should not cause any action.
457 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
458 /// Disconnect the socket pointed to by this SocketDescriptor.
460 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
461 /// call (doing so is a noop).
462 fn disconnect_socket(&mut self);
465 /// Details of a connected peer as returned by [`PeerManager::list_peers`].
466 pub struct PeerDetails {
467 /// The node id of the peer.
469 /// For outbound connections, this [`PublicKey`] will be the same as the `their_node_id` parameter
470 /// passed in to [`PeerManager::new_outbound_connection`].
471 pub counterparty_node_id: PublicKey,
472 /// The socket address the peer provided in the initial handshake.
474 /// Will only be `Some` if an address had been previously provided to
475 /// [`PeerManager::new_outbound_connection`] or [`PeerManager::new_inbound_connection`].
476 pub socket_address: Option<SocketAddress>,
477 /// The features the peer provided in the initial handshake.
478 pub init_features: InitFeatures,
479 /// Indicates the direction of the peer connection.
481 /// Will be `true` for inbound connections, and `false` for outbound connections.
482 pub is_inbound_connection: bool,
485 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
486 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
489 pub struct PeerHandleError { }
490 impl fmt::Debug for PeerHandleError {
491 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
492 formatter.write_str("Peer Sent Invalid Data")
495 impl fmt::Display for PeerHandleError {
496 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
497 formatter.write_str("Peer Sent Invalid Data")
501 #[cfg(feature = "std")]
502 impl error::Error for PeerHandleError {
503 fn description(&self) -> &str {
504 "Peer Sent Invalid Data"
508 enum InitSyncTracker{
510 ChannelsSyncing(u64),
511 NodesSyncing(NodeId),
514 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
515 /// forwarding gossip messages to peers altogether.
516 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
518 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
519 /// we have fewer than this many messages in the outbound buffer again.
520 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
521 /// refilled as we send bytes.
522 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
523 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
525 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
527 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
528 /// the socket receive buffer before receiving the ping.
530 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
531 /// including any network delays, outbound traffic, or the same for messages from other peers.
533 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
534 /// per connected peer to respond to a ping, as long as they send us at least one message during
535 /// each tick, ensuring we aren't actually just disconnected.
536 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
539 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
540 /// two connected peers, assuming most LDK-running systems have at least two cores.
541 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
543 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
544 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
545 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
546 /// process before the next ping.
548 /// Note that we continue responding to other messages even after we've sent this many messages, so
549 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
550 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
551 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
554 channel_encryptor: PeerChannelEncryptor,
555 /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
556 /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
557 their_node_id: Option<(PublicKey, NodeId)>,
558 /// The features provided in the peer's [`msgs::Init`] message.
560 /// This is set only after we've processed the [`msgs::Init`] message and called relevant
561 /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
562 /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
564 their_features: Option<InitFeatures>,
565 their_socket_address: Option<SocketAddress>,
567 pending_outbound_buffer: VecDeque<Vec<u8>>,
568 pending_outbound_buffer_first_msg_offset: usize,
569 /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
570 /// prioritize channel messages over them.
572 /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
573 gossip_broadcast_buffer: VecDeque<MessageBuf>,
574 awaiting_write_event: bool,
576 pending_read_buffer: Vec<u8>,
577 pending_read_buffer_pos: usize,
578 pending_read_is_header: bool,
580 sync_status: InitSyncTracker,
582 msgs_sent_since_pong: usize,
583 awaiting_pong_timer_tick_intervals: i64,
584 received_message_since_timer_tick: bool,
585 sent_gossip_timestamp_filter: bool,
587 /// Indicates we've received a `channel_announcement` since the last time we had
588 /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
589 /// `channel_announcement` at all - we set this unconditionally but unset it every time we
590 /// check if we're gossip-processing-backlogged).
591 received_channel_announce_since_backlogged: bool,
593 inbound_connection: bool,
597 /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
598 /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
600 fn handshake_complete(&self) -> bool {
601 self.their_features.is_some()
604 /// Returns true if the channel announcements/updates for the given channel should be
605 /// forwarded to this peer.
606 /// If we are sending our routing table to this peer and we have not yet sent channel
607 /// announcements/updates for the given channel_id then we will send it when we get to that
608 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
609 /// sent the old versions, we should send the update, and so return true here.
610 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
611 if !self.handshake_complete() { return false; }
612 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
613 !self.sent_gossip_timestamp_filter {
616 match self.sync_status {
617 InitSyncTracker::NoSyncRequested => true,
618 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
619 InitSyncTracker::NodesSyncing(_) => true,
623 /// Similar to the above, but for node announcements indexed by node_id.
624 fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
625 if !self.handshake_complete() { return false; }
626 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
627 !self.sent_gossip_timestamp_filter {
630 match self.sync_status {
631 InitSyncTracker::NoSyncRequested => true,
632 InitSyncTracker::ChannelsSyncing(_) => false,
633 InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
637 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
638 /// buffer still has space and we don't need to pause reads to get some writes out.
639 fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
640 if !gossip_processing_backlogged {
641 self.received_channel_announce_since_backlogged = false;
643 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
644 (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
647 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
648 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
649 fn should_buffer_gossip_backfill(&self) -> bool {
650 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
651 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
652 && self.handshake_complete()
655 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
656 /// every time the peer's buffer may have been drained.
657 fn should_buffer_onion_message(&self) -> bool {
658 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
659 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
662 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
663 /// buffer. This is checked every time the peer's buffer may have been drained.
664 fn should_buffer_gossip_broadcast(&self) -> bool {
665 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
666 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
669 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
670 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
671 let total_outbound_buffered =
672 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
674 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
675 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
678 fn set_their_node_id(&mut self, node_id: PublicKey) {
679 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
683 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
684 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
685 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
686 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
687 /// issues such as overly long function definitions.
689 /// This is not exported to bindings users as type aliases aren't supported in most languages.
690 #[cfg(not(c_bindings))]
691 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<
693 Arc<SimpleArcChannelManager<M, T, F, L>>,
694 Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, C, Arc<L>>>,
695 Arc<SimpleArcOnionMessenger<M, T, F, L>>,
697 IgnoringMessageHandler,
701 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
702 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
703 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
704 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
705 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
706 /// helps with issues such as long function definitions.
708 /// This is not exported to bindings users as type aliases aren't supported in most languages.
709 #[cfg(not(c_bindings))]
710 pub type SimpleRefPeerManager<
711 'a, 'b, 'c, 'd, 'e, 'f, 'logger, 'h, 'i, 'j, 'graph, 'k, SD, M, T, F, C, L
714 &'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, M, T, F, L>,
715 &'f P2PGossipSync<&'graph NetworkGraph<&'logger L>, C, &'logger L>,
716 &'h SimpleRefOnionMessenger<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, 'j, 'k, M, T, F, L>,
718 IgnoringMessageHandler,
723 /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or
724 /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather
725 /// than the full set of bounds on [`PeerManager`] itself.
727 /// This is not exported to bindings users as general cover traits aren't useful in other
729 #[allow(missing_docs)]
730 pub trait APeerManager {
731 type Descriptor: SocketDescriptor;
732 type CMT: ChannelMessageHandler + ?Sized;
733 type CM: Deref<Target=Self::CMT>;
734 type RMT: RoutingMessageHandler + ?Sized;
735 type RM: Deref<Target=Self::RMT>;
736 type OMT: OnionMessageHandler + ?Sized;
737 type OM: Deref<Target=Self::OMT>;
738 type LT: Logger + ?Sized;
739 type L: Deref<Target=Self::LT>;
740 type CMHT: CustomMessageHandler + ?Sized;
741 type CMH: Deref<Target=Self::CMHT>;
742 type NST: NodeSigner + ?Sized;
743 type NS: Deref<Target=Self::NST>;
744 /// Gets a reference to the underlying [`PeerManager`].
745 fn as_ref(&self) -> &PeerManager<Self::Descriptor, Self::CM, Self::RM, Self::OM, Self::L, Self::CMH, Self::NS>;
748 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref>
749 APeerManager for PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
750 CM::Target: ChannelMessageHandler,
751 RM::Target: RoutingMessageHandler,
752 OM::Target: OnionMessageHandler,
754 CMH::Target: CustomMessageHandler,
755 NS::Target: NodeSigner,
757 type Descriptor = Descriptor;
758 type CMT = <CM as Deref>::Target;
760 type RMT = <RM as Deref>::Target;
762 type OMT = <OM as Deref>::Target;
764 type LT = <L as Deref>::Target;
766 type CMHT = <CMH as Deref>::Target;
768 type NST = <NS as Deref>::Target;
770 fn as_ref(&self) -> &PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> { self }
773 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
774 /// socket events into messages which it passes on to its [`MessageHandler`].
776 /// Locks are taken internally, so you must never assume that reentrancy from a
777 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
779 /// Calls to [`read_event`] will decode relevant messages and pass them to the
780 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
781 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
782 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
783 /// calls only after previous ones have returned.
785 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
786 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
787 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
788 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
789 /// you're using lightning-net-tokio.
791 /// [`read_event`]: PeerManager::read_event
792 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
793 CM::Target: ChannelMessageHandler,
794 RM::Target: RoutingMessageHandler,
795 OM::Target: OnionMessageHandler,
797 CMH::Target: CustomMessageHandler,
798 NS::Target: NodeSigner {
799 message_handler: MessageHandler<CM, RM, OM, CMH>,
800 /// Connection state for each connected peer - we have an outer read-write lock which is taken
801 /// as read while we're doing processing for a peer and taken write when a peer is being added
804 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
805 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
806 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
807 /// the `MessageHandler`s for a given peer is already guaranteed.
808 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
809 /// Only add to this set when noise completes.
810 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
811 /// lock held. Entries may be added with only the `peers` read lock held (though the
812 /// `Descriptor` value must already exist in `peers`).
813 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
814 /// We can only have one thread processing events at once, but if a second call to
815 /// `process_events` happens while a first call is in progress, one of the two calls needs to
816 /// start from the top to ensure any new messages are also handled.
818 /// Because the event handler calls into user code which may block, we don't want to block a
819 /// second thread waiting for another thread to handle events which is then blocked on user
820 /// code, so we store an atomic counter here:
821 /// * 0 indicates no event processor is running
822 /// * 1 indicates an event processor is running
823 /// * > 1 indicates an event processor is running but needs to start again from the top once
824 /// it finishes as another thread tried to start processing events but returned early.
825 event_processing_state: AtomicI32,
827 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
828 /// value increases strictly since we don't assume access to a time source.
829 last_node_announcement_serial: AtomicU32,
831 ephemeral_key_midstate: Sha256Engine,
833 peer_counter: AtomicCounter,
835 gossip_processing_backlogged: AtomicBool,
836 gossip_processing_backlog_lifted: AtomicBool,
841 secp_ctx: Secp256k1<secp256k1::SignOnly>
844 enum MessageHandlingError {
845 PeerHandleError(PeerHandleError),
846 LightningError(LightningError),
849 impl From<PeerHandleError> for MessageHandlingError {
850 fn from(error: PeerHandleError) -> Self {
851 MessageHandlingError::PeerHandleError(error)
855 impl From<LightningError> for MessageHandlingError {
856 fn from(error: LightningError) -> Self {
857 MessageHandlingError::LightningError(error)
861 macro_rules! encode_msg {
863 let mut buffer = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
864 wire::write($msg, &mut buffer).unwrap();
869 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
870 CM::Target: ChannelMessageHandler,
871 OM::Target: OnionMessageHandler,
873 NS::Target: NodeSigner {
874 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
875 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
878 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
879 /// cryptographically secure random bytes.
881 /// `current_time` is used as an always-increasing counter that survives across restarts and is
882 /// incremented irregularly internally. In general it is best to simply use the current UNIX
883 /// timestamp, however if it is not available a persistent counter that increases once per
884 /// minute should suffice.
886 /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
887 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 {
888 Self::new(MessageHandler {
889 chan_handler: channel_message_handler,
890 route_handler: IgnoringMessageHandler{},
891 onion_message_handler,
892 custom_message_handler: IgnoringMessageHandler{},
893 }, current_time, ephemeral_random_data, logger, node_signer)
897 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
898 RM::Target: RoutingMessageHandler,
900 NS::Target: NodeSigner {
901 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
902 /// handler or onion message handler is used and onion and channel messages will be ignored (or
903 /// generate error messages). Note that some other lightning implementations time-out connections
904 /// after some time if no channel is built with the peer.
906 /// `current_time` is used as an always-increasing counter that survives across restarts and is
907 /// incremented irregularly internally. In general it is best to simply use the current UNIX
908 /// timestamp, however if it is not available a persistent counter that increases once per
909 /// minute should suffice.
911 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
912 /// cryptographically secure random bytes.
914 /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
915 pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
916 Self::new(MessageHandler {
917 chan_handler: ErroringMessageHandler::new(),
918 route_handler: routing_message_handler,
919 onion_message_handler: IgnoringMessageHandler{},
920 custom_message_handler: IgnoringMessageHandler{},
921 }, current_time, ephemeral_random_data, logger, node_signer)
925 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
926 /// This works around `format!()` taking a reference to each argument, preventing
927 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
928 /// due to lifetime errors.
929 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
930 impl core::fmt::Display for OptionalFromDebugger<'_> {
931 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
932 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
936 /// A function used to filter out local or private addresses
937 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
938 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
939 fn filter_addresses(ip_address: Option<SocketAddress>) -> Option<SocketAddress> {
941 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
942 Some(SocketAddress::TcpIpV4{addr: [10, _, _, _], port: _}) => None,
943 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
944 Some(SocketAddress::TcpIpV4{addr: [0, _, _, _], port: _}) => None,
945 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
946 Some(SocketAddress::TcpIpV4{addr: [100, 64..=127, _, _], port: _}) => None,
947 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
948 Some(SocketAddress::TcpIpV4{addr: [127, _, _, _], port: _}) => None,
949 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
950 Some(SocketAddress::TcpIpV4{addr: [169, 254, _, _], port: _}) => None,
951 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
952 Some(SocketAddress::TcpIpV4{addr: [172, 16..=31, _, _], port: _}) => None,
953 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
954 Some(SocketAddress::TcpIpV4{addr: [192, 168, _, _], port: _}) => None,
955 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
956 Some(SocketAddress::TcpIpV4{addr: [192, 88, 99, _], port: _}) => None,
957 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
958 Some(SocketAddress::TcpIpV6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
959 // For remaining addresses
960 Some(SocketAddress::TcpIpV6{addr: _, port: _}) => None,
961 Some(..) => ip_address,
966 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
967 CM::Target: ChannelMessageHandler,
968 RM::Target: RoutingMessageHandler,
969 OM::Target: OnionMessageHandler,
971 CMH::Target: CustomMessageHandler,
972 NS::Target: NodeSigner
974 /// Constructs a new `PeerManager` with the given message handlers.
976 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
977 /// cryptographically secure random bytes.
979 /// `current_time` is used as an always-increasing counter that survives across restarts and is
980 /// incremented irregularly internally. In general it is best to simply use the current UNIX
981 /// timestamp, however if it is not available a persistent counter that increases once per
982 /// minute should suffice.
983 pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
984 let mut ephemeral_key_midstate = Sha256::engine();
985 ephemeral_key_midstate.input(ephemeral_random_data);
987 let mut secp_ctx = Secp256k1::signing_only();
988 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).to_byte_array();
989 secp_ctx.seeded_randomize(&ephemeral_hash);
993 peers: FairRwLock::new(new_hash_map()),
994 node_id_to_descriptor: Mutex::new(new_hash_map()),
995 event_processing_state: AtomicI32::new(0),
996 ephemeral_key_midstate,
997 peer_counter: AtomicCounter::new(),
998 gossip_processing_backlogged: AtomicBool::new(false),
999 gossip_processing_backlog_lifted: AtomicBool::new(false),
1000 last_node_announcement_serial: AtomicU32::new(current_time),
1007 /// Returns a list of [`PeerDetails`] for connected peers that have completed the initial
1009 pub fn list_peers(&self) -> Vec<PeerDetails> {
1010 let peers = self.peers.read().unwrap();
1011 peers.values().filter_map(|peer_mutex| {
1012 let p = peer_mutex.lock().unwrap();
1013 if !p.handshake_complete() {
1016 let details = PeerDetails {
1017 // unwrap safety: their_node_id is guaranteed to be `Some` after the handshake
1019 counterparty_node_id: p.their_node_id.unwrap().0,
1020 socket_address: p.their_socket_address.clone(),
1021 // unwrap safety: their_features is guaranteed to be `Some` after the handshake
1023 init_features: p.their_features.clone().unwrap(),
1024 is_inbound_connection: p.inbound_connection,
1030 /// Returns the [`PeerDetails`] of a connected peer that has completed the initial handshake.
1032 /// Will return `None` if the peer is unknown or it hasn't completed the initial handshake.
1033 pub fn peer_by_node_id(&self, their_node_id: &PublicKey) -> Option<PeerDetails> {
1034 let peers = self.peers.read().unwrap();
1035 peers.values().find_map(|peer_mutex| {
1036 let p = peer_mutex.lock().unwrap();
1037 if !p.handshake_complete() {
1041 // unwrap safety: their_node_id is guaranteed to be `Some` after the handshake
1043 let counterparty_node_id = p.their_node_id.unwrap().0;
1045 if counterparty_node_id != *their_node_id {
1049 let details = PeerDetails {
1050 counterparty_node_id,
1051 socket_address: p.their_socket_address.clone(),
1052 // unwrap safety: their_features is guaranteed to be `Some` after the handshake
1054 init_features: p.their_features.clone().unwrap(),
1055 is_inbound_connection: p.inbound_connection,
1061 fn get_ephemeral_key(&self) -> SecretKey {
1062 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
1063 let counter = self.peer_counter.get_increment();
1064 ephemeral_hash.input(&counter.to_le_bytes());
1065 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).to_byte_array()).expect("You broke SHA-256!")
1068 fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
1069 self.message_handler.chan_handler.provided_init_features(their_node_id)
1070 | self.message_handler.route_handler.provided_init_features(their_node_id)
1071 | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
1072 | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
1075 /// Indicates a new outbound connection has been established to a node with the given `node_id`
1076 /// and an optional remote network address.
1078 /// The remote network address adds the option to report a remote IP address back to a connecting
1079 /// peer using the init message.
1080 /// The user should pass the remote network address of the host they are connected to.
1082 /// If an `Err` is returned here you must disconnect the connection immediately.
1084 /// Returns a small number of bytes to send to the remote node (currently always 50).
1086 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1087 /// [`socket_disconnected`].
1089 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1090 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<Vec<u8>, PeerHandleError> {
1091 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
1092 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
1093 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
1095 let mut peers = self.peers.write().unwrap();
1096 match peers.entry(descriptor) {
1097 hash_map::Entry::Occupied(_) => {
1098 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1099 Err(PeerHandleError {})
1101 hash_map::Entry::Vacant(e) => {
1102 e.insert(Mutex::new(Peer {
1103 channel_encryptor: peer_encryptor,
1104 their_node_id: None,
1105 their_features: None,
1106 their_socket_address: remote_network_address,
1108 pending_outbound_buffer: VecDeque::new(),
1109 pending_outbound_buffer_first_msg_offset: 0,
1110 gossip_broadcast_buffer: VecDeque::new(),
1111 awaiting_write_event: false,
1113 pending_read_buffer,
1114 pending_read_buffer_pos: 0,
1115 pending_read_is_header: false,
1117 sync_status: InitSyncTracker::NoSyncRequested,
1119 msgs_sent_since_pong: 0,
1120 awaiting_pong_timer_tick_intervals: 0,
1121 received_message_since_timer_tick: false,
1122 sent_gossip_timestamp_filter: false,
1124 received_channel_announce_since_backlogged: false,
1125 inbound_connection: false,
1132 /// Indicates a new inbound connection has been established to a node with an optional remote
1133 /// network address.
1135 /// The remote network address adds the option to report a remote IP address back to a connecting
1136 /// peer using the init message.
1137 /// The user should pass the remote network address of the host they are connected to.
1139 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
1140 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
1141 /// the connection immediately.
1143 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1144 /// [`socket_disconnected`].
1146 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1147 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<(), PeerHandleError> {
1148 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1149 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1151 let mut peers = self.peers.write().unwrap();
1152 match peers.entry(descriptor) {
1153 hash_map::Entry::Occupied(_) => {
1154 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1155 Err(PeerHandleError {})
1157 hash_map::Entry::Vacant(e) => {
1158 e.insert(Mutex::new(Peer {
1159 channel_encryptor: peer_encryptor,
1160 their_node_id: None,
1161 their_features: None,
1162 their_socket_address: remote_network_address,
1164 pending_outbound_buffer: VecDeque::new(),
1165 pending_outbound_buffer_first_msg_offset: 0,
1166 gossip_broadcast_buffer: VecDeque::new(),
1167 awaiting_write_event: false,
1169 pending_read_buffer,
1170 pending_read_buffer_pos: 0,
1171 pending_read_is_header: false,
1173 sync_status: InitSyncTracker::NoSyncRequested,
1175 msgs_sent_since_pong: 0,
1176 awaiting_pong_timer_tick_intervals: 0,
1177 received_message_since_timer_tick: false,
1178 sent_gossip_timestamp_filter: false,
1180 received_channel_announce_since_backlogged: false,
1181 inbound_connection: true,
1188 fn peer_should_read(&self, peer: &mut Peer) -> bool {
1189 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1192 fn update_gossip_backlogged(&self) {
1193 let new_state = self.message_handler.route_handler.processing_queue_high();
1194 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1195 if prev_state && !new_state {
1196 self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1200 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1201 let mut have_written = false;
1202 while !peer.awaiting_write_event {
1203 if peer.should_buffer_onion_message() {
1204 if let Some((peer_node_id, _)) = peer.their_node_id {
1205 if let Some(next_onion_message) =
1206 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1207 self.enqueue_message(peer, &next_onion_message);
1211 if peer.should_buffer_gossip_broadcast() {
1212 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1213 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(msg));
1216 if peer.should_buffer_gossip_backfill() {
1217 match peer.sync_status {
1218 InitSyncTracker::NoSyncRequested => {},
1219 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1220 if let Some((announce, update_a_option, update_b_option)) =
1221 self.message_handler.route_handler.get_next_channel_announcement(c)
1223 self.enqueue_message(peer, &announce);
1224 if let Some(update_a) = update_a_option {
1225 self.enqueue_message(peer, &update_a);
1227 if let Some(update_b) = update_b_option {
1228 self.enqueue_message(peer, &update_b);
1230 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1232 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1235 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1236 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1237 self.enqueue_message(peer, &msg);
1238 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1240 peer.sync_status = InitSyncTracker::NoSyncRequested;
1243 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1244 InitSyncTracker::NodesSyncing(sync_node_id) => {
1245 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1246 self.enqueue_message(peer, &msg);
1247 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1249 peer.sync_status = InitSyncTracker::NoSyncRequested;
1254 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1255 self.maybe_send_extra_ping(peer);
1258 let should_read = self.peer_should_read(peer);
1259 let next_buff = match peer.pending_outbound_buffer.front() {
1261 if force_one_write && !have_written {
1263 let data_sent = descriptor.send_data(&[], should_read);
1264 debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1272 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1273 let data_sent = descriptor.send_data(pending, should_read);
1274 have_written = true;
1275 peer.pending_outbound_buffer_first_msg_offset += data_sent;
1276 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1277 peer.pending_outbound_buffer_first_msg_offset = 0;
1278 peer.pending_outbound_buffer.pop_front();
1279 const VEC_SIZE: usize = ::core::mem::size_of::<Vec<u8>>();
1280 let large_capacity = peer.pending_outbound_buffer.capacity() > 4096 / VEC_SIZE;
1281 let lots_of_slack = peer.pending_outbound_buffer.len()
1282 < peer.pending_outbound_buffer.capacity() / 2;
1283 if large_capacity && lots_of_slack {
1284 peer.pending_outbound_buffer.shrink_to_fit();
1287 peer.awaiting_write_event = true;
1292 /// Indicates that there is room to write data to the given socket descriptor.
1294 /// May return an Err to indicate that the connection should be closed.
1296 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1297 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1298 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1299 /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1302 /// [`send_data`]: SocketDescriptor::send_data
1303 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1304 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1305 let peers = self.peers.read().unwrap();
1306 match peers.get(descriptor) {
1308 // This is most likely a simple race condition where the user found that the socket
1309 // was writeable, then we told the user to `disconnect_socket()`, then they called
1310 // this method. Return an error to make sure we get disconnected.
1311 return Err(PeerHandleError { });
1313 Some(peer_mutex) => {
1314 let mut peer = peer_mutex.lock().unwrap();
1315 peer.awaiting_write_event = false;
1316 self.do_attempt_write_data(descriptor, &mut peer, false);
1322 /// Indicates that data was read from the given socket descriptor.
1324 /// May return an Err to indicate that the connection should be closed.
1326 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1327 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1328 /// [`send_data`] calls to handle responses.
1330 /// If `Ok(true)` is returned, further read_events should not be triggered until a
1331 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1334 /// In order to avoid processing too many messages at once per peer, `data` should be on the
1337 /// [`send_data`]: SocketDescriptor::send_data
1338 /// [`process_events`]: PeerManager::process_events
1339 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1340 match self.do_read_event(peer_descriptor, data) {
1343 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1344 self.disconnect_event_internal(peer_descriptor);
1350 /// Append a message to a peer's pending outbound/write buffer
1351 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1352 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1353 if is_gossip_msg(message.type_id()) {
1354 log_gossip!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1356 log_trace!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1358 peer.msgs_sent_since_pong += 1;
1359 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1362 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1363 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: MessageBuf) {
1364 peer.msgs_sent_since_pong += 1;
1365 debug_assert!(peer.gossip_broadcast_buffer.len() <= OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP);
1366 peer.gossip_broadcast_buffer.push_back(encoded_message);
1369 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1370 let mut pause_read = false;
1371 let peers = self.peers.read().unwrap();
1372 let mut msgs_to_forward = Vec::new();
1373 let mut peer_node_id = None;
1374 match peers.get(peer_descriptor) {
1376 // This is most likely a simple race condition where the user read some bytes
1377 // from the socket, then we told the user to `disconnect_socket()`, then they
1378 // called this method. Return an error to make sure we get disconnected.
1379 return Err(PeerHandleError { });
1381 Some(peer_mutex) => {
1382 let mut read_pos = 0;
1383 while read_pos < data.len() {
1384 macro_rules! try_potential_handleerror {
1385 ($peer: expr, $thing: expr) => {{
1387 let logger = WithContext::from(&self.logger, peer_node_id.map(|(id, _)| id), None, None);
1392 msgs::ErrorAction::DisconnectPeer { .. } => {
1393 // We may have an `ErrorMessage` to send to the peer,
1394 // but writing to the socket while reading can lead to
1395 // re-entrant code and possibly unexpected behavior. The
1396 // message send is optimistic anyway, and in this case
1397 // we immediately disconnect the peer.
1398 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1399 return Err(PeerHandleError { });
1401 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1402 // We have a `WarningMessage` to send to the peer, but
1403 // writing to the socket while reading can lead to
1404 // re-entrant code and possibly unexpected behavior. The
1405 // message send is optimistic anyway, and in this case
1406 // we immediately disconnect the peer.
1407 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1408 return Err(PeerHandleError { });
1410 msgs::ErrorAction::IgnoreAndLog(level) => {
1411 log_given_level!(logger, level, "Error handling {}message{}; ignoring: {}",
1412 if level == Level::Gossip { "gossip " } else { "" },
1413 OptionalFromDebugger(&peer_node_id), e.err);
1416 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1417 msgs::ErrorAction::IgnoreError => {
1418 log_debug!(logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1421 msgs::ErrorAction::SendErrorMessage { msg } => {
1422 log_debug!(logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1423 self.enqueue_message($peer, &msg);
1426 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1427 log_given_level!(logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1428 self.enqueue_message($peer, &msg);
1437 let mut peer_lock = peer_mutex.lock().unwrap();
1438 let peer = &mut *peer_lock;
1439 let mut msg_to_handle = None;
1440 if peer_node_id.is_none() {
1441 peer_node_id = peer.their_node_id.clone();
1444 assert!(peer.pending_read_buffer.len() > 0);
1445 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1448 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1449 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]);
1450 read_pos += data_to_copy;
1451 peer.pending_read_buffer_pos += data_to_copy;
1454 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1455 peer.pending_read_buffer_pos = 0;
1457 macro_rules! insert_node_id {
1459 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1460 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1461 hash_map::Entry::Occupied(e) => {
1462 log_trace!(logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1463 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1464 // Check that the peers map is consistent with the
1465 // node_id_to_descriptor map, as this has been broken
1467 debug_assert!(peers.get(e.get()).is_some());
1468 return Err(PeerHandleError { })
1470 hash_map::Entry::Vacant(entry) => {
1471 log_debug!(logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1472 entry.insert(peer_descriptor.clone())
1478 let next_step = peer.channel_encryptor.get_noise_step();
1480 NextNoiseStep::ActOne => {
1481 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1482 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1483 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1484 peer.pending_outbound_buffer.push_back(act_two);
1485 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1487 NextNoiseStep::ActTwo => {
1488 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1489 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1490 &self.node_signer));
1491 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1492 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1493 peer.pending_read_is_header = true;
1495 peer.set_their_node_id(their_node_id);
1497 let features = self.init_features(&their_node_id);
1498 let networks = self.message_handler.chan_handler.get_chain_hashes();
1499 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1500 self.enqueue_message(peer, &resp);
1502 NextNoiseStep::ActThree => {
1503 let their_node_id = try_potential_handleerror!(peer,
1504 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1505 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1506 peer.pending_read_is_header = true;
1507 peer.set_their_node_id(their_node_id);
1509 let features = self.init_features(&their_node_id);
1510 let networks = self.message_handler.chan_handler.get_chain_hashes();
1511 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1512 self.enqueue_message(peer, &resp);
1514 NextNoiseStep::NoiseComplete => {
1515 if peer.pending_read_is_header {
1516 let msg_len = try_potential_handleerror!(peer,
1517 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1518 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1519 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1520 if msg_len < 2 { // Need at least the message type tag
1521 return Err(PeerHandleError { });
1523 peer.pending_read_is_header = false;
1525 debug_assert!(peer.pending_read_buffer.len() >= 2 + 16);
1526 try_potential_handleerror!(peer,
1527 peer.channel_encryptor.decrypt_message(&mut peer.pending_read_buffer[..]));
1529 let mut reader = io::Cursor::new(&peer.pending_read_buffer[..peer.pending_read_buffer.len() - 16]);
1530 let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1532 // Reset read buffer
1533 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1534 peer.pending_read_buffer.resize(18, 0);
1535 peer.pending_read_is_header = true;
1537 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1538 let message = match message_result {
1542 // Note that to avoid re-entrancy we never call
1543 // `do_attempt_write_data` from here, causing
1544 // the messages enqueued here to not actually
1545 // be sent before the peer is disconnected.
1546 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1547 log_gossip!(logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1550 (msgs::DecodeError::UnsupportedCompression, _) => {
1551 log_gossip!(logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1552 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: ChannelId::new_zero(), data: "Unsupported message compression: zlib".to_owned() });
1555 (_, Some(ty)) if is_gossip_msg(ty) => {
1556 log_gossip!(logger, "Got an invalid value while deserializing a gossip message");
1557 self.enqueue_message(peer, &msgs::WarningMessage {
1558 channel_id: ChannelId::new_zero(),
1559 data: format!("Unreadable/bogus gossip message of type {}", ty),
1563 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1564 log_debug!(logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1565 return Err(PeerHandleError { });
1567 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1568 (msgs::DecodeError::InvalidValue, _) => {
1569 log_debug!(logger, "Got an invalid value while deserializing message");
1570 return Err(PeerHandleError { });
1572 (msgs::DecodeError::ShortRead, _) => {
1573 log_debug!(logger, "Deserialization failed due to shortness of message");
1574 return Err(PeerHandleError { });
1576 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1577 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1578 (msgs::DecodeError::DangerousValue, _) => return Err(PeerHandleError { }),
1583 msg_to_handle = Some(message);
1588 pause_read = !self.peer_should_read(peer);
1590 if let Some(message) = msg_to_handle {
1591 match self.handle_message(&peer_mutex, peer_lock, message) {
1592 Err(handling_error) => match handling_error {
1593 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1594 MessageHandlingError::LightningError(e) => {
1595 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1599 msgs_to_forward.push(msg);
1608 for msg in msgs_to_forward.drain(..) {
1609 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1615 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1617 /// Returns the message back if it needs to be broadcasted to all other peers.
1620 peer_mutex: &Mutex<Peer>,
1621 peer_lock: MutexGuard<Peer>,
1622 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1623 ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1624 let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages").0;
1625 let logger = WithContext::from(&self.logger, Some(their_node_id), None, None);
1627 let message = match self.do_handle_message_holding_peer_lock(peer_lock, message, &their_node_id, &logger)? {
1628 Some(processed_message) => processed_message,
1629 None => return Ok(None),
1632 self.do_handle_message_without_peer_lock(peer_mutex, message, &their_node_id, &logger)
1635 // Conducts all message processing that requires us to hold the `peer_lock`.
1637 // Returns `None` if the message was fully processed and otherwise returns the message back to
1638 // allow it to be subsequently processed by `do_handle_message_without_peer_lock`.
1639 fn do_handle_message_holding_peer_lock<'a>(
1641 mut peer_lock: MutexGuard<Peer>,
1642 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>,
1643 their_node_id: &PublicKey,
1644 logger: &WithContext<'a, L>
1645 ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError>
1647 peer_lock.received_message_since_timer_tick = true;
1649 // Need an Init as first message
1650 if let wire::Message::Init(msg) = message {
1651 // Check if we have any compatible chains if the `networks` field is specified.
1652 if let Some(networks) = &msg.networks {
1653 if let Some(our_chains) = self.message_handler.chan_handler.get_chain_hashes() {
1654 let mut have_compatible_chains = false;
1655 'our_chains: for our_chain in our_chains.iter() {
1656 for their_chain in networks {
1657 if our_chain == their_chain {
1658 have_compatible_chains = true;
1663 if !have_compatible_chains {
1664 log_debug!(logger, "Peer does not support any of our supported chains");
1665 return Err(PeerHandleError { }.into());
1670 let our_features = self.init_features(&their_node_id);
1671 if msg.features.requires_unknown_bits_from(&our_features) {
1672 log_debug!(logger, "Peer {} requires features unknown to us: {:?}",
1673 log_pubkey!(their_node_id), msg.features.required_unknown_bits_from(&our_features));
1674 return Err(PeerHandleError { }.into());
1677 if our_features.requires_unknown_bits_from(&msg.features) {
1678 log_debug!(logger, "We require features unknown to our peer {}: {:?}",
1679 log_pubkey!(their_node_id), our_features.required_unknown_bits_from(&msg.features));
1680 return Err(PeerHandleError { }.into());
1683 if peer_lock.their_features.is_some() {
1684 return Err(PeerHandleError { }.into());
1687 log_info!(logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1689 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1690 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1691 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1694 if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1695 log_debug!(logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1696 return Err(PeerHandleError { }.into());
1698 if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1699 log_debug!(logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1700 return Err(PeerHandleError { }.into());
1702 if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1703 log_debug!(logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1704 return Err(PeerHandleError { }.into());
1706 if let Err(()) = self.message_handler.custom_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1707 log_debug!(logger, "Custom Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1708 return Err(PeerHandleError { }.into());
1711 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1712 peer_lock.their_features = Some(msg.features);
1714 } else if peer_lock.their_features.is_none() {
1715 log_debug!(logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1716 return Err(PeerHandleError { }.into());
1719 if let wire::Message::GossipTimestampFilter(_msg) = message {
1720 // When supporting gossip messages, start initial gossip sync only after we receive
1721 // a GossipTimestampFilter
1722 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1723 !peer_lock.sent_gossip_timestamp_filter {
1724 peer_lock.sent_gossip_timestamp_filter = true;
1725 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1730 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1731 peer_lock.received_channel_announce_since_backlogged = true;
1737 // Conducts all message processing that doesn't require us to hold the `peer_lock`.
1739 // Returns the message back if it needs to be broadcasted to all other peers.
1740 fn do_handle_message_without_peer_lock<'a>(
1742 peer_mutex: &Mutex<Peer>,
1743 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>,
1744 their_node_id: &PublicKey,
1745 logger: &WithContext<'a, L>
1746 ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError>
1748 if is_gossip_msg(message.type_id()) {
1749 log_gossip!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1751 log_trace!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1754 let mut should_forward = None;
1757 // Setup and Control messages:
1758 wire::Message::Init(_) => {
1761 wire::Message::GossipTimestampFilter(_) => {
1764 wire::Message::Error(msg) => {
1765 log_debug!(logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1766 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1767 if msg.channel_id.is_zero() {
1768 return Err(PeerHandleError { }.into());
1771 wire::Message::Warning(msg) => {
1772 log_debug!(logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1775 wire::Message::Ping(msg) => {
1776 if msg.ponglen < 65532 {
1777 let resp = msgs::Pong { byteslen: msg.ponglen };
1778 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1781 wire::Message::Pong(_msg) => {
1782 let mut peer_lock = peer_mutex.lock().unwrap();
1783 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1784 peer_lock.msgs_sent_since_pong = 0;
1787 // Channel messages:
1788 wire::Message::OpenChannel(msg) => {
1789 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1791 wire::Message::OpenChannelV2(msg) => {
1792 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1794 wire::Message::AcceptChannel(msg) => {
1795 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1797 wire::Message::AcceptChannelV2(msg) => {
1798 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1801 wire::Message::FundingCreated(msg) => {
1802 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1804 wire::Message::FundingSigned(msg) => {
1805 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1807 wire::Message::ChannelReady(msg) => {
1808 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1811 // Quiescence messages:
1812 wire::Message::Stfu(msg) => {
1813 self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
1817 // Splicing messages:
1818 wire::Message::Splice(msg) => {
1819 self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
1822 wire::Message::SpliceAck(msg) => {
1823 self.message_handler.chan_handler.handle_splice_ack(&their_node_id, &msg);
1826 wire::Message::SpliceLocked(msg) => {
1827 self.message_handler.chan_handler.handle_splice_locked(&their_node_id, &msg);
1830 // Interactive transaction construction messages:
1831 wire::Message::TxAddInput(msg) => {
1832 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1834 wire::Message::TxAddOutput(msg) => {
1835 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1837 wire::Message::TxRemoveInput(msg) => {
1838 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1840 wire::Message::TxRemoveOutput(msg) => {
1841 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1843 wire::Message::TxComplete(msg) => {
1844 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1846 wire::Message::TxSignatures(msg) => {
1847 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1849 wire::Message::TxInitRbf(msg) => {
1850 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1852 wire::Message::TxAckRbf(msg) => {
1853 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1855 wire::Message::TxAbort(msg) => {
1856 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1859 wire::Message::Shutdown(msg) => {
1860 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1862 wire::Message::ClosingSigned(msg) => {
1863 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1866 // Commitment messages:
1867 wire::Message::UpdateAddHTLC(msg) => {
1868 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1870 wire::Message::UpdateFulfillHTLC(msg) => {
1871 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1873 wire::Message::UpdateFailHTLC(msg) => {
1874 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1876 wire::Message::UpdateFailMalformedHTLC(msg) => {
1877 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1880 wire::Message::CommitmentSigned(msg) => {
1881 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1883 wire::Message::RevokeAndACK(msg) => {
1884 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1886 wire::Message::UpdateFee(msg) => {
1887 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1889 wire::Message::ChannelReestablish(msg) => {
1890 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1893 // Routing messages:
1894 wire::Message::AnnouncementSignatures(msg) => {
1895 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1897 wire::Message::ChannelAnnouncement(msg) => {
1898 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1899 .map_err(|e| -> MessageHandlingError { e.into() })? {
1900 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1902 self.update_gossip_backlogged();
1904 wire::Message::NodeAnnouncement(msg) => {
1905 if self.message_handler.route_handler.handle_node_announcement(&msg)
1906 .map_err(|e| -> MessageHandlingError { e.into() })? {
1907 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1909 self.update_gossip_backlogged();
1911 wire::Message::ChannelUpdate(msg) => {
1912 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1913 if self.message_handler.route_handler.handle_channel_update(&msg)
1914 .map_err(|e| -> MessageHandlingError { e.into() })? {
1915 should_forward = Some(wire::Message::ChannelUpdate(msg));
1917 self.update_gossip_backlogged();
1919 wire::Message::QueryShortChannelIds(msg) => {
1920 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1922 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1923 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1925 wire::Message::QueryChannelRange(msg) => {
1926 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1928 wire::Message::ReplyChannelRange(msg) => {
1929 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1933 wire::Message::OnionMessage(msg) => {
1934 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1937 // Unknown messages:
1938 wire::Message::Unknown(type_id) if message.is_even() => {
1939 log_debug!(logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1940 return Err(PeerHandleError { }.into());
1942 wire::Message::Unknown(type_id) => {
1943 log_trace!(logger, "Received unknown odd message of type {}, ignoring", type_id);
1945 wire::Message::Custom(custom) => {
1946 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1952 fn forward_broadcast_msg(&self, peers: &HashMap<Descriptor, Mutex<Peer>>, msg: &wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>, except_node: Option<&PublicKey>) {
1954 wire::Message::ChannelAnnouncement(ref msg) => {
1955 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1956 let encoded_msg = encode_msg!(msg);
1958 for (_, peer_mutex) in peers.iter() {
1959 let mut peer = peer_mutex.lock().unwrap();
1960 if !peer.handshake_complete() ||
1961 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1964 debug_assert!(peer.their_node_id.is_some());
1965 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1966 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1967 if peer.buffer_full_drop_gossip_broadcast() {
1968 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1971 if let Some((_, their_node_id)) = peer.their_node_id {
1972 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1976 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1979 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1982 wire::Message::NodeAnnouncement(ref msg) => {
1983 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1984 let encoded_msg = encode_msg!(msg);
1986 for (_, peer_mutex) in peers.iter() {
1987 let mut peer = peer_mutex.lock().unwrap();
1988 if !peer.handshake_complete() ||
1989 !peer.should_forward_node_announcement(msg.contents.node_id) {
1992 debug_assert!(peer.their_node_id.is_some());
1993 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1994 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1995 if peer.buffer_full_drop_gossip_broadcast() {
1996 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1999 if let Some((_, their_node_id)) = peer.their_node_id {
2000 if their_node_id == msg.contents.node_id {
2004 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
2007 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
2010 wire::Message::ChannelUpdate(ref msg) => {
2011 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
2012 let encoded_msg = encode_msg!(msg);
2014 for (_, peer_mutex) in peers.iter() {
2015 let mut peer = peer_mutex.lock().unwrap();
2016 if !peer.handshake_complete() ||
2017 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
2020 debug_assert!(peer.their_node_id.is_some());
2021 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2022 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
2023 if peer.buffer_full_drop_gossip_broadcast() {
2024 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
2027 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
2030 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
2033 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
2037 /// Checks for any events generated by our handlers and processes them. Includes sending most
2038 /// response messages as well as messages generated by calls to handler functions directly (eg
2039 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
2041 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2044 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
2045 /// or one of the other clients provided in our language bindings.
2047 /// Note that if there are any other calls to this function waiting on lock(s) this may return
2048 /// without doing any work. All available events that need handling will be handled before the
2049 /// other calls return.
2051 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2052 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
2053 /// [`send_data`]: SocketDescriptor::send_data
2054 pub fn process_events(&self) {
2055 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
2056 // If we're not the first event processor to get here, just return early, the increment
2057 // we just did will be treated as "go around again" at the end.
2062 self.update_gossip_backlogged();
2063 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2065 let mut peers_to_disconnect = new_hash_map();
2068 let peers_lock = self.peers.read().unwrap();
2070 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
2071 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
2073 let peers = &*peers_lock;
2074 macro_rules! get_peer_for_forwarding {
2075 ($node_id: expr) => {
2077 if peers_to_disconnect.get($node_id).is_some() {
2078 // If we've "disconnected" this peer, do not send to it.
2081 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
2082 match descriptor_opt {
2083 Some(descriptor) => match peers.get(&descriptor) {
2084 Some(peer_mutex) => {
2085 let peer_lock = peer_mutex.lock().unwrap();
2086 if !peer_lock.handshake_complete() {
2092 debug_assert!(false, "Inconsistent peers set state!");
2103 for event in events_generated.drain(..) {
2105 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
2106 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 {}",
2107 log_pubkey!(node_id),
2108 &msg.common_fields.temporary_channel_id);
2109 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2111 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
2112 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 {}",
2113 log_pubkey!(node_id),
2114 &msg.common_fields.temporary_channel_id);
2115 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2117 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
2118 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 {}",
2119 log_pubkey!(node_id),
2120 &msg.common_fields.temporary_channel_id);
2121 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2123 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
2124 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 {}",
2125 log_pubkey!(node_id),
2126 &msg.common_fields.temporary_channel_id);
2127 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2129 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
2130 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 {})",
2131 log_pubkey!(node_id),
2132 &msg.temporary_channel_id,
2133 ChannelId::v1_from_funding_txid(msg.funding_txid.as_byte_array(), msg.funding_output_index));
2134 // TODO: If the peer is gone we should generate a DiscardFunding event
2135 // indicating to the wallet that they should just throw away this funding transaction
2136 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2138 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
2139 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
2140 log_pubkey!(node_id),
2142 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2144 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
2145 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendChannelReady event in peer_handler for node {} for channel {}",
2146 log_pubkey!(node_id),
2148 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2150 MessageSendEvent::SendStfu { ref node_id, ref msg} => {
2151 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None);
2152 log_debug!(logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
2153 log_pubkey!(node_id),
2155 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2157 MessageSendEvent::SendSplice { ref node_id, ref msg} => {
2158 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None);
2159 log_debug!(logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
2160 log_pubkey!(node_id),
2162 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2164 MessageSendEvent::SendSpliceAck { ref node_id, ref msg} => {
2165 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None);
2166 log_debug!(logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}",
2167 log_pubkey!(node_id),
2169 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2171 MessageSendEvent::SendSpliceLocked { ref node_id, ref msg} => {
2172 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None);
2173 log_debug!(logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}",
2174 log_pubkey!(node_id),
2176 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2178 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
2179 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
2180 log_pubkey!(node_id),
2182 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2184 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
2185 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAddOutput event in peer_handler for node {} for channel {}",
2186 log_pubkey!(node_id),
2188 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2190 MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => {
2191 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
2192 log_pubkey!(node_id),
2194 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2196 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
2197 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
2198 log_pubkey!(node_id),
2200 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2202 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
2203 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxComplete event in peer_handler for node {} for channel {}",
2204 log_pubkey!(node_id),
2206 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2208 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
2209 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
2210 log_pubkey!(node_id),
2212 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2214 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
2215 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
2216 log_pubkey!(node_id),
2218 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2220 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2221 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2222 log_pubkey!(node_id),
2224 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2226 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2227 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2228 log_pubkey!(node_id),
2230 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2232 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2233 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2234 log_pubkey!(node_id),
2236 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2238 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 } } => {
2239 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 {}",
2240 log_pubkey!(node_id),
2241 update_add_htlcs.len(),
2242 update_fulfill_htlcs.len(),
2243 update_fail_htlcs.len(),
2244 &commitment_signed.channel_id);
2245 let mut peer = get_peer_for_forwarding!(node_id);
2246 for msg in update_add_htlcs {
2247 self.enqueue_message(&mut *peer, msg);
2249 for msg in update_fulfill_htlcs {
2250 self.enqueue_message(&mut *peer, msg);
2252 for msg in update_fail_htlcs {
2253 self.enqueue_message(&mut *peer, msg);
2255 for msg in update_fail_malformed_htlcs {
2256 self.enqueue_message(&mut *peer, msg);
2258 if let &Some(ref msg) = update_fee {
2259 self.enqueue_message(&mut *peer, msg);
2261 self.enqueue_message(&mut *peer, commitment_signed);
2263 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2264 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2265 log_pubkey!(node_id),
2267 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2269 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2270 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2271 log_pubkey!(node_id),
2273 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2275 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2276 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling Shutdown event in peer_handler for node {} for channel {}",
2277 log_pubkey!(node_id),
2279 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2281 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2282 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2283 log_pubkey!(node_id),
2285 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2287 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2288 log_debug!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2289 log_pubkey!(node_id),
2290 msg.contents.short_channel_id);
2291 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2292 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2294 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2295 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2296 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2297 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2298 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2301 if let Some(msg) = update_msg {
2302 match self.message_handler.route_handler.handle_channel_update(&msg) {
2303 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2304 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2309 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2310 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents);
2311 match self.message_handler.route_handler.handle_channel_update(&msg) {
2312 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2313 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2317 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2318 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2319 match self.message_handler.route_handler.handle_node_announcement(&msg) {
2320 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2321 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2325 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2326 log_trace!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2327 log_pubkey!(node_id), msg.contents.short_channel_id);
2328 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2330 MessageSendEvent::HandleError { node_id, action } => {
2331 let logger = WithContext::from(&self.logger, Some(node_id), None, None);
2333 msgs::ErrorAction::DisconnectPeer { msg } => {
2334 if let Some(msg) = msg.as_ref() {
2335 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2336 log_pubkey!(node_id), msg.data);
2338 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2339 log_pubkey!(node_id));
2341 // We do not have the peers write lock, so we just store that we're
2342 // about to disconnect the peer and do it after we finish
2343 // processing most messages.
2344 let msg = msg.map(|msg| wire::Message::<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2345 peers_to_disconnect.insert(node_id, msg);
2347 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2348 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2349 log_pubkey!(node_id), msg.data);
2350 // We do not have the peers write lock, so we just store that we're
2351 // about to disconnect the peer and do it after we finish
2352 // processing most messages.
2353 peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2355 msgs::ErrorAction::IgnoreAndLog(level) => {
2356 log_given_level!(logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2358 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2359 msgs::ErrorAction::IgnoreError => {
2360 log_debug!(logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2362 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2363 log_trace!(logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2364 log_pubkey!(node_id),
2366 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2368 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2369 log_given_level!(logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2370 log_pubkey!(node_id),
2372 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2376 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2377 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2379 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2380 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2382 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2383 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={}",
2384 log_pubkey!(node_id),
2385 msg.short_channel_ids.len(),
2387 msg.number_of_blocks,
2389 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2391 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2392 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2397 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2398 if peers_to_disconnect.get(&node_id).is_some() { continue; }
2399 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2402 for (descriptor, peer_mutex) in peers.iter() {
2403 let mut peer = peer_mutex.lock().unwrap();
2404 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2405 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2408 if !peers_to_disconnect.is_empty() {
2409 let mut peers_lock = self.peers.write().unwrap();
2410 let peers = &mut *peers_lock;
2411 for (node_id, msg) in peers_to_disconnect.drain() {
2412 // Note that since we are holding the peers *write* lock we can
2413 // remove from node_id_to_descriptor immediately (as no other
2414 // thread can be holding the peer lock if we have the global write
2417 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2418 if let Some(mut descriptor) = descriptor_opt {
2419 if let Some(peer_mutex) = peers.remove(&descriptor) {
2420 let mut peer = peer_mutex.lock().unwrap();
2421 if let Some(msg) = msg {
2422 self.enqueue_message(&mut *peer, &msg);
2423 // This isn't guaranteed to work, but if there is enough free
2424 // room in the send buffer, put the error message there...
2425 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2427 self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2428 } else { debug_assert!(false, "Missing connection for peer"); }
2433 if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2434 // If another thread incremented the state while we were running we should go
2435 // around again, but only once.
2436 self.event_processing_state.store(1, Ordering::Release);
2443 /// Indicates that the given socket descriptor's connection is now closed.
2444 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2445 self.disconnect_event_internal(descriptor);
2448 fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2449 if !peer.handshake_complete() {
2450 log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2451 descriptor.disconnect_socket();
2455 debug_assert!(peer.their_node_id.is_some());
2456 if let Some((node_id, _)) = peer.their_node_id {
2457 log_trace!(WithContext::from(&self.logger, Some(node_id), None, None), "Disconnecting peer with id {} due to {}", node_id, reason);
2458 self.message_handler.chan_handler.peer_disconnected(&node_id);
2459 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2460 self.message_handler.custom_message_handler.peer_disconnected(&node_id);
2462 descriptor.disconnect_socket();
2465 fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2466 let mut peers = self.peers.write().unwrap();
2467 let peer_option = peers.remove(descriptor);
2470 // This is most likely a simple race condition where the user found that the socket
2471 // was disconnected, then we told the user to `disconnect_socket()`, then they
2472 // called this method. Either way we're disconnected, return.
2474 Some(peer_lock) => {
2475 let peer = peer_lock.lock().unwrap();
2476 if let Some((node_id, _)) = peer.their_node_id {
2477 log_trace!(WithContext::from(&self.logger, Some(node_id), None, None), "Handling disconnection of peer {}", log_pubkey!(node_id));
2478 let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2479 debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2480 if !peer.handshake_complete() { return; }
2481 self.message_handler.chan_handler.peer_disconnected(&node_id);
2482 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2483 self.message_handler.custom_message_handler.peer_disconnected(&node_id);
2489 /// Disconnect a peer given its node id.
2491 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2492 /// peer. Thus, be very careful about reentrancy issues.
2494 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2495 pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2496 let mut peers_lock = self.peers.write().unwrap();
2497 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2498 let peer_opt = peers_lock.remove(&descriptor);
2499 if let Some(peer_mutex) = peer_opt {
2500 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2501 } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2505 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2506 /// an indication that TCP sockets have stalled even if we weren't around to time them out
2507 /// using regular ping/pongs.
2508 pub fn disconnect_all_peers(&self) {
2509 let mut peers_lock = self.peers.write().unwrap();
2510 self.node_id_to_descriptor.lock().unwrap().clear();
2511 let peers = &mut *peers_lock;
2512 for (descriptor, peer_mutex) in peers.drain() {
2513 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2517 /// This is called when we're blocked on sending additional gossip messages until we receive a
2518 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2519 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2520 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2521 if peer.awaiting_pong_timer_tick_intervals == 0 {
2522 peer.awaiting_pong_timer_tick_intervals = -1;
2523 let ping = msgs::Ping {
2527 self.enqueue_message(peer, &ping);
2531 /// Send pings to each peer and disconnect those which did not respond to the last round of
2534 /// This may be called on any timescale you want, however, roughly once every ten seconds is
2535 /// preferred. The call rate determines both how often we send a ping to our peers and how much
2536 /// time they have to respond before we disconnect them.
2538 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2541 /// [`send_data`]: SocketDescriptor::send_data
2542 pub fn timer_tick_occurred(&self) {
2543 let mut descriptors_needing_disconnect = Vec::new();
2545 let peers_lock = self.peers.read().unwrap();
2547 self.update_gossip_backlogged();
2548 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2550 for (descriptor, peer_mutex) in peers_lock.iter() {
2551 let mut peer = peer_mutex.lock().unwrap();
2552 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2554 if !peer.handshake_complete() {
2555 // The peer needs to complete its handshake before we can exchange messages. We
2556 // give peers one timer tick to complete handshake, reusing
2557 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2558 // for handshake completion.
2559 if peer.awaiting_pong_timer_tick_intervals != 0 {
2560 descriptors_needing_disconnect.push(descriptor.clone());
2562 peer.awaiting_pong_timer_tick_intervals = 1;
2566 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2567 debug_assert!(peer.their_node_id.is_some());
2569 loop { // Used as a `goto` to skip writing a Ping message.
2570 if peer.awaiting_pong_timer_tick_intervals == -1 {
2571 // Magic value set in `maybe_send_extra_ping`.
2572 peer.awaiting_pong_timer_tick_intervals = 1;
2573 peer.received_message_since_timer_tick = false;
2577 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2578 || peer.awaiting_pong_timer_tick_intervals as u64 >
2579 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2581 descriptors_needing_disconnect.push(descriptor.clone());
2584 peer.received_message_since_timer_tick = false;
2586 if peer.awaiting_pong_timer_tick_intervals > 0 {
2587 peer.awaiting_pong_timer_tick_intervals += 1;
2591 peer.awaiting_pong_timer_tick_intervals = 1;
2592 let ping = msgs::Ping {
2596 self.enqueue_message(&mut *peer, &ping);
2599 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2603 if !descriptors_needing_disconnect.is_empty() {
2605 let mut peers_lock = self.peers.write().unwrap();
2606 for descriptor in descriptors_needing_disconnect {
2607 if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2608 let peer = peer_mutex.lock().unwrap();
2609 if let Some((node_id, _)) = peer.their_node_id {
2610 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2612 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2620 // Messages of up to 64KB should never end up more than half full with addresses, as that would
2621 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2622 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2624 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (SocketAddress::MAX_LEN as u32 + 1) / 2;
2626 // ...by failing to compile if the number of addresses that would be half of a message is
2627 // smaller than 100:
2628 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2630 /// Generates a signed node_announcement from the given arguments, sending it to all connected
2631 /// peers. Note that peers will likely ignore this message unless we have at least one public
2632 /// channel which has at least six confirmations on-chain.
2634 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2635 /// node to humans. They carry no in-protocol meaning.
2637 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2638 /// accepts incoming connections. These will be included in the node_announcement, publicly
2639 /// tying these addresses together and to this node. If you wish to preserve user privacy,
2640 /// addresses should likely contain only Tor Onion addresses.
2642 /// Panics if `addresses` is absurdly large (more than 100).
2644 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2645 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<SocketAddress>) {
2646 if addresses.len() > 100 {
2647 panic!("More than half the message size was taken up by public addresses!");
2650 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2651 // addresses be sorted for future compatibility.
2652 addresses.sort_by_key(|addr| addr.get_id());
2654 let features = self.message_handler.chan_handler.provided_node_features()
2655 | self.message_handler.route_handler.provided_node_features()
2656 | self.message_handler.onion_message_handler.provided_node_features()
2657 | self.message_handler.custom_message_handler.provided_node_features();
2658 let announcement = msgs::UnsignedNodeAnnouncement {
2660 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2661 node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2663 alias: NodeAlias(alias),
2665 excess_address_data: Vec::new(),
2666 excess_data: Vec::new(),
2668 let node_announce_sig = match self.node_signer.sign_gossip_message(
2669 msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2673 log_error!(self.logger, "Failed to generate signature for node_announcement");
2678 let msg = msgs::NodeAnnouncement {
2679 signature: node_announce_sig,
2680 contents: announcement
2683 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2684 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2685 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2689 fn is_gossip_msg(type_id: u16) -> bool {
2691 msgs::ChannelAnnouncement::TYPE |
2692 msgs::ChannelUpdate::TYPE |
2693 msgs::NodeAnnouncement::TYPE |
2694 msgs::QueryChannelRange::TYPE |
2695 msgs::ReplyChannelRange::TYPE |
2696 msgs::QueryShortChannelIds::TYPE |
2697 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2704 use crate::sign::{NodeSigner, Recipient};
2707 use crate::ln::types::ChannelId;
2708 use crate::ln::features::{InitFeatures, NodeFeatures};
2709 use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2710 use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses, ErroringMessageHandler, MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER};
2711 use crate::ln::{msgs, wire};
2712 use crate::ln::msgs::{Init, LightningError, SocketAddress};
2713 use crate::util::test_utils;
2715 use bitcoin::Network;
2716 use bitcoin::blockdata::constants::ChainHash;
2717 use bitcoin::secp256k1::{PublicKey, SecretKey};
2719 use crate::sync::{Arc, Mutex};
2720 use core::convert::Infallible;
2721 use core::sync::atomic::{AtomicBool, Ordering};
2723 #[allow(unused_imports)]
2724 use crate::prelude::*;
2727 struct FileDescriptor {
2729 outbound_data: Arc<Mutex<Vec<u8>>>,
2730 disconnect: Arc<AtomicBool>,
2732 impl PartialEq for FileDescriptor {
2733 fn eq(&self, other: &Self) -> bool {
2737 impl Eq for FileDescriptor { }
2738 impl core::hash::Hash for FileDescriptor {
2739 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2740 self.fd.hash(hasher)
2744 impl SocketDescriptor for FileDescriptor {
2745 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2746 self.outbound_data.lock().unwrap().extend_from_slice(data);
2750 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2753 struct PeerManagerCfg {
2754 chan_handler: test_utils::TestChannelMessageHandler,
2755 routing_handler: test_utils::TestRoutingMessageHandler,
2756 custom_handler: TestCustomMessageHandler,
2757 logger: test_utils::TestLogger,
2758 node_signer: test_utils::TestNodeSigner,
2761 struct TestCustomMessageHandler {
2762 features: InitFeatures,
2765 impl wire::CustomMessageReader for TestCustomMessageHandler {
2766 type CustomMessage = Infallible;
2767 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2772 impl CustomMessageHandler for TestCustomMessageHandler {
2773 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2777 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2780 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
2782 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
2784 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2786 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2787 self.features.clone()
2791 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2792 let mut cfgs = Vec::new();
2793 for i in 0..peer_count {
2794 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2796 let mut feature_bits = vec![0u8; 33];
2797 feature_bits[32] = 0b00000001;
2798 InitFeatures::from_le_bytes(feature_bits)
2802 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2803 logger: test_utils::TestLogger::new(),
2804 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2805 custom_handler: TestCustomMessageHandler { features },
2806 node_signer: test_utils::TestNodeSigner::new(node_secret),
2814 fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2815 let mut cfgs = Vec::new();
2816 for i in 0..peer_count {
2817 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2819 let mut feature_bits = vec![0u8; 33 + i + 1];
2820 feature_bits[33 + i] = 0b00000001;
2821 InitFeatures::from_le_bytes(feature_bits)
2825 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2826 logger: test_utils::TestLogger::new(),
2827 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2828 custom_handler: TestCustomMessageHandler { features },
2829 node_signer: test_utils::TestNodeSigner::new(node_secret),
2837 fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2838 let mut cfgs = Vec::new();
2839 for i in 0..peer_count {
2840 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2841 let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2842 let network = ChainHash::from(&[i as u8; 32]);
2845 chan_handler: test_utils::TestChannelMessageHandler::new(network),
2846 logger: test_utils::TestLogger::new(),
2847 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2848 custom_handler: TestCustomMessageHandler { features },
2849 node_signer: test_utils::TestNodeSigner::new(node_secret),
2857 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>> {
2858 let mut peers = Vec::new();
2859 for i in 0..peer_count {
2860 let ephemeral_bytes = [i as u8; 32];
2861 let msg_handler = MessageHandler {
2862 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2863 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2865 let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2872 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) {
2873 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2874 let mut fd_a = FileDescriptor {
2875 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2876 disconnect: Arc::new(AtomicBool::new(false)),
2878 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2879 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2880 let features_a = peer_a.init_features(&id_b);
2881 let features_b = peer_b.init_features(&id_a);
2882 let mut fd_b = FileDescriptor {
2883 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2884 disconnect: Arc::new(AtomicBool::new(false)),
2886 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2887 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2888 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2889 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2890 peer_a.process_events();
2892 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2893 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2895 peer_b.process_events();
2896 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2897 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2899 peer_a.process_events();
2900 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2901 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2903 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().counterparty_node_id, id_b);
2904 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().socket_address, Some(addr_b));
2905 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().init_features, features_b);
2906 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().counterparty_node_id, id_a);
2907 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().socket_address, Some(addr_a));
2908 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().init_features, features_a);
2909 (fd_a.clone(), fd_b.clone())
2913 #[cfg(feature = "std")]
2914 fn fuzz_threaded_connections() {
2915 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2916 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2917 // with our internal map consistency, and is a generally good smoke test of disconnection.
2918 let cfgs = Arc::new(create_peermgr_cfgs(2));
2919 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2920 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2922 let start_time = std::time::Instant::now();
2923 macro_rules! spawn_thread { ($id: expr) => { {
2924 let peers = Arc::clone(&peers);
2925 let cfgs = Arc::clone(&cfgs);
2926 std::thread::spawn(move || {
2928 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2929 let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2930 let mut fd_a = FileDescriptor {
2931 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2932 disconnect: Arc::new(AtomicBool::new(false)),
2934 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2935 let mut fd_b = FileDescriptor {
2936 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2937 disconnect: Arc::new(AtomicBool::new(false)),
2939 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2940 let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2941 peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2942 if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2944 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2945 peers[0].process_events();
2946 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2947 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2948 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2950 peers[1].process_events();
2951 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2952 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2953 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2955 cfgs[0].chan_handler.pending_events.lock().unwrap()
2956 .push(crate::events::MessageSendEvent::SendShutdown {
2957 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2958 msg: msgs::Shutdown {
2959 channel_id: ChannelId::new_zero(),
2960 scriptpubkey: bitcoin::ScriptBuf::new(),
2963 cfgs[1].chan_handler.pending_events.lock().unwrap()
2964 .push(crate::events::MessageSendEvent::SendShutdown {
2965 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2966 msg: msgs::Shutdown {
2967 channel_id: ChannelId::new_zero(),
2968 scriptpubkey: bitcoin::ScriptBuf::new(),
2973 peers[0].timer_tick_occurred();
2974 peers[1].timer_tick_occurred();
2978 peers[0].socket_disconnected(&fd_a);
2979 peers[1].socket_disconnected(&fd_b);
2981 std::thread::sleep(std::time::Duration::from_micros(1));
2985 let thrd_a = spawn_thread!(1);
2986 let thrd_b = spawn_thread!(2);
2988 thrd_a.join().unwrap();
2989 thrd_b.join().unwrap();
2993 fn test_feature_incompatible_peers() {
2994 let cfgs = create_peermgr_cfgs(2);
2995 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2997 let peers = create_network(2, &cfgs);
2998 let incompatible_peers = create_network(2, &incompatible_cfgs);
2999 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
3000 for (peer_a, peer_b) in peer_pairs.iter() {
3001 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
3002 let mut fd_a = FileDescriptor {
3003 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3004 disconnect: Arc::new(AtomicBool::new(false)),
3006 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
3007 let mut fd_b = FileDescriptor {
3008 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3009 disconnect: Arc::new(AtomicBool::new(false)),
3011 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
3012 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
3013 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
3014 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
3015 peer_a.process_events();
3017 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3018 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
3020 peer_b.process_events();
3021 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3023 // Should fail because of unknown required features
3024 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
3029 fn test_chain_incompatible_peers() {
3030 let cfgs = create_peermgr_cfgs(2);
3031 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
3033 let peers = create_network(2, &cfgs);
3034 let incompatible_peers = create_network(2, &incompatible_cfgs);
3035 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
3036 for (peer_a, peer_b) in peer_pairs.iter() {
3037 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
3038 let mut fd_a = FileDescriptor {
3039 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3040 disconnect: Arc::new(AtomicBool::new(false)),
3042 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
3043 let mut fd_b = FileDescriptor {
3044 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3045 disconnect: Arc::new(AtomicBool::new(false)),
3047 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
3048 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
3049 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
3050 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
3051 peer_a.process_events();
3053 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3054 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
3056 peer_b.process_events();
3057 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3059 // Should fail because of incompatible chains
3060 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
3065 fn test_disconnect_peer() {
3066 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3067 // push a DisconnectPeer event to remove the node flagged by id
3068 let cfgs = create_peermgr_cfgs(2);
3069 let peers = create_network(2, &cfgs);
3070 establish_connection(&peers[0], &peers[1]);
3071 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3073 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
3074 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
3076 action: msgs::ErrorAction::DisconnectPeer { msg: None },
3079 peers[0].process_events();
3080 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3084 fn test_send_simple_msg() {
3085 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3086 // push a message from one peer to another.
3087 let cfgs = create_peermgr_cfgs(2);
3088 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3089 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3090 let mut peers = create_network(2, &cfgs);
3091 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3092 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3094 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
3096 let msg = msgs::Shutdown { channel_id: ChannelId::from_bytes([42; 32]), scriptpubkey: bitcoin::ScriptBuf::new() };
3097 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
3098 node_id: their_id, msg: msg.clone()
3100 peers[0].message_handler.chan_handler = &a_chan_handler;
3102 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
3103 peers[1].message_handler.chan_handler = &b_chan_handler;
3105 peers[0].process_events();
3107 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3108 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3112 fn test_non_init_first_msg() {
3113 // Simple test of the first message received over a connection being something other than
3114 // Init. This results in an immediate disconnection, which previously included a spurious
3115 // peer_disconnected event handed to event handlers (which would panic in
3116 // `TestChannelMessageHandler` here).
3117 let cfgs = create_peermgr_cfgs(2);
3118 let peers = create_network(2, &cfgs);
3120 let mut fd_dup = FileDescriptor {
3121 fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
3122 disconnect: Arc::new(AtomicBool::new(false)),
3124 let addr_dup = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1003};
3125 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
3126 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
3128 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
3129 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
3130 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
3131 peers[0].process_events();
3133 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
3134 let (act_three, _) =
3135 dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
3136 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
3138 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
3139 let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg);
3140 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
3144 fn test_disconnect_all_peer() {
3145 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3146 // then calls disconnect_all_peers
3147 let cfgs = create_peermgr_cfgs(2);
3148 let peers = create_network(2, &cfgs);
3149 establish_connection(&peers[0], &peers[1]);
3150 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3152 peers[0].disconnect_all_peers();
3153 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3157 fn test_timer_tick_occurred() {
3158 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
3159 let cfgs = create_peermgr_cfgs(2);
3160 let peers = create_network(2, &cfgs);
3161 establish_connection(&peers[0], &peers[1]);
3162 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3164 // peers[0] awaiting_pong is set to true, but the Peer is still connected
3165 peers[0].timer_tick_occurred();
3166 peers[0].process_events();
3167 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3169 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
3170 peers[0].timer_tick_occurred();
3171 peers[0].process_events();
3172 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3176 fn test_do_attempt_write_data() {
3177 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
3178 let cfgs = create_peermgr_cfgs(2);
3179 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3180 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3181 let peers = create_network(2, &cfgs);
3183 // By calling establish_connect, we trigger do_attempt_write_data between
3184 // the peers. Previously this function would mistakenly enter an infinite loop
3185 // when there were more channel messages available than could fit into a peer's
3186 // buffer. This issue would now be detected by this test (because we use custom
3187 // RoutingMessageHandlers that intentionally return more channel messages
3188 // than can fit into a peer's buffer).
3189 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3191 // Make each peer to read the messages that the other peer just wrote to them. Note that
3192 // due to the max-message-before-ping limits this may take a few iterations to complete.
3193 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
3194 peers[1].process_events();
3195 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3196 assert!(!a_read_data.is_empty());
3198 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
3199 peers[0].process_events();
3201 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3202 assert!(!b_read_data.is_empty());
3203 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
3205 peers[0].process_events();
3206 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
3209 // Check that each peer has received the expected number of channel updates and channel
3211 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3212 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3213 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3214 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3218 fn test_handshake_timeout() {
3219 // Tests that we time out a peer still waiting on handshake completion after a full timer
3221 let cfgs = create_peermgr_cfgs(2);
3222 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3223 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3224 let peers = create_network(2, &cfgs);
3226 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
3227 let mut fd_a = FileDescriptor {
3228 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3229 disconnect: Arc::new(AtomicBool::new(false)),
3231 let mut fd_b = FileDescriptor {
3232 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3233 disconnect: Arc::new(AtomicBool::new(false)),
3235 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3236 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3238 // If we get a single timer tick before completion, that's fine
3239 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3240 peers[0].timer_tick_occurred();
3241 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3243 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3244 peers[0].process_events();
3245 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3246 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3247 peers[1].process_events();
3249 // ...but if we get a second timer tick, we should disconnect the peer
3250 peers[0].timer_tick_occurred();
3251 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3253 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3254 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3258 fn test_inbound_conn_handshake_complete_awaiting_pong() {
3259 // Test that we do not disconnect an outbound peer after the noise handshake completes due
3260 // to a pong timeout for a ping that was never sent if a timer tick fires after we send act
3261 // two of the noise handshake along with our init message but before we receive their init
3263 let logger = test_utils::TestLogger::new();
3264 let node_signer_a = test_utils::TestNodeSigner::new(SecretKey::from_slice(&[42; 32]).unwrap());
3265 let node_signer_b = test_utils::TestNodeSigner::new(SecretKey::from_slice(&[43; 32]).unwrap());
3266 let peer_a = PeerManager::new(MessageHandler {
3267 chan_handler: ErroringMessageHandler::new(),
3268 route_handler: IgnoringMessageHandler {},
3269 onion_message_handler: IgnoringMessageHandler {},
3270 custom_message_handler: IgnoringMessageHandler {},
3271 }, 0, &[0; 32], &logger, &node_signer_a);
3272 let peer_b = PeerManager::new(MessageHandler {
3273 chan_handler: ErroringMessageHandler::new(),
3274 route_handler: IgnoringMessageHandler {},
3275 onion_message_handler: IgnoringMessageHandler {},
3276 custom_message_handler: IgnoringMessageHandler {},
3277 }, 0, &[1; 32], &logger, &node_signer_b);
3279 let a_id = node_signer_a.get_node_id(Recipient::Node).unwrap();
3280 let mut fd_a = FileDescriptor {
3281 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3282 disconnect: Arc::new(AtomicBool::new(false)),
3284 let mut fd_b = FileDescriptor {
3285 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3286 disconnect: Arc::new(AtomicBool::new(false)),
3289 // Exchange messages with both peers until they both complete the init handshake.
3290 let act_one = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3291 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
3293 assert_eq!(peer_a.read_event(&mut fd_a, &act_one).unwrap(), false);
3294 peer_a.process_events();
3296 let act_two = fd_a.outbound_data.lock().unwrap().split_off(0);
3297 assert_eq!(peer_b.read_event(&mut fd_b, &act_two).unwrap(), false);
3298 peer_b.process_events();
3300 // Calling this here triggers the race on inbound connections.
3301 peer_b.timer_tick_occurred();
3303 let act_three_with_init_b = fd_b.outbound_data.lock().unwrap().split_off(0);
3304 assert!(!peer_a.peers.read().unwrap().get(&fd_a).unwrap().lock().unwrap().handshake_complete());
3305 assert_eq!(peer_a.read_event(&mut fd_a, &act_three_with_init_b).unwrap(), false);
3306 peer_a.process_events();
3307 assert!(peer_a.peers.read().unwrap().get(&fd_a).unwrap().lock().unwrap().handshake_complete());
3309 let init_a = fd_a.outbound_data.lock().unwrap().split_off(0);
3310 assert!(!init_a.is_empty());
3312 assert!(!peer_b.peers.read().unwrap().get(&fd_b).unwrap().lock().unwrap().handshake_complete());
3313 assert_eq!(peer_b.read_event(&mut fd_b, &init_a).unwrap(), false);
3314 peer_b.process_events();
3315 assert!(peer_b.peers.read().unwrap().get(&fd_b).unwrap().lock().unwrap().handshake_complete());
3317 // Make sure we're still connected.
3318 assert_eq!(peer_b.peers.read().unwrap().len(), 1);
3320 // B should send a ping on the first timer tick after `handshake_complete`.
3321 assert!(fd_b.outbound_data.lock().unwrap().split_off(0).is_empty());
3322 peer_b.timer_tick_occurred();
3323 peer_b.process_events();
3324 assert!(!fd_b.outbound_data.lock().unwrap().split_off(0).is_empty());
3326 let mut send_warning = || {
3328 let peers = peer_a.peers.read().unwrap();
3329 let mut peer_b = peers.get(&fd_a).unwrap().lock().unwrap();
3330 peer_a.enqueue_message(&mut peer_b, &msgs::WarningMessage {
3331 channel_id: ChannelId([0; 32]),
3332 data: "no disconnect plz".to_string(),
3335 peer_a.process_events();
3336 let msg = fd_a.outbound_data.lock().unwrap().split_off(0);
3337 assert!(!msg.is_empty());
3338 assert_eq!(peer_b.read_event(&mut fd_b, &msg).unwrap(), false);
3339 peer_b.process_events();
3342 // Fire more ticks until we reach the pong timeout. We send any message except pong to
3343 // pretend the connection is still alive.
3345 for _ in 0..MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER {
3346 peer_b.timer_tick_occurred();
3349 assert_eq!(peer_b.peers.read().unwrap().len(), 1);
3351 // One more tick should enforce the pong timeout.
3352 peer_b.timer_tick_occurred();
3353 assert_eq!(peer_b.peers.read().unwrap().len(), 0);
3357 fn test_filter_addresses(){
3358 // Tests the filter_addresses function.
3361 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 0, 0], port: 1000};
3362 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3363 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 255, 201], port: 1000};
3364 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3365 let ip_address = SocketAddress::TcpIpV4{addr: [10, 255, 255, 255], port: 1000};
3366 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3369 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 0, 0], port: 1000};
3370 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3371 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 255, 187], port: 1000};
3372 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3373 let ip_address = SocketAddress::TcpIpV4{addr: [0, 255, 255, 255], port: 1000};
3374 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3377 let ip_address = SocketAddress::TcpIpV4{addr: [100, 64, 0, 0], port: 1000};
3378 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3379 let ip_address = SocketAddress::TcpIpV4{addr: [100, 78, 255, 0], port: 1000};
3380 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3381 let ip_address = SocketAddress::TcpIpV4{addr: [100, 127, 255, 255], port: 1000};
3382 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3385 let ip_address = SocketAddress::TcpIpV4{addr: [127, 0, 0, 0], port: 1000};
3386 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3387 let ip_address = SocketAddress::TcpIpV4{addr: [127, 65, 73, 0], port: 1000};
3388 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3389 let ip_address = SocketAddress::TcpIpV4{addr: [127, 255, 255, 255], port: 1000};
3390 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3393 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 0, 0], port: 1000};
3394 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3395 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 221, 101], port: 1000};
3396 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3397 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 255, 255], port: 1000};
3398 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3401 let ip_address = SocketAddress::TcpIpV4{addr: [172, 16, 0, 0], port: 1000};
3402 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3403 let ip_address = SocketAddress::TcpIpV4{addr: [172, 27, 101, 23], port: 1000};
3404 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3405 let ip_address = SocketAddress::TcpIpV4{addr: [172, 31, 255, 255], port: 1000};
3406 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3409 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 0, 0], port: 1000};
3410 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3411 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 205, 159], port: 1000};
3412 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3413 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 255, 255], port: 1000};
3414 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3416 // For (192.88.99/24)
3417 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 0], port: 1000};
3418 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3419 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 140], port: 1000};
3420 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3421 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 255], port: 1000};
3422 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3424 // For other IPv4 addresses
3425 let ip_address = SocketAddress::TcpIpV4{addr: [188, 255, 99, 0], port: 1000};
3426 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3427 let ip_address = SocketAddress::TcpIpV4{addr: [123, 8, 129, 14], port: 1000};
3428 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3429 let ip_address = SocketAddress::TcpIpV4{addr: [2, 88, 9, 255], port: 1000};
3430 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3433 let ip_address = SocketAddress::TcpIpV6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3434 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3435 let ip_address = SocketAddress::TcpIpV6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3436 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3437 let ip_address = SocketAddress::TcpIpV6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3438 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3440 // For other IPv6 addresses
3441 let ip_address = SocketAddress::TcpIpV6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3442 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3443 let ip_address = SocketAddress::TcpIpV6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3444 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3445 let ip_address = SocketAddress::TcpIpV6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3446 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3449 assert_eq!(filter_addresses(None), None);
3453 #[cfg(feature = "std")]
3454 fn test_process_events_multithreaded() {
3455 use std::time::{Duration, Instant};
3456 // Test that `process_events` getting called on multiple threads doesn't generate too many
3458 // Each time `process_events` goes around the loop we call
3459 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3460 // Because the loop should go around once more after a call which fails to take the
3461 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3462 // should never observe there having been more than 2 loop iterations.
3463 // Further, because the last thread to exit will call `process_events` before returning, we
3464 // should always have at least one count at the end.
3465 let cfg = Arc::new(create_peermgr_cfgs(1));
3466 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3467 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3469 let exit_flag = Arc::new(AtomicBool::new(false));
3470 macro_rules! spawn_thread { () => { {
3471 let thread_cfg = Arc::clone(&cfg);
3472 let thread_peer = Arc::clone(&peer);
3473 let thread_exit = Arc::clone(&exit_flag);
3474 std::thread::spawn(move || {
3475 while !thread_exit.load(Ordering::Acquire) {
3476 thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3477 thread_peer.process_events();
3478 std::thread::sleep(Duration::from_micros(1));
3483 let thread_a = spawn_thread!();
3484 let thread_b = spawn_thread!();
3485 let thread_c = spawn_thread!();
3487 let start_time = Instant::now();
3488 while start_time.elapsed() < Duration::from_millis(100) {
3489 let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3491 std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3494 exit_flag.store(true, Ordering::Release);
3495 thread_a.join().unwrap();
3496 thread_b.join().unwrap();
3497 thread_c.join().unwrap();
3498 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);