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::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
23 use crate::ln::ChannelId;
24 use crate::ln::features::{InitFeatures, NodeFeatures};
26 use crate::ln::msgs::{ChannelMessageHandler, 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::messenger::{CustomOnionMessageHandler, PendingOnionMessage};
32 use crate::onion_message::offers::{OffersMessage, OffersMessageHandler};
33 use crate::onion_message::packet::OnionMessageContents;
34 use crate::routing::gossip::{NodeId, NodeAlias};
35 use crate::util::atomic_counter::AtomicCounter;
36 use crate::util::logger::{Level, Logger, WithContext};
37 use crate::util::string::PrintableString;
39 #[allow(unused_imports)]
40 use crate::prelude::*;
43 use crate::sync::{Mutex, MutexGuard, FairRwLock};
44 use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering};
45 use core::{cmp, hash, fmt, mem};
47 use core::convert::Infallible;
48 #[cfg(feature = "std")]
50 #[cfg(not(c_bindings))]
52 crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager},
53 crate::onion_message::messenger::{SimpleArcOnionMessenger, SimpleRefOnionMessenger},
54 crate::routing::gossip::{NetworkGraph, P2PGossipSync},
55 crate::sign::KeysManager,
59 use bitcoin::hashes::sha256::Hash as Sha256;
60 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
61 use bitcoin::hashes::{HashEngine, Hash};
63 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
65 /// [BOLT 1] specifies a custom message type range for use with experimental or application-specific
66 /// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the
67 /// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler.
69 /// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
70 /// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message
71 pub trait CustomMessageHandler: wire::CustomMessageReader {
72 /// Handles the given message sent from `sender_node_id`, possibly producing messages for
73 /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`]
75 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
77 /// Returns the list of pending messages that were generated by the handler, clearing the list
78 /// in the process. Each message is paired with the node id of the intended recipient. If no
79 /// connection to the node exists, then the message is simply not sent.
80 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
82 /// Gets the node feature flags which this handler itself supports. All available handlers are
83 /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
84 /// which are broadcasted in our [`NodeAnnouncement`] message.
86 /// [`NodeAnnouncement`]: crate::ln::msgs::NodeAnnouncement
87 fn provided_node_features(&self) -> NodeFeatures;
89 /// Gets the init feature flags which should be sent to the given peer. All available handlers
90 /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
91 /// which are sent in our [`Init`] message.
93 /// [`Init`]: crate::ln::msgs::Init
94 fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
97 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
98 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
99 pub struct IgnoringMessageHandler{}
100 impl EventsProvider for IgnoringMessageHandler {
101 fn process_pending_events<H: Deref>(&self, _handler: H) where H::Target: EventHandler {}
103 impl MessageSendEventsProvider for IgnoringMessageHandler {
104 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
106 impl RoutingMessageHandler for IgnoringMessageHandler {
107 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
108 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
109 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
110 fn get_next_channel_announcement(&self, _starting_point: u64) ->
111 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
112 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
113 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
114 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
115 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
116 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
117 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
118 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
119 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
120 let mut features = InitFeatures::empty();
121 features.set_gossip_queries_optional();
124 fn processing_queue_high(&self) -> bool { false }
126 impl OnionMessageHandler for IgnoringMessageHandler {
127 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
128 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
129 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
130 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
131 fn timer_tick_occurred(&self) {}
132 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
133 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
134 InitFeatures::empty()
137 impl OffersMessageHandler for IgnoringMessageHandler {
138 fn handle_message(&self, _msg: OffersMessage) -> Option<OffersMessage> { None }
140 impl CustomOnionMessageHandler for IgnoringMessageHandler {
141 type CustomMessage = Infallible;
142 fn handle_custom_message(&self, _msg: Infallible) -> Option<Infallible> {
143 // Since we always return `None` in the read the handle method should never be called.
146 fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
149 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Infallible>> {
154 impl OnionMessageContents for Infallible {
155 fn tlv_type(&self) -> u64 { unreachable!(); }
158 impl Deref for IgnoringMessageHandler {
159 type Target = IgnoringMessageHandler;
160 fn deref(&self) -> &Self { self }
163 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
164 // method that takes self for it.
165 impl wire::Type for Infallible {
166 fn type_id(&self) -> u16 {
170 impl Writeable for Infallible {
171 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
176 impl wire::CustomMessageReader for IgnoringMessageHandler {
177 type CustomMessage = Infallible;
178 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
183 impl CustomMessageHandler for IgnoringMessageHandler {
184 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
185 // Since we always return `None` in the read the handle method should never be called.
189 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
191 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
193 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
194 InitFeatures::empty()
198 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
199 /// You can provide one of these as the route_handler in a MessageHandler.
200 pub struct ErroringMessageHandler {
201 message_queue: Mutex<Vec<MessageSendEvent>>
203 impl ErroringMessageHandler {
204 /// Constructs a new ErroringMessageHandler
205 pub fn new() -> Self {
206 Self { message_queue: Mutex::new(Vec::new()) }
208 fn push_error(&self, node_id: &PublicKey, channel_id: ChannelId) {
209 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
210 action: msgs::ErrorAction::SendErrorMessage {
211 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
213 node_id: node_id.clone(),
217 impl MessageSendEventsProvider for ErroringMessageHandler {
218 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
219 let mut res = Vec::new();
220 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
224 impl ChannelMessageHandler for ErroringMessageHandler {
225 // Any messages which are related to a specific channel generate an error message to let the
226 // peer know we don't care about channels.
227 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
228 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
230 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
231 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
233 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
234 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
236 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
237 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
239 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
240 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
242 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
243 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
245 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
246 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
248 fn handle_stfu(&self, their_node_id: &PublicKey, msg: &msgs::Stfu) {
249 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
252 fn handle_splice(&self, their_node_id: &PublicKey, msg: &msgs::Splice) {
253 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
256 fn handle_splice_ack(&self, their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
257 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
260 fn handle_splice_locked(&self, their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
261 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
263 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
264 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
266 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
267 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
269 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
270 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
272 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
273 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
275 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
276 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
278 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
279 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
281 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
282 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
284 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
285 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
287 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
288 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
290 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
291 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
292 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
293 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
294 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
295 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
296 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
297 // Set a number of features which various nodes may require to talk to us. It's totally
298 // reasonable to indicate we "support" all kinds of channel features...we just reject all
300 let mut features = InitFeatures::empty();
301 features.set_data_loss_protect_optional();
302 features.set_upfront_shutdown_script_optional();
303 features.set_variable_length_onion_optional();
304 features.set_static_remote_key_optional();
305 features.set_payment_secret_optional();
306 features.set_basic_mpp_optional();
307 features.set_wumbo_optional();
308 features.set_shutdown_any_segwit_optional();
309 features.set_channel_type_optional();
310 features.set_scid_privacy_optional();
311 features.set_zero_conf_optional();
312 features.set_route_blinding_optional();
316 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
317 // We don't enforce any chains upon peer connection for `ErroringMessageHandler` and leave it up
318 // to users of `ErroringMessageHandler` to make decisions on network compatiblility.
319 // There's not really any way to pull in specific networks here, and hardcoding can cause breakages.
323 fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
324 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
327 fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
328 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
331 fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
332 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
335 fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
336 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
339 fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
340 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
343 fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
344 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
347 fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &msgs::TxComplete) {
348 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
351 fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
352 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
355 fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
356 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
359 fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
360 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
363 fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &msgs::TxAbort) {
364 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
368 impl Deref for ErroringMessageHandler {
369 type Target = ErroringMessageHandler;
370 fn deref(&self) -> &Self { self }
373 /// Provides references to trait impls which handle different types of messages.
374 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref, CustomM: Deref> where
375 CM::Target: ChannelMessageHandler,
376 RM::Target: RoutingMessageHandler,
377 OM::Target: OnionMessageHandler,
378 CustomM::Target: CustomMessageHandler,
380 /// A message handler which handles messages specific to channels. Usually this is just a
381 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
383 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
384 pub chan_handler: CM,
385 /// A message handler which handles messages updating our knowledge of the network channel
386 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
388 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
389 pub route_handler: RM,
391 /// A message handler which handles onion messages. This should generally be an
392 /// [`OnionMessenger`], but can also be an [`IgnoringMessageHandler`].
394 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
395 pub onion_message_handler: OM,
397 /// A message handler which handles custom messages. The only LDK-provided implementation is
398 /// [`IgnoringMessageHandler`].
399 pub custom_message_handler: CustomM,
402 /// Provides an object which can be used to send data to and which uniquely identifies a connection
403 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
404 /// implement Hash to meet the PeerManager API.
406 /// For efficiency, [`Clone`] should be relatively cheap for this type.
408 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
409 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
410 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
411 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
412 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
413 /// to simply use another value which is guaranteed to be globally unique instead.
414 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
415 /// Attempts to send some data from the given slice to the peer.
417 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
418 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
419 /// called and further write attempts may occur until that time.
421 /// If the returned size is smaller than `data.len()`, a
422 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
423 /// written. Additionally, until a `send_data` event completes fully, no further
424 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
425 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
428 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
429 /// (indicating that read events should be paused to prevent DoS in the send buffer),
430 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
431 /// `resume_read` of false carries no meaning, and should not cause any action.
432 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
433 /// Disconnect the socket pointed to by this SocketDescriptor.
435 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
436 /// call (doing so is a noop).
437 fn disconnect_socket(&mut self);
440 /// Details of a connected peer as returned by [`PeerManager::list_peers`].
441 pub struct PeerDetails {
442 /// The node id of the peer.
444 /// For outbound connections, this [`PublicKey`] will be the same as the `their_node_id` parameter
445 /// passed in to [`PeerManager::new_outbound_connection`].
446 pub counterparty_node_id: PublicKey,
447 /// The socket address the peer provided in the initial handshake.
449 /// Will only be `Some` if an address had been previously provided to
450 /// [`PeerManager::new_outbound_connection`] or [`PeerManager::new_inbound_connection`].
451 pub socket_address: Option<SocketAddress>,
452 /// The features the peer provided in the initial handshake.
453 pub init_features: InitFeatures,
454 /// Indicates the direction of the peer connection.
456 /// Will be `true` for inbound connections, and `false` for outbound connections.
457 pub is_inbound_connection: bool,
460 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
461 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
464 pub struct PeerHandleError { }
465 impl fmt::Debug for PeerHandleError {
466 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
467 formatter.write_str("Peer Sent Invalid Data")
470 impl fmt::Display for PeerHandleError {
471 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
472 formatter.write_str("Peer Sent Invalid Data")
476 #[cfg(feature = "std")]
477 impl error::Error for PeerHandleError {
478 fn description(&self) -> &str {
479 "Peer Sent Invalid Data"
483 enum InitSyncTracker{
485 ChannelsSyncing(u64),
486 NodesSyncing(NodeId),
489 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
490 /// forwarding gossip messages to peers altogether.
491 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
493 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
494 /// we have fewer than this many messages in the outbound buffer again.
495 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
496 /// refilled as we send bytes.
497 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
498 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
500 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
502 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
503 /// the socket receive buffer before receiving the ping.
505 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
506 /// including any network delays, outbound traffic, or the same for messages from other peers.
508 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
509 /// per connected peer to respond to a ping, as long as they send us at least one message during
510 /// each tick, ensuring we aren't actually just disconnected.
511 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
514 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
515 /// two connected peers, assuming most LDK-running systems have at least two cores.
516 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
518 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
519 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
520 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
521 /// process before the next ping.
523 /// Note that we continue responding to other messages even after we've sent this many messages, so
524 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
525 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
526 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
529 channel_encryptor: PeerChannelEncryptor,
530 /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
531 /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
532 their_node_id: Option<(PublicKey, NodeId)>,
533 /// The features provided in the peer's [`msgs::Init`] message.
535 /// This is set only after we've processed the [`msgs::Init`] message and called relevant
536 /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
537 /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
539 their_features: Option<InitFeatures>,
540 their_socket_address: Option<SocketAddress>,
542 pending_outbound_buffer: VecDeque<Vec<u8>>,
543 pending_outbound_buffer_first_msg_offset: usize,
544 /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
545 /// prioritize channel messages over them.
547 /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
548 gossip_broadcast_buffer: VecDeque<MessageBuf>,
549 awaiting_write_event: bool,
551 pending_read_buffer: Vec<u8>,
552 pending_read_buffer_pos: usize,
553 pending_read_is_header: bool,
555 sync_status: InitSyncTracker,
557 msgs_sent_since_pong: usize,
558 awaiting_pong_timer_tick_intervals: i64,
559 received_message_since_timer_tick: bool,
560 sent_gossip_timestamp_filter: bool,
562 /// Indicates we've received a `channel_announcement` since the last time we had
563 /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
564 /// `channel_announcement` at all - we set this unconditionally but unset it every time we
565 /// check if we're gossip-processing-backlogged).
566 received_channel_announce_since_backlogged: bool,
568 inbound_connection: bool,
572 /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
573 /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
575 fn handshake_complete(&self) -> bool {
576 self.their_features.is_some()
579 /// Returns true if the channel announcements/updates for the given channel should be
580 /// forwarded to this peer.
581 /// If we are sending our routing table to this peer and we have not yet sent channel
582 /// announcements/updates for the given channel_id then we will send it when we get to that
583 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
584 /// sent the old versions, we should send the update, and so return true here.
585 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
586 if !self.handshake_complete() { return false; }
587 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
588 !self.sent_gossip_timestamp_filter {
591 match self.sync_status {
592 InitSyncTracker::NoSyncRequested => true,
593 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
594 InitSyncTracker::NodesSyncing(_) => true,
598 /// Similar to the above, but for node announcements indexed by node_id.
599 fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
600 if !self.handshake_complete() { return false; }
601 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
602 !self.sent_gossip_timestamp_filter {
605 match self.sync_status {
606 InitSyncTracker::NoSyncRequested => true,
607 InitSyncTracker::ChannelsSyncing(_) => false,
608 InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
612 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
613 /// buffer still has space and we don't need to pause reads to get some writes out.
614 fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
615 if !gossip_processing_backlogged {
616 self.received_channel_announce_since_backlogged = false;
618 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
619 (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
622 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
623 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
624 fn should_buffer_gossip_backfill(&self) -> bool {
625 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
626 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
627 && self.handshake_complete()
630 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
631 /// every time the peer's buffer may have been drained.
632 fn should_buffer_onion_message(&self) -> bool {
633 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
634 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
637 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
638 /// buffer. This is checked every time the peer's buffer may have been drained.
639 fn should_buffer_gossip_broadcast(&self) -> bool {
640 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
641 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
644 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
645 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
646 let total_outbound_buffered =
647 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
649 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
650 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
653 fn set_their_node_id(&mut self, node_id: PublicKey) {
654 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
658 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
659 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
660 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
661 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
662 /// issues such as overly long function definitions.
664 /// This is not exported to bindings users as type aliases aren't supported in most languages.
665 #[cfg(not(c_bindings))]
666 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<
668 Arc<SimpleArcChannelManager<M, T, F, L>>,
669 Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, C, Arc<L>>>,
670 Arc<SimpleArcOnionMessenger<M, T, F, L>>,
672 IgnoringMessageHandler,
676 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
677 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
678 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
679 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
680 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
681 /// helps with issues such as long function definitions.
683 /// This is not exported to bindings users as type aliases aren't supported in most languages.
684 #[cfg(not(c_bindings))]
685 pub type SimpleRefPeerManager<
686 'a, 'b, 'c, 'd, 'e, 'f, 'logger, 'h, 'i, 'j, 'graph, 'k, SD, M, T, F, C, L
689 &'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, M, T, F, L>,
690 &'f P2PGossipSync<&'graph NetworkGraph<&'logger L>, C, &'logger L>,
691 &'h SimpleRefOnionMessenger<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, 'j, 'k, M, T, F, L>,
693 IgnoringMessageHandler,
698 /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or
699 /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather
700 /// than the full set of bounds on [`PeerManager`] itself.
702 /// This is not exported to bindings users as general cover traits aren't useful in other
704 #[allow(missing_docs)]
705 pub trait APeerManager {
706 type Descriptor: SocketDescriptor;
707 type CMT: ChannelMessageHandler + ?Sized;
708 type CM: Deref<Target=Self::CMT>;
709 type RMT: RoutingMessageHandler + ?Sized;
710 type RM: Deref<Target=Self::RMT>;
711 type OMT: OnionMessageHandler + ?Sized;
712 type OM: Deref<Target=Self::OMT>;
713 type LT: Logger + ?Sized;
714 type L: Deref<Target=Self::LT>;
715 type CMHT: CustomMessageHandler + ?Sized;
716 type CMH: Deref<Target=Self::CMHT>;
717 type NST: NodeSigner + ?Sized;
718 type NS: Deref<Target=Self::NST>;
719 /// Gets a reference to the underlying [`PeerManager`].
720 fn as_ref(&self) -> &PeerManager<Self::Descriptor, Self::CM, Self::RM, Self::OM, Self::L, Self::CMH, Self::NS>;
721 /// Returns the peer manager's [`OnionMessageHandler`].
722 fn onion_message_handler(&self) -> &Self::OMT;
725 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref>
726 APeerManager for PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
727 CM::Target: ChannelMessageHandler,
728 RM::Target: RoutingMessageHandler,
729 OM::Target: OnionMessageHandler,
731 CMH::Target: CustomMessageHandler,
732 NS::Target: NodeSigner,
734 type Descriptor = Descriptor;
735 type CMT = <CM as Deref>::Target;
737 type RMT = <RM as Deref>::Target;
739 type OMT = <OM as Deref>::Target;
741 type LT = <L as Deref>::Target;
743 type CMHT = <CMH as Deref>::Target;
745 type NST = <NS as Deref>::Target;
747 fn as_ref(&self) -> &PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> { self }
748 fn onion_message_handler(&self) -> &Self::OMT {
749 self.message_handler.onion_message_handler.deref()
753 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
754 /// socket events into messages which it passes on to its [`MessageHandler`].
756 /// Locks are taken internally, so you must never assume that reentrancy from a
757 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
759 /// Calls to [`read_event`] will decode relevant messages and pass them to the
760 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
761 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
762 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
763 /// calls only after previous ones have returned.
765 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
766 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
767 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
768 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
769 /// you're using lightning-net-tokio.
771 /// [`read_event`]: PeerManager::read_event
772 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
773 CM::Target: ChannelMessageHandler,
774 RM::Target: RoutingMessageHandler,
775 OM::Target: OnionMessageHandler,
777 CMH::Target: CustomMessageHandler,
778 NS::Target: NodeSigner {
779 message_handler: MessageHandler<CM, RM, OM, CMH>,
780 /// Connection state for each connected peer - we have an outer read-write lock which is taken
781 /// as read while we're doing processing for a peer and taken write when a peer is being added
784 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
785 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
786 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
787 /// the `MessageHandler`s for a given peer is already guaranteed.
788 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
789 /// Only add to this set when noise completes.
790 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
791 /// lock held. Entries may be added with only the `peers` read lock held (though the
792 /// `Descriptor` value must already exist in `peers`).
793 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
794 /// We can only have one thread processing events at once, but if a second call to
795 /// `process_events` happens while a first call is in progress, one of the two calls needs to
796 /// start from the top to ensure any new messages are also handled.
798 /// Because the event handler calls into user code which may block, we don't want to block a
799 /// second thread waiting for another thread to handle events which is then blocked on user
800 /// code, so we store an atomic counter here:
801 /// * 0 indicates no event processor is running
802 /// * 1 indicates an event processor is running
803 /// * > 1 indicates an event processor is running but needs to start again from the top once
804 /// it finishes as another thread tried to start processing events but returned early.
805 event_processing_state: AtomicI32,
807 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
808 /// value increases strictly since we don't assume access to a time source.
809 last_node_announcement_serial: AtomicU32,
811 ephemeral_key_midstate: Sha256Engine,
813 peer_counter: AtomicCounter,
815 gossip_processing_backlogged: AtomicBool,
816 gossip_processing_backlog_lifted: AtomicBool,
821 secp_ctx: Secp256k1<secp256k1::SignOnly>
824 enum MessageHandlingError {
825 PeerHandleError(PeerHandleError),
826 LightningError(LightningError),
829 impl From<PeerHandleError> for MessageHandlingError {
830 fn from(error: PeerHandleError) -> Self {
831 MessageHandlingError::PeerHandleError(error)
835 impl From<LightningError> for MessageHandlingError {
836 fn from(error: LightningError) -> Self {
837 MessageHandlingError::LightningError(error)
841 macro_rules! encode_msg {
843 let mut buffer = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
844 wire::write($msg, &mut buffer).unwrap();
849 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
850 CM::Target: ChannelMessageHandler,
851 OM::Target: OnionMessageHandler,
853 NS::Target: NodeSigner {
854 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
855 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
858 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
859 /// cryptographically secure random bytes.
861 /// `current_time` is used as an always-increasing counter that survives across restarts and is
862 /// incremented irregularly internally. In general it is best to simply use the current UNIX
863 /// timestamp, however if it is not available a persistent counter that increases once per
864 /// minute should suffice.
866 /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
867 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 {
868 Self::new(MessageHandler {
869 chan_handler: channel_message_handler,
870 route_handler: IgnoringMessageHandler{},
871 onion_message_handler,
872 custom_message_handler: IgnoringMessageHandler{},
873 }, current_time, ephemeral_random_data, logger, node_signer)
877 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
878 RM::Target: RoutingMessageHandler,
880 NS::Target: NodeSigner {
881 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
882 /// handler or onion message handler is used and onion and channel messages will be ignored (or
883 /// generate error messages). Note that some other lightning implementations time-out connections
884 /// after some time if no channel is built with the peer.
886 /// `current_time` is used as an always-increasing counter that survives across restarts and is
887 /// incremented irregularly internally. In general it is best to simply use the current UNIX
888 /// timestamp, however if it is not available a persistent counter that increases once per
889 /// minute should suffice.
891 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
892 /// cryptographically secure random bytes.
894 /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
895 pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
896 Self::new(MessageHandler {
897 chan_handler: ErroringMessageHandler::new(),
898 route_handler: routing_message_handler,
899 onion_message_handler: IgnoringMessageHandler{},
900 custom_message_handler: IgnoringMessageHandler{},
901 }, current_time, ephemeral_random_data, logger, node_signer)
905 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
906 /// This works around `format!()` taking a reference to each argument, preventing
907 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
908 /// due to lifetime errors.
909 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
910 impl core::fmt::Display for OptionalFromDebugger<'_> {
911 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
912 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
916 /// A function used to filter out local or private addresses
917 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
918 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
919 fn filter_addresses(ip_address: Option<SocketAddress>) -> Option<SocketAddress> {
921 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
922 Some(SocketAddress::TcpIpV4{addr: [10, _, _, _], port: _}) => None,
923 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
924 Some(SocketAddress::TcpIpV4{addr: [0, _, _, _], port: _}) => None,
925 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
926 Some(SocketAddress::TcpIpV4{addr: [100, 64..=127, _, _], port: _}) => None,
927 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
928 Some(SocketAddress::TcpIpV4{addr: [127, _, _, _], port: _}) => None,
929 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
930 Some(SocketAddress::TcpIpV4{addr: [169, 254, _, _], port: _}) => None,
931 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
932 Some(SocketAddress::TcpIpV4{addr: [172, 16..=31, _, _], port: _}) => None,
933 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
934 Some(SocketAddress::TcpIpV4{addr: [192, 168, _, _], port: _}) => None,
935 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
936 Some(SocketAddress::TcpIpV4{addr: [192, 88, 99, _], port: _}) => None,
937 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
938 Some(SocketAddress::TcpIpV6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
939 // For remaining addresses
940 Some(SocketAddress::TcpIpV6{addr: _, port: _}) => None,
941 Some(..) => ip_address,
946 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
947 CM::Target: ChannelMessageHandler,
948 RM::Target: RoutingMessageHandler,
949 OM::Target: OnionMessageHandler,
951 CMH::Target: CustomMessageHandler,
952 NS::Target: NodeSigner
954 /// Constructs a new `PeerManager` with the given message handlers.
956 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
957 /// cryptographically secure random bytes.
959 /// `current_time` is used as an always-increasing counter that survives across restarts and is
960 /// incremented irregularly internally. In general it is best to simply use the current UNIX
961 /// timestamp, however if it is not available a persistent counter that increases once per
962 /// minute should suffice.
963 pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
964 let mut ephemeral_key_midstate = Sha256::engine();
965 ephemeral_key_midstate.input(ephemeral_random_data);
967 let mut secp_ctx = Secp256k1::signing_only();
968 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).to_byte_array();
969 secp_ctx.seeded_randomize(&ephemeral_hash);
973 peers: FairRwLock::new(new_hash_map()),
974 node_id_to_descriptor: Mutex::new(new_hash_map()),
975 event_processing_state: AtomicI32::new(0),
976 ephemeral_key_midstate,
977 peer_counter: AtomicCounter::new(),
978 gossip_processing_backlogged: AtomicBool::new(false),
979 gossip_processing_backlog_lifted: AtomicBool::new(false),
980 last_node_announcement_serial: AtomicU32::new(current_time),
987 /// Returns a list of [`PeerDetails`] for connected peers that have completed the initial
989 pub fn list_peers(&self) -> Vec<PeerDetails> {
990 let peers = self.peers.read().unwrap();
991 peers.values().filter_map(|peer_mutex| {
992 let p = peer_mutex.lock().unwrap();
993 if !p.handshake_complete() {
996 let details = PeerDetails {
997 // unwrap safety: their_node_id is guaranteed to be `Some` after the handshake
999 counterparty_node_id: p.their_node_id.unwrap().0,
1000 socket_address: p.their_socket_address.clone(),
1001 // unwrap safety: their_features is guaranteed to be `Some` after the handshake
1003 init_features: p.their_features.clone().unwrap(),
1004 is_inbound_connection: p.inbound_connection,
1010 /// Returns the [`PeerDetails`] of a connected peer that has completed the initial handshake.
1012 /// Will return `None` if the peer is unknown or it hasn't completed the initial handshake.
1013 pub fn peer_by_node_id(&self, their_node_id: &PublicKey) -> Option<PeerDetails> {
1014 let peers = self.peers.read().unwrap();
1015 peers.values().find_map(|peer_mutex| {
1016 let p = peer_mutex.lock().unwrap();
1017 if !p.handshake_complete() {
1021 // unwrap safety: their_node_id is guaranteed to be `Some` after the handshake
1023 let counterparty_node_id = p.their_node_id.unwrap().0;
1025 if counterparty_node_id != *their_node_id {
1029 let details = PeerDetails {
1030 counterparty_node_id,
1031 socket_address: p.their_socket_address.clone(),
1032 // unwrap safety: their_features is guaranteed to be `Some` after the handshake
1034 init_features: p.their_features.clone().unwrap(),
1035 is_inbound_connection: p.inbound_connection,
1041 fn get_ephemeral_key(&self) -> SecretKey {
1042 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
1043 let counter = self.peer_counter.get_increment();
1044 ephemeral_hash.input(&counter.to_le_bytes());
1045 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).to_byte_array()).expect("You broke SHA-256!")
1048 fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
1049 self.message_handler.chan_handler.provided_init_features(their_node_id)
1050 | self.message_handler.route_handler.provided_init_features(their_node_id)
1051 | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
1052 | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
1055 /// Indicates a new outbound connection has been established to a node with the given `node_id`
1056 /// and an optional remote network address.
1058 /// The remote network address adds the option to report a remote IP address back to a connecting
1059 /// peer using the init message.
1060 /// The user should pass the remote network address of the host they are connected to.
1062 /// If an `Err` is returned here you must disconnect the connection immediately.
1064 /// Returns a small number of bytes to send to the remote node (currently always 50).
1066 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1067 /// [`socket_disconnected`].
1069 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1070 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<Vec<u8>, PeerHandleError> {
1071 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
1072 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
1073 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
1075 let mut peers = self.peers.write().unwrap();
1076 match peers.entry(descriptor) {
1077 hash_map::Entry::Occupied(_) => {
1078 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1079 Err(PeerHandleError {})
1081 hash_map::Entry::Vacant(e) => {
1082 e.insert(Mutex::new(Peer {
1083 channel_encryptor: peer_encryptor,
1084 their_node_id: None,
1085 their_features: None,
1086 their_socket_address: remote_network_address,
1088 pending_outbound_buffer: VecDeque::new(),
1089 pending_outbound_buffer_first_msg_offset: 0,
1090 gossip_broadcast_buffer: VecDeque::new(),
1091 awaiting_write_event: false,
1093 pending_read_buffer,
1094 pending_read_buffer_pos: 0,
1095 pending_read_is_header: false,
1097 sync_status: InitSyncTracker::NoSyncRequested,
1099 msgs_sent_since_pong: 0,
1100 awaiting_pong_timer_tick_intervals: 0,
1101 received_message_since_timer_tick: false,
1102 sent_gossip_timestamp_filter: false,
1104 received_channel_announce_since_backlogged: false,
1105 inbound_connection: false,
1112 /// Indicates a new inbound connection has been established to a node with an optional remote
1113 /// network address.
1115 /// The remote network address adds the option to report a remote IP address back to a connecting
1116 /// peer using the init message.
1117 /// The user should pass the remote network address of the host they are connected to.
1119 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
1120 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
1121 /// the connection immediately.
1123 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1124 /// [`socket_disconnected`].
1126 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1127 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<(), PeerHandleError> {
1128 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1129 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1131 let mut peers = self.peers.write().unwrap();
1132 match peers.entry(descriptor) {
1133 hash_map::Entry::Occupied(_) => {
1134 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1135 Err(PeerHandleError {})
1137 hash_map::Entry::Vacant(e) => {
1138 e.insert(Mutex::new(Peer {
1139 channel_encryptor: peer_encryptor,
1140 their_node_id: None,
1141 their_features: None,
1142 their_socket_address: remote_network_address,
1144 pending_outbound_buffer: VecDeque::new(),
1145 pending_outbound_buffer_first_msg_offset: 0,
1146 gossip_broadcast_buffer: VecDeque::new(),
1147 awaiting_write_event: false,
1149 pending_read_buffer,
1150 pending_read_buffer_pos: 0,
1151 pending_read_is_header: false,
1153 sync_status: InitSyncTracker::NoSyncRequested,
1155 msgs_sent_since_pong: 0,
1156 awaiting_pong_timer_tick_intervals: 0,
1157 received_message_since_timer_tick: false,
1158 sent_gossip_timestamp_filter: false,
1160 received_channel_announce_since_backlogged: false,
1161 inbound_connection: true,
1168 fn peer_should_read(&self, peer: &mut Peer) -> bool {
1169 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1172 fn update_gossip_backlogged(&self) {
1173 let new_state = self.message_handler.route_handler.processing_queue_high();
1174 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1175 if prev_state && !new_state {
1176 self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1180 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1181 let mut have_written = false;
1182 while !peer.awaiting_write_event {
1183 if peer.should_buffer_onion_message() {
1184 if let Some((peer_node_id, _)) = peer.their_node_id {
1185 if let Some(next_onion_message) =
1186 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1187 self.enqueue_message(peer, &next_onion_message);
1191 if peer.should_buffer_gossip_broadcast() {
1192 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1193 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(msg));
1196 if peer.should_buffer_gossip_backfill() {
1197 match peer.sync_status {
1198 InitSyncTracker::NoSyncRequested => {},
1199 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1200 if let Some((announce, update_a_option, update_b_option)) =
1201 self.message_handler.route_handler.get_next_channel_announcement(c)
1203 self.enqueue_message(peer, &announce);
1204 if let Some(update_a) = update_a_option {
1205 self.enqueue_message(peer, &update_a);
1207 if let Some(update_b) = update_b_option {
1208 self.enqueue_message(peer, &update_b);
1210 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1212 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1215 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1216 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1217 self.enqueue_message(peer, &msg);
1218 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1220 peer.sync_status = InitSyncTracker::NoSyncRequested;
1223 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1224 InitSyncTracker::NodesSyncing(sync_node_id) => {
1225 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1226 self.enqueue_message(peer, &msg);
1227 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1229 peer.sync_status = InitSyncTracker::NoSyncRequested;
1234 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1235 self.maybe_send_extra_ping(peer);
1238 let should_read = self.peer_should_read(peer);
1239 let next_buff = match peer.pending_outbound_buffer.front() {
1241 if force_one_write && !have_written {
1243 let data_sent = descriptor.send_data(&[], should_read);
1244 debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1252 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1253 let data_sent = descriptor.send_data(pending, should_read);
1254 have_written = true;
1255 peer.pending_outbound_buffer_first_msg_offset += data_sent;
1256 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1257 peer.pending_outbound_buffer_first_msg_offset = 0;
1258 peer.pending_outbound_buffer.pop_front();
1259 const VEC_SIZE: usize = ::core::mem::size_of::<Vec<u8>>();
1260 let large_capacity = peer.pending_outbound_buffer.capacity() > 4096 / VEC_SIZE;
1261 let lots_of_slack = peer.pending_outbound_buffer.len()
1262 < peer.pending_outbound_buffer.capacity() / 2;
1263 if large_capacity && lots_of_slack {
1264 peer.pending_outbound_buffer.shrink_to_fit();
1267 peer.awaiting_write_event = true;
1272 /// Indicates that there is room to write data to the given socket descriptor.
1274 /// May return an Err to indicate that the connection should be closed.
1276 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1277 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1278 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1279 /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1282 /// [`send_data`]: SocketDescriptor::send_data
1283 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1284 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1285 let peers = self.peers.read().unwrap();
1286 match peers.get(descriptor) {
1288 // This is most likely a simple race condition where the user found that the socket
1289 // was writeable, then we told the user to `disconnect_socket()`, then they called
1290 // this method. Return an error to make sure we get disconnected.
1291 return Err(PeerHandleError { });
1293 Some(peer_mutex) => {
1294 let mut peer = peer_mutex.lock().unwrap();
1295 peer.awaiting_write_event = false;
1296 self.do_attempt_write_data(descriptor, &mut peer, false);
1302 /// Indicates that data was read from the given socket descriptor.
1304 /// May return an Err to indicate that the connection should be closed.
1306 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1307 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1308 /// [`send_data`] calls to handle responses.
1310 /// If `Ok(true)` is returned, further read_events should not be triggered until a
1311 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1314 /// In order to avoid processing too many messages at once per peer, `data` should be on the
1317 /// [`send_data`]: SocketDescriptor::send_data
1318 /// [`process_events`]: PeerManager::process_events
1319 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1320 match self.do_read_event(peer_descriptor, data) {
1323 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1324 self.disconnect_event_internal(peer_descriptor);
1330 /// Append a message to a peer's pending outbound/write buffer
1331 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1332 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1333 if is_gossip_msg(message.type_id()) {
1334 log_gossip!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1336 log_trace!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1338 peer.msgs_sent_since_pong += 1;
1339 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1342 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1343 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: MessageBuf) {
1344 peer.msgs_sent_since_pong += 1;
1345 debug_assert!(peer.gossip_broadcast_buffer.len() <= OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP);
1346 peer.gossip_broadcast_buffer.push_back(encoded_message);
1349 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1350 let mut pause_read = false;
1351 let peers = self.peers.read().unwrap();
1352 let mut msgs_to_forward = Vec::new();
1353 let mut peer_node_id = None;
1354 match peers.get(peer_descriptor) {
1356 // This is most likely a simple race condition where the user read some bytes
1357 // from the socket, then we told the user to `disconnect_socket()`, then they
1358 // called this method. Return an error to make sure we get disconnected.
1359 return Err(PeerHandleError { });
1361 Some(peer_mutex) => {
1362 let mut read_pos = 0;
1363 while read_pos < data.len() {
1364 macro_rules! try_potential_handleerror {
1365 ($peer: expr, $thing: expr) => {{
1367 let logger = WithContext::from(&self.logger, peer_node_id.map(|(id, _)| id), None);
1372 msgs::ErrorAction::DisconnectPeer { .. } => {
1373 // We may have an `ErrorMessage` to send to the peer,
1374 // but writing to the socket while reading can lead to
1375 // re-entrant code and possibly unexpected behavior. The
1376 // message send is optimistic anyway, and in this case
1377 // we immediately disconnect the peer.
1378 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1379 return Err(PeerHandleError { });
1381 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1382 // We have a `WarningMessage` to send to the peer, but
1383 // writing to the socket while reading can lead to
1384 // re-entrant code and possibly unexpected behavior. The
1385 // message send is optimistic anyway, and in this case
1386 // we immediately disconnect the peer.
1387 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1388 return Err(PeerHandleError { });
1390 msgs::ErrorAction::IgnoreAndLog(level) => {
1391 log_given_level!(logger, level, "Error handling {}message{}; ignoring: {}",
1392 if level == Level::Gossip { "gossip " } else { "" },
1393 OptionalFromDebugger(&peer_node_id), e.err);
1396 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1397 msgs::ErrorAction::IgnoreError => {
1398 log_debug!(logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1401 msgs::ErrorAction::SendErrorMessage { msg } => {
1402 log_debug!(logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1403 self.enqueue_message($peer, &msg);
1406 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1407 log_given_level!(logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1408 self.enqueue_message($peer, &msg);
1417 let mut peer_lock = peer_mutex.lock().unwrap();
1418 let peer = &mut *peer_lock;
1419 let mut msg_to_handle = None;
1420 if peer_node_id.is_none() {
1421 peer_node_id = peer.their_node_id.clone();
1424 assert!(peer.pending_read_buffer.len() > 0);
1425 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1428 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1429 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]);
1430 read_pos += data_to_copy;
1431 peer.pending_read_buffer_pos += data_to_copy;
1434 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1435 peer.pending_read_buffer_pos = 0;
1437 macro_rules! insert_node_id {
1439 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1440 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1441 hash_map::Entry::Occupied(e) => {
1442 log_trace!(logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1443 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1444 // Check that the peers map is consistent with the
1445 // node_id_to_descriptor map, as this has been broken
1447 debug_assert!(peers.get(e.get()).is_some());
1448 return Err(PeerHandleError { })
1450 hash_map::Entry::Vacant(entry) => {
1451 log_debug!(logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1452 entry.insert(peer_descriptor.clone())
1458 let next_step = peer.channel_encryptor.get_noise_step();
1460 NextNoiseStep::ActOne => {
1461 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1462 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1463 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1464 peer.pending_outbound_buffer.push_back(act_two);
1465 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1467 NextNoiseStep::ActTwo => {
1468 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1469 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1470 &self.node_signer));
1471 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1472 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1473 peer.pending_read_is_header = true;
1475 peer.set_their_node_id(their_node_id);
1477 let features = self.init_features(&their_node_id);
1478 let networks = self.message_handler.chan_handler.get_chain_hashes();
1479 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1480 self.enqueue_message(peer, &resp);
1482 NextNoiseStep::ActThree => {
1483 let their_node_id = try_potential_handleerror!(peer,
1484 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1485 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1486 peer.pending_read_is_header = true;
1487 peer.set_their_node_id(their_node_id);
1489 let features = self.init_features(&their_node_id);
1490 let networks = self.message_handler.chan_handler.get_chain_hashes();
1491 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1492 self.enqueue_message(peer, &resp);
1494 NextNoiseStep::NoiseComplete => {
1495 if peer.pending_read_is_header {
1496 let msg_len = try_potential_handleerror!(peer,
1497 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1498 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1499 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1500 if msg_len < 2 { // Need at least the message type tag
1501 return Err(PeerHandleError { });
1503 peer.pending_read_is_header = false;
1505 debug_assert!(peer.pending_read_buffer.len() >= 2 + 16);
1506 try_potential_handleerror!(peer,
1507 peer.channel_encryptor.decrypt_message(&mut peer.pending_read_buffer[..]));
1509 let mut reader = io::Cursor::new(&peer.pending_read_buffer[..peer.pending_read_buffer.len() - 16]);
1510 let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1512 // Reset read buffer
1513 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1514 peer.pending_read_buffer.resize(18, 0);
1515 peer.pending_read_is_header = true;
1517 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1518 let message = match message_result {
1522 // Note that to avoid re-entrancy we never call
1523 // `do_attempt_write_data` from here, causing
1524 // the messages enqueued here to not actually
1525 // be sent before the peer is disconnected.
1526 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1527 log_gossip!(logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1530 (msgs::DecodeError::UnsupportedCompression, _) => {
1531 log_gossip!(logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1532 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: ChannelId::new_zero(), data: "Unsupported message compression: zlib".to_owned() });
1535 (_, Some(ty)) if is_gossip_msg(ty) => {
1536 log_gossip!(logger, "Got an invalid value while deserializing a gossip message");
1537 self.enqueue_message(peer, &msgs::WarningMessage {
1538 channel_id: ChannelId::new_zero(),
1539 data: format!("Unreadable/bogus gossip message of type {}", ty),
1543 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1544 log_debug!(logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1545 return Err(PeerHandleError { });
1547 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1548 (msgs::DecodeError::InvalidValue, _) => {
1549 log_debug!(logger, "Got an invalid value while deserializing message");
1550 return Err(PeerHandleError { });
1552 (msgs::DecodeError::ShortRead, _) => {
1553 log_debug!(logger, "Deserialization failed due to shortness of message");
1554 return Err(PeerHandleError { });
1556 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1557 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1558 (msgs::DecodeError::DangerousValue, _) => return Err(PeerHandleError { }),
1563 msg_to_handle = Some(message);
1568 pause_read = !self.peer_should_read(peer);
1570 if let Some(message) = msg_to_handle {
1571 match self.handle_message(&peer_mutex, peer_lock, message) {
1572 Err(handling_error) => match handling_error {
1573 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1574 MessageHandlingError::LightningError(e) => {
1575 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1579 msgs_to_forward.push(msg);
1588 for msg in msgs_to_forward.drain(..) {
1589 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1595 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1597 /// Returns the message back if it needs to be broadcasted to all other peers.
1600 peer_mutex: &Mutex<Peer>,
1601 peer_lock: MutexGuard<Peer>,
1602 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1603 ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1604 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;
1605 let logger = WithContext::from(&self.logger, Some(their_node_id), None);
1607 let message = match self.do_handle_message_holding_peer_lock(peer_lock, message, &their_node_id, &logger)? {
1608 Some(processed_message) => processed_message,
1609 None => return Ok(None),
1612 self.do_handle_message_without_peer_lock(peer_mutex, message, &their_node_id, &logger)
1615 // Conducts all message processing that requires us to hold the `peer_lock`.
1617 // Returns `None` if the message was fully processed and otherwise returns the message back to
1618 // allow it to be subsequently processed by `do_handle_message_without_peer_lock`.
1619 fn do_handle_message_holding_peer_lock<'a>(
1621 mut peer_lock: MutexGuard<Peer>,
1622 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>,
1623 their_node_id: &PublicKey,
1624 logger: &WithContext<'a, L>
1625 ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError>
1627 peer_lock.received_message_since_timer_tick = true;
1629 // Need an Init as first message
1630 if let wire::Message::Init(msg) = message {
1631 // Check if we have any compatible chains if the `networks` field is specified.
1632 if let Some(networks) = &msg.networks {
1633 if let Some(our_chains) = self.message_handler.chan_handler.get_chain_hashes() {
1634 let mut have_compatible_chains = false;
1635 'our_chains: for our_chain in our_chains.iter() {
1636 for their_chain in networks {
1637 if our_chain == their_chain {
1638 have_compatible_chains = true;
1643 if !have_compatible_chains {
1644 log_debug!(logger, "Peer does not support any of our supported chains");
1645 return Err(PeerHandleError { }.into());
1650 let our_features = self.init_features(&their_node_id);
1651 if msg.features.requires_unknown_bits_from(&our_features) {
1652 log_debug!(logger, "Peer requires features unknown to us");
1653 return Err(PeerHandleError { }.into());
1656 if our_features.requires_unknown_bits_from(&msg.features) {
1657 log_debug!(logger, "We require features unknown to our peer");
1658 return Err(PeerHandleError { }.into());
1661 if peer_lock.their_features.is_some() {
1662 return Err(PeerHandleError { }.into());
1665 log_info!(logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1667 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1668 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1669 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1672 if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1673 log_debug!(logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1674 return Err(PeerHandleError { }.into());
1676 if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1677 log_debug!(logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1678 return Err(PeerHandleError { }.into());
1680 if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1681 log_debug!(logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1682 return Err(PeerHandleError { }.into());
1685 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1686 peer_lock.their_features = Some(msg.features);
1688 } else if peer_lock.their_features.is_none() {
1689 log_debug!(logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1690 return Err(PeerHandleError { }.into());
1693 if let wire::Message::GossipTimestampFilter(_msg) = message {
1694 // When supporting gossip messages, start initial gossip sync only after we receive
1695 // a GossipTimestampFilter
1696 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1697 !peer_lock.sent_gossip_timestamp_filter {
1698 peer_lock.sent_gossip_timestamp_filter = true;
1699 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1704 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1705 peer_lock.received_channel_announce_since_backlogged = true;
1711 // Conducts all message processing that doesn't require us to hold the `peer_lock`.
1713 // Returns the message back if it needs to be broadcasted to all other peers.
1714 fn do_handle_message_without_peer_lock<'a>(
1716 peer_mutex: &Mutex<Peer>,
1717 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>,
1718 their_node_id: &PublicKey,
1719 logger: &WithContext<'a, L>
1720 ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError>
1722 if is_gossip_msg(message.type_id()) {
1723 log_gossip!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1725 log_trace!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1728 let mut should_forward = None;
1731 // Setup and Control messages:
1732 wire::Message::Init(_) => {
1735 wire::Message::GossipTimestampFilter(_) => {
1738 wire::Message::Error(msg) => {
1739 log_debug!(logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1740 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1741 if msg.channel_id.is_zero() {
1742 return Err(PeerHandleError { }.into());
1745 wire::Message::Warning(msg) => {
1746 log_debug!(logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1749 wire::Message::Ping(msg) => {
1750 if msg.ponglen < 65532 {
1751 let resp = msgs::Pong { byteslen: msg.ponglen };
1752 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1755 wire::Message::Pong(_msg) => {
1756 let mut peer_lock = peer_mutex.lock().unwrap();
1757 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1758 peer_lock.msgs_sent_since_pong = 0;
1761 // Channel messages:
1762 wire::Message::OpenChannel(msg) => {
1763 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1765 wire::Message::OpenChannelV2(msg) => {
1766 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1768 wire::Message::AcceptChannel(msg) => {
1769 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1771 wire::Message::AcceptChannelV2(msg) => {
1772 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1775 wire::Message::FundingCreated(msg) => {
1776 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1778 wire::Message::FundingSigned(msg) => {
1779 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1781 wire::Message::ChannelReady(msg) => {
1782 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1785 // Quiescence messages:
1786 wire::Message::Stfu(msg) => {
1787 self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
1791 // Splicing messages:
1792 wire::Message::Splice(msg) => {
1793 self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
1796 wire::Message::SpliceAck(msg) => {
1797 self.message_handler.chan_handler.handle_splice_ack(&their_node_id, &msg);
1800 wire::Message::SpliceLocked(msg) => {
1801 self.message_handler.chan_handler.handle_splice_locked(&their_node_id, &msg);
1804 // Interactive transaction construction messages:
1805 wire::Message::TxAddInput(msg) => {
1806 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1808 wire::Message::TxAddOutput(msg) => {
1809 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1811 wire::Message::TxRemoveInput(msg) => {
1812 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1814 wire::Message::TxRemoveOutput(msg) => {
1815 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1817 wire::Message::TxComplete(msg) => {
1818 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1820 wire::Message::TxSignatures(msg) => {
1821 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1823 wire::Message::TxInitRbf(msg) => {
1824 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1826 wire::Message::TxAckRbf(msg) => {
1827 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1829 wire::Message::TxAbort(msg) => {
1830 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1833 wire::Message::Shutdown(msg) => {
1834 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1836 wire::Message::ClosingSigned(msg) => {
1837 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1840 // Commitment messages:
1841 wire::Message::UpdateAddHTLC(msg) => {
1842 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1844 wire::Message::UpdateFulfillHTLC(msg) => {
1845 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1847 wire::Message::UpdateFailHTLC(msg) => {
1848 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1850 wire::Message::UpdateFailMalformedHTLC(msg) => {
1851 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1854 wire::Message::CommitmentSigned(msg) => {
1855 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1857 wire::Message::RevokeAndACK(msg) => {
1858 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1860 wire::Message::UpdateFee(msg) => {
1861 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1863 wire::Message::ChannelReestablish(msg) => {
1864 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1867 // Routing messages:
1868 wire::Message::AnnouncementSignatures(msg) => {
1869 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1871 wire::Message::ChannelAnnouncement(msg) => {
1872 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1873 .map_err(|e| -> MessageHandlingError { e.into() })? {
1874 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1876 self.update_gossip_backlogged();
1878 wire::Message::NodeAnnouncement(msg) => {
1879 if self.message_handler.route_handler.handle_node_announcement(&msg)
1880 .map_err(|e| -> MessageHandlingError { e.into() })? {
1881 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1883 self.update_gossip_backlogged();
1885 wire::Message::ChannelUpdate(msg) => {
1886 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1887 if self.message_handler.route_handler.handle_channel_update(&msg)
1888 .map_err(|e| -> MessageHandlingError { e.into() })? {
1889 should_forward = Some(wire::Message::ChannelUpdate(msg));
1891 self.update_gossip_backlogged();
1893 wire::Message::QueryShortChannelIds(msg) => {
1894 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1896 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1897 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1899 wire::Message::QueryChannelRange(msg) => {
1900 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1902 wire::Message::ReplyChannelRange(msg) => {
1903 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1907 wire::Message::OnionMessage(msg) => {
1908 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1911 // Unknown messages:
1912 wire::Message::Unknown(type_id) if message.is_even() => {
1913 log_debug!(logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1914 return Err(PeerHandleError { }.into());
1916 wire::Message::Unknown(type_id) => {
1917 log_trace!(logger, "Received unknown odd message of type {}, ignoring", type_id);
1919 wire::Message::Custom(custom) => {
1920 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1926 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>) {
1928 wire::Message::ChannelAnnouncement(ref msg) => {
1929 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1930 let encoded_msg = encode_msg!(msg);
1932 for (_, peer_mutex) in peers.iter() {
1933 let mut peer = peer_mutex.lock().unwrap();
1934 if !peer.handshake_complete() ||
1935 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1938 debug_assert!(peer.their_node_id.is_some());
1939 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1940 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1941 if peer.buffer_full_drop_gossip_broadcast() {
1942 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1945 if let Some((_, their_node_id)) = peer.their_node_id {
1946 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1950 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1953 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1956 wire::Message::NodeAnnouncement(ref msg) => {
1957 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1958 let encoded_msg = encode_msg!(msg);
1960 for (_, peer_mutex) in peers.iter() {
1961 let mut peer = peer_mutex.lock().unwrap();
1962 if !peer.handshake_complete() ||
1963 !peer.should_forward_node_announcement(msg.contents.node_id) {
1966 debug_assert!(peer.their_node_id.is_some());
1967 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1968 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1969 if peer.buffer_full_drop_gossip_broadcast() {
1970 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1973 if let Some((_, their_node_id)) = peer.their_node_id {
1974 if their_node_id == msg.contents.node_id {
1978 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1981 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1984 wire::Message::ChannelUpdate(ref msg) => {
1985 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1986 let encoded_msg = encode_msg!(msg);
1988 for (_, peer_mutex) in peers.iter() {
1989 let mut peer = peer_mutex.lock().unwrap();
1990 if !peer.handshake_complete() ||
1991 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1994 debug_assert!(peer.their_node_id.is_some());
1995 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1996 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1997 if peer.buffer_full_drop_gossip_broadcast() {
1998 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
2001 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
2004 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
2007 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
2011 /// Checks for any events generated by our handlers and processes them. Includes sending most
2012 /// response messages as well as messages generated by calls to handler functions directly (eg
2013 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
2015 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2018 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
2019 /// or one of the other clients provided in our language bindings.
2021 /// Note that if there are any other calls to this function waiting on lock(s) this may return
2022 /// without doing any work. All available events that need handling will be handled before the
2023 /// other calls return.
2025 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2026 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
2027 /// [`send_data`]: SocketDescriptor::send_data
2028 pub fn process_events(&self) {
2029 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
2030 // If we're not the first event processor to get here, just return early, the increment
2031 // we just did will be treated as "go around again" at the end.
2036 self.update_gossip_backlogged();
2037 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2039 let mut peers_to_disconnect = new_hash_map();
2042 let peers_lock = self.peers.read().unwrap();
2044 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
2045 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
2047 let peers = &*peers_lock;
2048 macro_rules! get_peer_for_forwarding {
2049 ($node_id: expr) => {
2051 if peers_to_disconnect.get($node_id).is_some() {
2052 // If we've "disconnected" this peer, do not send to it.
2055 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
2056 match descriptor_opt {
2057 Some(descriptor) => match peers.get(&descriptor) {
2058 Some(peer_mutex) => {
2059 let peer_lock = peer_mutex.lock().unwrap();
2060 if !peer_lock.handshake_complete() {
2066 debug_assert!(false, "Inconsistent peers set state!");
2077 for event in events_generated.drain(..) {
2079 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
2080 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id)), "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
2081 log_pubkey!(node_id),
2082 &msg.common_fields.temporary_channel_id);
2083 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2085 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
2086 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id)), "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
2087 log_pubkey!(node_id),
2088 &msg.common_fields.temporary_channel_id);
2089 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2091 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
2092 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id)), "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
2093 log_pubkey!(node_id),
2094 &msg.common_fields.temporary_channel_id);
2095 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2097 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
2098 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id)), "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}",
2099 log_pubkey!(node_id),
2100 &msg.common_fields.temporary_channel_id);
2101 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2103 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
2104 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
2105 log_pubkey!(node_id),
2106 &msg.temporary_channel_id,
2107 ChannelId::v1_from_funding_txid(msg.funding_txid.as_byte_array(), msg.funding_output_index));
2108 // TODO: If the peer is gone we should generate a DiscardFunding event
2109 // indicating to the wallet that they should just throw away this funding transaction
2110 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2112 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
2113 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
2114 log_pubkey!(node_id),
2116 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2118 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
2119 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReady event in peer_handler for node {} for channel {}",
2120 log_pubkey!(node_id),
2122 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2124 MessageSendEvent::SendStfu { ref node_id, ref msg} => {
2125 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2126 log_debug!(logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
2127 log_pubkey!(node_id),
2129 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2131 MessageSendEvent::SendSplice { ref node_id, ref msg} => {
2132 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2133 log_debug!(logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
2134 log_pubkey!(node_id),
2136 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2138 MessageSendEvent::SendSpliceAck { ref node_id, ref msg} => {
2139 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2140 log_debug!(logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}",
2141 log_pubkey!(node_id),
2143 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2145 MessageSendEvent::SendSpliceLocked { ref node_id, ref msg} => {
2146 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2147 log_debug!(logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}",
2148 log_pubkey!(node_id),
2150 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2152 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
2153 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
2154 log_pubkey!(node_id),
2156 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2158 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
2159 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddOutput 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::SendTxRemoveInput { ref node_id, ref msg } => {
2165 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
2166 log_pubkey!(node_id),
2168 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2170 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
2171 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
2172 log_pubkey!(node_id),
2174 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2176 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
2177 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxComplete event in peer_handler for node {} for channel {}",
2178 log_pubkey!(node_id),
2180 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2182 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
2183 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
2184 log_pubkey!(node_id),
2186 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2188 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
2189 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
2190 log_pubkey!(node_id),
2192 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2194 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2195 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2196 log_pubkey!(node_id),
2198 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2200 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2201 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2202 log_pubkey!(node_id),
2204 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2206 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2207 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2208 log_pubkey!(node_id),
2210 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2212 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 } } => {
2213 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(commitment_signed.channel_id)), "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
2214 log_pubkey!(node_id),
2215 update_add_htlcs.len(),
2216 update_fulfill_htlcs.len(),
2217 update_fail_htlcs.len(),
2218 &commitment_signed.channel_id);
2219 let mut peer = get_peer_for_forwarding!(node_id);
2220 for msg in update_add_htlcs {
2221 self.enqueue_message(&mut *peer, msg);
2223 for msg in update_fulfill_htlcs {
2224 self.enqueue_message(&mut *peer, msg);
2226 for msg in update_fail_htlcs {
2227 self.enqueue_message(&mut *peer, msg);
2229 for msg in update_fail_malformed_htlcs {
2230 self.enqueue_message(&mut *peer, msg);
2232 if let &Some(ref msg) = update_fee {
2233 self.enqueue_message(&mut *peer, msg);
2235 self.enqueue_message(&mut *peer, commitment_signed);
2237 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2238 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2239 log_pubkey!(node_id),
2241 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2243 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2244 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2245 log_pubkey!(node_id),
2247 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2249 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2250 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling Shutdown event in peer_handler for node {} for channel {}",
2251 log_pubkey!(node_id),
2253 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2255 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2256 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2257 log_pubkey!(node_id),
2259 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2261 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2262 log_debug!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2263 log_pubkey!(node_id),
2264 msg.contents.short_channel_id);
2265 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2266 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2268 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2269 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2270 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2271 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2272 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2275 if let Some(msg) = update_msg {
2276 match self.message_handler.route_handler.handle_channel_update(&msg) {
2277 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2278 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2283 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2284 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents);
2285 match self.message_handler.route_handler.handle_channel_update(&msg) {
2286 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2287 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2291 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2292 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2293 match self.message_handler.route_handler.handle_node_announcement(&msg) {
2294 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2295 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2299 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2300 log_trace!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2301 log_pubkey!(node_id), msg.contents.short_channel_id);
2302 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2304 MessageSendEvent::HandleError { node_id, action } => {
2305 let logger = WithContext::from(&self.logger, Some(node_id), None);
2307 msgs::ErrorAction::DisconnectPeer { msg } => {
2308 if let Some(msg) = msg.as_ref() {
2309 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2310 log_pubkey!(node_id), msg.data);
2312 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2313 log_pubkey!(node_id));
2315 // We do not have the peers write lock, so we just store that we're
2316 // about to disconnect the peer and do it after we finish
2317 // processing most messages.
2318 let msg = msg.map(|msg| wire::Message::<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2319 peers_to_disconnect.insert(node_id, msg);
2321 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2322 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2323 log_pubkey!(node_id), msg.data);
2324 // We do not have the peers write lock, so we just store that we're
2325 // about to disconnect the peer and do it after we finish
2326 // processing most messages.
2327 peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2329 msgs::ErrorAction::IgnoreAndLog(level) => {
2330 log_given_level!(logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2332 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2333 msgs::ErrorAction::IgnoreError => {
2334 log_debug!(logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2336 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2337 log_trace!(logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2338 log_pubkey!(node_id),
2340 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2342 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2343 log_given_level!(logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2344 log_pubkey!(node_id),
2346 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2350 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2351 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2353 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2354 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2356 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2357 log_gossip!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
2358 log_pubkey!(node_id),
2359 msg.short_channel_ids.len(),
2361 msg.number_of_blocks,
2363 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2365 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2366 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2371 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2372 if peers_to_disconnect.get(&node_id).is_some() { continue; }
2373 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2376 for (descriptor, peer_mutex) in peers.iter() {
2377 let mut peer = peer_mutex.lock().unwrap();
2378 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2379 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2382 if !peers_to_disconnect.is_empty() {
2383 let mut peers_lock = self.peers.write().unwrap();
2384 let peers = &mut *peers_lock;
2385 for (node_id, msg) in peers_to_disconnect.drain() {
2386 // Note that since we are holding the peers *write* lock we can
2387 // remove from node_id_to_descriptor immediately (as no other
2388 // thread can be holding the peer lock if we have the global write
2391 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2392 if let Some(mut descriptor) = descriptor_opt {
2393 if let Some(peer_mutex) = peers.remove(&descriptor) {
2394 let mut peer = peer_mutex.lock().unwrap();
2395 if let Some(msg) = msg {
2396 self.enqueue_message(&mut *peer, &msg);
2397 // This isn't guaranteed to work, but if there is enough free
2398 // room in the send buffer, put the error message there...
2399 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2401 self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2402 } else { debug_assert!(false, "Missing connection for peer"); }
2407 if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2408 // If another thread incremented the state while we were running we should go
2409 // around again, but only once.
2410 self.event_processing_state.store(1, Ordering::Release);
2417 /// Indicates that the given socket descriptor's connection is now closed.
2418 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2419 self.disconnect_event_internal(descriptor);
2422 fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2423 if !peer.handshake_complete() {
2424 log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2425 descriptor.disconnect_socket();
2429 debug_assert!(peer.their_node_id.is_some());
2430 if let Some((node_id, _)) = peer.their_node_id {
2431 log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Disconnecting peer with id {} due to {}", node_id, reason);
2432 self.message_handler.chan_handler.peer_disconnected(&node_id);
2433 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2435 descriptor.disconnect_socket();
2438 fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2439 let mut peers = self.peers.write().unwrap();
2440 let peer_option = peers.remove(descriptor);
2443 // This is most likely a simple race condition where the user found that the socket
2444 // was disconnected, then we told the user to `disconnect_socket()`, then they
2445 // called this method. Either way we're disconnected, return.
2447 Some(peer_lock) => {
2448 let peer = peer_lock.lock().unwrap();
2449 if let Some((node_id, _)) = peer.their_node_id {
2450 log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Handling disconnection of peer {}", log_pubkey!(node_id));
2451 let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2452 debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2453 if !peer.handshake_complete() { return; }
2454 self.message_handler.chan_handler.peer_disconnected(&node_id);
2455 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2461 /// Disconnect a peer given its node id.
2463 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2464 /// peer. Thus, be very careful about reentrancy issues.
2466 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2467 pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2468 let mut peers_lock = self.peers.write().unwrap();
2469 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2470 let peer_opt = peers_lock.remove(&descriptor);
2471 if let Some(peer_mutex) = peer_opt {
2472 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2473 } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2477 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2478 /// an indication that TCP sockets have stalled even if we weren't around to time them out
2479 /// using regular ping/pongs.
2480 pub fn disconnect_all_peers(&self) {
2481 let mut peers_lock = self.peers.write().unwrap();
2482 self.node_id_to_descriptor.lock().unwrap().clear();
2483 let peers = &mut *peers_lock;
2484 for (descriptor, peer_mutex) in peers.drain() {
2485 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2489 /// This is called when we're blocked on sending additional gossip messages until we receive a
2490 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2491 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2492 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2493 if peer.awaiting_pong_timer_tick_intervals == 0 {
2494 peer.awaiting_pong_timer_tick_intervals = -1;
2495 let ping = msgs::Ping {
2499 self.enqueue_message(peer, &ping);
2503 /// Send pings to each peer and disconnect those which did not respond to the last round of
2506 /// This may be called on any timescale you want, however, roughly once every ten seconds is
2507 /// preferred. The call rate determines both how often we send a ping to our peers and how much
2508 /// time they have to respond before we disconnect them.
2510 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2513 /// [`send_data`]: SocketDescriptor::send_data
2514 pub fn timer_tick_occurred(&self) {
2515 let mut descriptors_needing_disconnect = Vec::new();
2517 let peers_lock = self.peers.read().unwrap();
2519 self.update_gossip_backlogged();
2520 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2522 for (descriptor, peer_mutex) in peers_lock.iter() {
2523 let mut peer = peer_mutex.lock().unwrap();
2524 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2526 if !peer.handshake_complete() {
2527 // The peer needs to complete its handshake before we can exchange messages. We
2528 // give peers one timer tick to complete handshake, reusing
2529 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2530 // for handshake completion.
2531 if peer.awaiting_pong_timer_tick_intervals != 0 {
2532 descriptors_needing_disconnect.push(descriptor.clone());
2534 peer.awaiting_pong_timer_tick_intervals = 1;
2538 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2539 debug_assert!(peer.their_node_id.is_some());
2541 loop { // Used as a `goto` to skip writing a Ping message.
2542 if peer.awaiting_pong_timer_tick_intervals == -1 {
2543 // Magic value set in `maybe_send_extra_ping`.
2544 peer.awaiting_pong_timer_tick_intervals = 1;
2545 peer.received_message_since_timer_tick = false;
2549 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2550 || peer.awaiting_pong_timer_tick_intervals as u64 >
2551 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2553 descriptors_needing_disconnect.push(descriptor.clone());
2556 peer.received_message_since_timer_tick = false;
2558 if peer.awaiting_pong_timer_tick_intervals > 0 {
2559 peer.awaiting_pong_timer_tick_intervals += 1;
2563 peer.awaiting_pong_timer_tick_intervals = 1;
2564 let ping = msgs::Ping {
2568 self.enqueue_message(&mut *peer, &ping);
2571 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2575 if !descriptors_needing_disconnect.is_empty() {
2577 let mut peers_lock = self.peers.write().unwrap();
2578 for descriptor in descriptors_needing_disconnect {
2579 if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2580 let peer = peer_mutex.lock().unwrap();
2581 if let Some((node_id, _)) = peer.their_node_id {
2582 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2584 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2592 // Messages of up to 64KB should never end up more than half full with addresses, as that would
2593 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2594 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2596 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (SocketAddress::MAX_LEN as u32 + 1) / 2;
2598 // ...by failing to compile if the number of addresses that would be half of a message is
2599 // smaller than 100:
2600 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2602 /// Generates a signed node_announcement from the given arguments, sending it to all connected
2603 /// peers. Note that peers will likely ignore this message unless we have at least one public
2604 /// channel which has at least six confirmations on-chain.
2606 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2607 /// node to humans. They carry no in-protocol meaning.
2609 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2610 /// accepts incoming connections. These will be included in the node_announcement, publicly
2611 /// tying these addresses together and to this node. If you wish to preserve user privacy,
2612 /// addresses should likely contain only Tor Onion addresses.
2614 /// Panics if `addresses` is absurdly large (more than 100).
2616 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2617 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<SocketAddress>) {
2618 if addresses.len() > 100 {
2619 panic!("More than half the message size was taken up by public addresses!");
2622 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2623 // addresses be sorted for future compatibility.
2624 addresses.sort_by_key(|addr| addr.get_id());
2626 let features = self.message_handler.chan_handler.provided_node_features()
2627 | self.message_handler.route_handler.provided_node_features()
2628 | self.message_handler.onion_message_handler.provided_node_features()
2629 | self.message_handler.custom_message_handler.provided_node_features();
2630 let announcement = msgs::UnsignedNodeAnnouncement {
2632 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2633 node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2635 alias: NodeAlias(alias),
2637 excess_address_data: Vec::new(),
2638 excess_data: Vec::new(),
2640 let node_announce_sig = match self.node_signer.sign_gossip_message(
2641 msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2645 log_error!(self.logger, "Failed to generate signature for node_announcement");
2650 let msg = msgs::NodeAnnouncement {
2651 signature: node_announce_sig,
2652 contents: announcement
2655 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2656 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2657 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2661 fn is_gossip_msg(type_id: u16) -> bool {
2663 msgs::ChannelAnnouncement::TYPE |
2664 msgs::ChannelUpdate::TYPE |
2665 msgs::NodeAnnouncement::TYPE |
2666 msgs::QueryChannelRange::TYPE |
2667 msgs::ReplyChannelRange::TYPE |
2668 msgs::QueryShortChannelIds::TYPE |
2669 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2676 use crate::sign::{NodeSigner, Recipient};
2679 use crate::ln::ChannelId;
2680 use crate::ln::features::{InitFeatures, NodeFeatures};
2681 use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2682 use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses, ErroringMessageHandler, MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER};
2683 use crate::ln::{msgs, wire};
2684 use crate::ln::msgs::{LightningError, SocketAddress};
2685 use crate::util::test_utils;
2687 use bitcoin::Network;
2688 use bitcoin::blockdata::constants::ChainHash;
2689 use bitcoin::secp256k1::{PublicKey, SecretKey};
2691 use crate::sync::{Arc, Mutex};
2692 use core::convert::Infallible;
2693 use core::sync::atomic::{AtomicBool, Ordering};
2695 #[allow(unused_imports)]
2696 use crate::prelude::*;
2699 struct FileDescriptor {
2701 outbound_data: Arc<Mutex<Vec<u8>>>,
2702 disconnect: Arc<AtomicBool>,
2704 impl PartialEq for FileDescriptor {
2705 fn eq(&self, other: &Self) -> bool {
2709 impl Eq for FileDescriptor { }
2710 impl core::hash::Hash for FileDescriptor {
2711 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2712 self.fd.hash(hasher)
2716 impl SocketDescriptor for FileDescriptor {
2717 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2718 self.outbound_data.lock().unwrap().extend_from_slice(data);
2722 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2725 struct PeerManagerCfg {
2726 chan_handler: test_utils::TestChannelMessageHandler,
2727 routing_handler: test_utils::TestRoutingMessageHandler,
2728 custom_handler: TestCustomMessageHandler,
2729 logger: test_utils::TestLogger,
2730 node_signer: test_utils::TestNodeSigner,
2733 struct TestCustomMessageHandler {
2734 features: InitFeatures,
2737 impl wire::CustomMessageReader for TestCustomMessageHandler {
2738 type CustomMessage = Infallible;
2739 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2744 impl CustomMessageHandler for TestCustomMessageHandler {
2745 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2749 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2751 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2753 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2754 self.features.clone()
2758 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2759 let mut cfgs = Vec::new();
2760 for i in 0..peer_count {
2761 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2763 let mut feature_bits = vec![0u8; 33];
2764 feature_bits[32] = 0b00000001;
2765 InitFeatures::from_le_bytes(feature_bits)
2769 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2770 logger: test_utils::TestLogger::new(),
2771 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2772 custom_handler: TestCustomMessageHandler { features },
2773 node_signer: test_utils::TestNodeSigner::new(node_secret),
2781 fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2782 let mut cfgs = Vec::new();
2783 for i in 0..peer_count {
2784 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2786 let mut feature_bits = vec![0u8; 33 + i + 1];
2787 feature_bits[33 + i] = 0b00000001;
2788 InitFeatures::from_le_bytes(feature_bits)
2792 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2793 logger: test_utils::TestLogger::new(),
2794 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2795 custom_handler: TestCustomMessageHandler { features },
2796 node_signer: test_utils::TestNodeSigner::new(node_secret),
2804 fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2805 let mut cfgs = Vec::new();
2806 for i in 0..peer_count {
2807 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2808 let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2809 let network = ChainHash::from(&[i as u8; 32]);
2812 chan_handler: test_utils::TestChannelMessageHandler::new(network),
2813 logger: test_utils::TestLogger::new(),
2814 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2815 custom_handler: TestCustomMessageHandler { features },
2816 node_signer: test_utils::TestNodeSigner::new(node_secret),
2824 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>> {
2825 let mut peers = Vec::new();
2826 for i in 0..peer_count {
2827 let ephemeral_bytes = [i as u8; 32];
2828 let msg_handler = MessageHandler {
2829 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2830 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2832 let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2839 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) {
2840 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2841 let mut fd_a = FileDescriptor {
2842 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2843 disconnect: Arc::new(AtomicBool::new(false)),
2845 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2846 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2847 let features_a = peer_a.init_features(&id_b);
2848 let features_b = peer_b.init_features(&id_a);
2849 let mut fd_b = FileDescriptor {
2850 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2851 disconnect: Arc::new(AtomicBool::new(false)),
2853 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2854 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2855 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2856 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2857 peer_a.process_events();
2859 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2860 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2862 peer_b.process_events();
2863 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2864 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2866 peer_a.process_events();
2867 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2868 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2870 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().counterparty_node_id, id_b);
2871 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().socket_address, Some(addr_b));
2872 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().init_features, features_b);
2873 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().counterparty_node_id, id_a);
2874 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().socket_address, Some(addr_a));
2875 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().init_features, features_a);
2876 (fd_a.clone(), fd_b.clone())
2880 #[cfg(feature = "std")]
2881 fn fuzz_threaded_connections() {
2882 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2883 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2884 // with our internal map consistency, and is a generally good smoke test of disconnection.
2885 let cfgs = Arc::new(create_peermgr_cfgs(2));
2886 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2887 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2889 let start_time = std::time::Instant::now();
2890 macro_rules! spawn_thread { ($id: expr) => { {
2891 let peers = Arc::clone(&peers);
2892 let cfgs = Arc::clone(&cfgs);
2893 std::thread::spawn(move || {
2895 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2896 let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2897 let mut fd_a = FileDescriptor {
2898 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2899 disconnect: Arc::new(AtomicBool::new(false)),
2901 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2902 let mut fd_b = FileDescriptor {
2903 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2904 disconnect: Arc::new(AtomicBool::new(false)),
2906 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2907 let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2908 peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2909 if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2911 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2912 peers[0].process_events();
2913 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2914 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2915 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2917 peers[1].process_events();
2918 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2919 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2920 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2922 cfgs[0].chan_handler.pending_events.lock().unwrap()
2923 .push(crate::events::MessageSendEvent::SendShutdown {
2924 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2925 msg: msgs::Shutdown {
2926 channel_id: ChannelId::new_zero(),
2927 scriptpubkey: bitcoin::ScriptBuf::new(),
2930 cfgs[1].chan_handler.pending_events.lock().unwrap()
2931 .push(crate::events::MessageSendEvent::SendShutdown {
2932 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2933 msg: msgs::Shutdown {
2934 channel_id: ChannelId::new_zero(),
2935 scriptpubkey: bitcoin::ScriptBuf::new(),
2940 peers[0].timer_tick_occurred();
2941 peers[1].timer_tick_occurred();
2945 peers[0].socket_disconnected(&fd_a);
2946 peers[1].socket_disconnected(&fd_b);
2948 std::thread::sleep(std::time::Duration::from_micros(1));
2952 let thrd_a = spawn_thread!(1);
2953 let thrd_b = spawn_thread!(2);
2955 thrd_a.join().unwrap();
2956 thrd_b.join().unwrap();
2960 fn test_feature_incompatible_peers() {
2961 let cfgs = create_peermgr_cfgs(2);
2962 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2964 let peers = create_network(2, &cfgs);
2965 let incompatible_peers = create_network(2, &incompatible_cfgs);
2966 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2967 for (peer_a, peer_b) in peer_pairs.iter() {
2968 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2969 let mut fd_a = FileDescriptor {
2970 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2971 disconnect: Arc::new(AtomicBool::new(false)),
2973 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2974 let mut fd_b = FileDescriptor {
2975 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2976 disconnect: Arc::new(AtomicBool::new(false)),
2978 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2979 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2980 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2981 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2982 peer_a.process_events();
2984 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2985 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2987 peer_b.process_events();
2988 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2990 // Should fail because of unknown required features
2991 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2996 fn test_chain_incompatible_peers() {
2997 let cfgs = create_peermgr_cfgs(2);
2998 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
3000 let peers = create_network(2, &cfgs);
3001 let incompatible_peers = create_network(2, &incompatible_cfgs);
3002 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
3003 for (peer_a, peer_b) in peer_pairs.iter() {
3004 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
3005 let mut fd_a = FileDescriptor {
3006 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3007 disconnect: Arc::new(AtomicBool::new(false)),
3009 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
3010 let mut fd_b = FileDescriptor {
3011 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3012 disconnect: Arc::new(AtomicBool::new(false)),
3014 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
3015 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
3016 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
3017 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
3018 peer_a.process_events();
3020 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3021 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
3023 peer_b.process_events();
3024 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3026 // Should fail because of incompatible chains
3027 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
3032 fn test_disconnect_peer() {
3033 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3034 // push a DisconnectPeer event to remove the node flagged by id
3035 let cfgs = create_peermgr_cfgs(2);
3036 let peers = create_network(2, &cfgs);
3037 establish_connection(&peers[0], &peers[1]);
3038 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3040 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
3041 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
3043 action: msgs::ErrorAction::DisconnectPeer { msg: None },
3046 peers[0].process_events();
3047 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3051 fn test_send_simple_msg() {
3052 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3053 // push a message from one peer to another.
3054 let cfgs = create_peermgr_cfgs(2);
3055 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3056 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3057 let mut peers = create_network(2, &cfgs);
3058 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3059 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3061 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
3063 let msg = msgs::Shutdown { channel_id: ChannelId::from_bytes([42; 32]), scriptpubkey: bitcoin::ScriptBuf::new() };
3064 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
3065 node_id: their_id, msg: msg.clone()
3067 peers[0].message_handler.chan_handler = &a_chan_handler;
3069 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
3070 peers[1].message_handler.chan_handler = &b_chan_handler;
3072 peers[0].process_events();
3074 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3075 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3079 fn test_non_init_first_msg() {
3080 // Simple test of the first message received over a connection being something other than
3081 // Init. This results in an immediate disconnection, which previously included a spurious
3082 // peer_disconnected event handed to event handlers (which would panic in
3083 // `TestChannelMessageHandler` here).
3084 let cfgs = create_peermgr_cfgs(2);
3085 let peers = create_network(2, &cfgs);
3087 let mut fd_dup = FileDescriptor {
3088 fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
3089 disconnect: Arc::new(AtomicBool::new(false)),
3091 let addr_dup = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1003};
3092 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
3093 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
3095 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
3096 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
3097 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
3098 peers[0].process_events();
3100 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
3101 let (act_three, _) =
3102 dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
3103 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
3105 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
3106 let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg);
3107 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
3111 fn test_disconnect_all_peer() {
3112 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3113 // then calls disconnect_all_peers
3114 let cfgs = create_peermgr_cfgs(2);
3115 let peers = create_network(2, &cfgs);
3116 establish_connection(&peers[0], &peers[1]);
3117 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3119 peers[0].disconnect_all_peers();
3120 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3124 fn test_timer_tick_occurred() {
3125 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
3126 let cfgs = create_peermgr_cfgs(2);
3127 let peers = create_network(2, &cfgs);
3128 establish_connection(&peers[0], &peers[1]);
3129 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3131 // peers[0] awaiting_pong is set to true, but the Peer is still connected
3132 peers[0].timer_tick_occurred();
3133 peers[0].process_events();
3134 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3136 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
3137 peers[0].timer_tick_occurred();
3138 peers[0].process_events();
3139 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3143 fn test_do_attempt_write_data() {
3144 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
3145 let cfgs = create_peermgr_cfgs(2);
3146 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3147 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3148 let peers = create_network(2, &cfgs);
3150 // By calling establish_connect, we trigger do_attempt_write_data between
3151 // the peers. Previously this function would mistakenly enter an infinite loop
3152 // when there were more channel messages available than could fit into a peer's
3153 // buffer. This issue would now be detected by this test (because we use custom
3154 // RoutingMessageHandlers that intentionally return more channel messages
3155 // than can fit into a peer's buffer).
3156 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3158 // Make each peer to read the messages that the other peer just wrote to them. Note that
3159 // due to the max-message-before-ping limits this may take a few iterations to complete.
3160 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
3161 peers[1].process_events();
3162 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3163 assert!(!a_read_data.is_empty());
3165 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
3166 peers[0].process_events();
3168 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3169 assert!(!b_read_data.is_empty());
3170 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
3172 peers[0].process_events();
3173 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
3176 // Check that each peer has received the expected number of channel updates and channel
3178 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3179 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3180 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3181 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3185 fn test_handshake_timeout() {
3186 // Tests that we time out a peer still waiting on handshake completion after a full timer
3188 let cfgs = create_peermgr_cfgs(2);
3189 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3190 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3191 let peers = create_network(2, &cfgs);
3193 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
3194 let mut fd_a = FileDescriptor {
3195 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3196 disconnect: Arc::new(AtomicBool::new(false)),
3198 let mut fd_b = FileDescriptor {
3199 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3200 disconnect: Arc::new(AtomicBool::new(false)),
3202 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3203 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3205 // If we get a single timer tick before completion, that's fine
3206 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3207 peers[0].timer_tick_occurred();
3208 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3210 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3211 peers[0].process_events();
3212 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3213 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3214 peers[1].process_events();
3216 // ...but if we get a second timer tick, we should disconnect the peer
3217 peers[0].timer_tick_occurred();
3218 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3220 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3221 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3225 fn test_inbound_conn_handshake_complete_awaiting_pong() {
3226 // Test that we do not disconnect an outbound peer after the noise handshake completes due
3227 // to a pong timeout for a ping that was never sent if a timer tick fires after we send act
3228 // two of the noise handshake along with our init message but before we receive their init
3230 let logger = test_utils::TestLogger::new();
3231 let node_signer_a = test_utils::TestNodeSigner::new(SecretKey::from_slice(&[42; 32]).unwrap());
3232 let node_signer_b = test_utils::TestNodeSigner::new(SecretKey::from_slice(&[43; 32]).unwrap());
3233 let peer_a = PeerManager::new(MessageHandler {
3234 chan_handler: ErroringMessageHandler::new(),
3235 route_handler: IgnoringMessageHandler {},
3236 onion_message_handler: IgnoringMessageHandler {},
3237 custom_message_handler: IgnoringMessageHandler {},
3238 }, 0, &[0; 32], &logger, &node_signer_a);
3239 let peer_b = PeerManager::new(MessageHandler {
3240 chan_handler: ErroringMessageHandler::new(),
3241 route_handler: IgnoringMessageHandler {},
3242 onion_message_handler: IgnoringMessageHandler {},
3243 custom_message_handler: IgnoringMessageHandler {},
3244 }, 0, &[1; 32], &logger, &node_signer_b);
3246 let a_id = node_signer_a.get_node_id(Recipient::Node).unwrap();
3247 let mut fd_a = FileDescriptor {
3248 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3249 disconnect: Arc::new(AtomicBool::new(false)),
3251 let mut fd_b = FileDescriptor {
3252 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3253 disconnect: Arc::new(AtomicBool::new(false)),
3256 // Exchange messages with both peers until they both complete the init handshake.
3257 let act_one = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3258 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
3260 assert_eq!(peer_a.read_event(&mut fd_a, &act_one).unwrap(), false);
3261 peer_a.process_events();
3263 let act_two = fd_a.outbound_data.lock().unwrap().split_off(0);
3264 assert_eq!(peer_b.read_event(&mut fd_b, &act_two).unwrap(), false);
3265 peer_b.process_events();
3267 // Calling this here triggers the race on inbound connections.
3268 peer_b.timer_tick_occurred();
3270 let act_three_with_init_b = fd_b.outbound_data.lock().unwrap().split_off(0);
3271 assert!(!peer_a.peers.read().unwrap().get(&fd_a).unwrap().lock().unwrap().handshake_complete());
3272 assert_eq!(peer_a.read_event(&mut fd_a, &act_three_with_init_b).unwrap(), false);
3273 peer_a.process_events();
3274 assert!(peer_a.peers.read().unwrap().get(&fd_a).unwrap().lock().unwrap().handshake_complete());
3276 let init_a = fd_a.outbound_data.lock().unwrap().split_off(0);
3277 assert!(!init_a.is_empty());
3279 assert!(!peer_b.peers.read().unwrap().get(&fd_b).unwrap().lock().unwrap().handshake_complete());
3280 assert_eq!(peer_b.read_event(&mut fd_b, &init_a).unwrap(), false);
3281 peer_b.process_events();
3282 assert!(peer_b.peers.read().unwrap().get(&fd_b).unwrap().lock().unwrap().handshake_complete());
3284 // Make sure we're still connected.
3285 assert_eq!(peer_b.peers.read().unwrap().len(), 1);
3287 // B should send a ping on the first timer tick after `handshake_complete`.
3288 assert!(fd_b.outbound_data.lock().unwrap().split_off(0).is_empty());
3289 peer_b.timer_tick_occurred();
3290 peer_b.process_events();
3291 assert!(!fd_b.outbound_data.lock().unwrap().split_off(0).is_empty());
3293 let mut send_warning = || {
3295 let peers = peer_a.peers.read().unwrap();
3296 let mut peer_b = peers.get(&fd_a).unwrap().lock().unwrap();
3297 peer_a.enqueue_message(&mut peer_b, &msgs::WarningMessage {
3298 channel_id: ChannelId([0; 32]),
3299 data: "no disconnect plz".to_string(),
3302 peer_a.process_events();
3303 let msg = fd_a.outbound_data.lock().unwrap().split_off(0);
3304 assert!(!msg.is_empty());
3305 assert_eq!(peer_b.read_event(&mut fd_b, &msg).unwrap(), false);
3306 peer_b.process_events();
3309 // Fire more ticks until we reach the pong timeout. We send any message except pong to
3310 // pretend the connection is still alive.
3312 for _ in 0..MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER {
3313 peer_b.timer_tick_occurred();
3316 assert_eq!(peer_b.peers.read().unwrap().len(), 1);
3318 // One more tick should enforce the pong timeout.
3319 peer_b.timer_tick_occurred();
3320 assert_eq!(peer_b.peers.read().unwrap().len(), 0);
3324 fn test_filter_addresses(){
3325 // Tests the filter_addresses function.
3328 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 0, 0], port: 1000};
3329 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3330 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 255, 201], port: 1000};
3331 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3332 let ip_address = SocketAddress::TcpIpV4{addr: [10, 255, 255, 255], port: 1000};
3333 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3336 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 0, 0], port: 1000};
3337 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3338 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 255, 187], port: 1000};
3339 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3340 let ip_address = SocketAddress::TcpIpV4{addr: [0, 255, 255, 255], port: 1000};
3341 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3344 let ip_address = SocketAddress::TcpIpV4{addr: [100, 64, 0, 0], port: 1000};
3345 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3346 let ip_address = SocketAddress::TcpIpV4{addr: [100, 78, 255, 0], port: 1000};
3347 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3348 let ip_address = SocketAddress::TcpIpV4{addr: [100, 127, 255, 255], port: 1000};
3349 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3352 let ip_address = SocketAddress::TcpIpV4{addr: [127, 0, 0, 0], port: 1000};
3353 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3354 let ip_address = SocketAddress::TcpIpV4{addr: [127, 65, 73, 0], port: 1000};
3355 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3356 let ip_address = SocketAddress::TcpIpV4{addr: [127, 255, 255, 255], port: 1000};
3357 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3360 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 0, 0], port: 1000};
3361 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3362 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 221, 101], port: 1000};
3363 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3364 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 255, 255], port: 1000};
3365 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3368 let ip_address = SocketAddress::TcpIpV4{addr: [172, 16, 0, 0], port: 1000};
3369 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3370 let ip_address = SocketAddress::TcpIpV4{addr: [172, 27, 101, 23], port: 1000};
3371 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3372 let ip_address = SocketAddress::TcpIpV4{addr: [172, 31, 255, 255], port: 1000};
3373 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3376 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 0, 0], port: 1000};
3377 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3378 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 205, 159], port: 1000};
3379 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3380 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 255, 255], port: 1000};
3381 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3383 // For (192.88.99/24)
3384 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 0], port: 1000};
3385 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3386 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 140], port: 1000};
3387 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3388 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 255], port: 1000};
3389 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3391 // For other IPv4 addresses
3392 let ip_address = SocketAddress::TcpIpV4{addr: [188, 255, 99, 0], port: 1000};
3393 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3394 let ip_address = SocketAddress::TcpIpV4{addr: [123, 8, 129, 14], port: 1000};
3395 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3396 let ip_address = SocketAddress::TcpIpV4{addr: [2, 88, 9, 255], port: 1000};
3397 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3400 let ip_address = SocketAddress::TcpIpV6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3401 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3402 let ip_address = SocketAddress::TcpIpV6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3403 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3404 let ip_address = SocketAddress::TcpIpV6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3405 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3407 // For other IPv6 addresses
3408 let ip_address = SocketAddress::TcpIpV6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3409 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3410 let ip_address = SocketAddress::TcpIpV6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3411 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3412 let ip_address = SocketAddress::TcpIpV6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3413 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3416 assert_eq!(filter_addresses(None), None);
3420 #[cfg(feature = "std")]
3421 fn test_process_events_multithreaded() {
3422 use std::time::{Duration, Instant};
3423 // Test that `process_events` getting called on multiple threads doesn't generate too many
3425 // Each time `process_events` goes around the loop we call
3426 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3427 // Because the loop should go around once more after a call which fails to take the
3428 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3429 // should never observe there having been more than 2 loop iterations.
3430 // Further, because the last thread to exit will call `process_events` before returning, we
3431 // should always have at least one count at the end.
3432 let cfg = Arc::new(create_peermgr_cfgs(1));
3433 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3434 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3436 let exit_flag = Arc::new(AtomicBool::new(false));
3437 macro_rules! spawn_thread { () => { {
3438 let thread_cfg = Arc::clone(&cfg);
3439 let thread_peer = Arc::clone(&peer);
3440 let thread_exit = Arc::clone(&exit_flag);
3441 std::thread::spawn(move || {
3442 while !thread_exit.load(Ordering::Acquire) {
3443 thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3444 thread_peer.process_events();
3445 std::thread::sleep(Duration::from_micros(1));
3450 let thread_a = spawn_thread!();
3451 let thread_b = spawn_thread!();
3452 let thread_c = spawn_thread!();
3454 let start_time = Instant::now();
3455 while start_time.elapsed() < Duration::from_millis(100) {
3456 let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3458 std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3461 exit_flag.store(true, Ordering::Release);
3462 thread_a.join().unwrap();
3463 thread_b.join().unwrap();
3464 thread_c.join().unwrap();
3465 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);