1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Top level peer message handling and socket handling logic lives here.
12 //! Instead of actually servicing sockets ourselves we require that you implement the
13 //! SocketDescriptor interface and use that to receive actions which you should perform on the
14 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
15 //! call into the provided message handlers (probably a ChannelManager and P2PGossipSync) with
16 //! messages they should handle, and encoding/sending response messages.
18 use bitcoin::blockdata::constants::ChainHash;
19 use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
21 use crate::sign::{NodeSigner, Recipient};
22 use crate::events::{MessageSendEvent, MessageSendEventsProvider};
23 use crate::ln::types::ChannelId;
24 use crate::ln::features::{InitFeatures, NodeFeatures};
26 use crate::ln::msgs::{ChannelMessageHandler, 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, Responder, ResponseInstruction};
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 MessageSendEventsProvider for IgnoringMessageHandler {
101 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
103 impl RoutingMessageHandler for IgnoringMessageHandler {
104 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
105 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
106 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
107 fn get_next_channel_announcement(&self, _starting_point: u64) ->
108 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
109 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
110 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
111 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
112 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
113 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
114 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
115 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
116 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
117 let mut features = InitFeatures::empty();
118 features.set_gossip_queries_optional();
121 fn processing_queue_high(&self) -> bool { false }
124 impl OnionMessageHandler for IgnoringMessageHandler {
125 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
126 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
127 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
128 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
129 fn timer_tick_occurred(&self) {}
130 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
131 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
132 InitFeatures::empty()
136 impl OffersMessageHandler for IgnoringMessageHandler {
137 fn handle_message(&self, _message: OffersMessage, _responder: Option<Responder>) -> ResponseInstruction<OffersMessage> {
138 ResponseInstruction::NoResponse
141 impl CustomOnionMessageHandler for IgnoringMessageHandler {
142 type CustomMessage = Infallible;
143 fn handle_custom_message(&self, _message: Self::CustomMessage, _responder: Option<Responder>) -> ResponseInstruction<Self::CustomMessage> {
144 // Since we always return `None` in the read the handle method should never be called.
147 fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
150 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Infallible>> {
155 impl OnionMessageContents for Infallible {
156 fn tlv_type(&self) -> u64 { unreachable!(); }
157 fn msg_type(&self) -> &'static str { unreachable!(); }
160 impl Deref for IgnoringMessageHandler {
161 type Target = IgnoringMessageHandler;
162 fn deref(&self) -> &Self { self }
165 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
166 // method that takes self for it.
167 impl wire::Type for Infallible {
168 fn type_id(&self) -> u16 {
172 impl Writeable for Infallible {
173 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
178 impl wire::CustomMessageReader for IgnoringMessageHandler {
179 type CustomMessage = Infallible;
180 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
185 impl CustomMessageHandler for IgnoringMessageHandler {
186 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
187 // Since we always return `None` in the read the handle method should never be called.
191 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
193 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
195 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
196 InitFeatures::empty()
200 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
201 /// You can provide one of these as the route_handler in a MessageHandler.
202 pub struct ErroringMessageHandler {
203 message_queue: Mutex<Vec<MessageSendEvent>>
205 impl ErroringMessageHandler {
206 /// Constructs a new ErroringMessageHandler
207 pub fn new() -> Self {
208 Self { message_queue: Mutex::new(Vec::new()) }
210 fn push_error(&self, node_id: &PublicKey, channel_id: ChannelId) {
211 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
212 action: msgs::ErrorAction::SendErrorMessage {
213 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
215 node_id: node_id.clone(),
219 impl MessageSendEventsProvider for ErroringMessageHandler {
220 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
221 let mut res = Vec::new();
222 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
226 impl ChannelMessageHandler for ErroringMessageHandler {
227 // Any messages which are related to a specific channel generate an error message to let the
228 // peer know we don't care about channels.
229 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
230 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
232 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
233 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
235 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
236 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
238 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
239 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
241 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
242 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
244 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
245 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
247 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
248 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
250 fn handle_stfu(&self, their_node_id: &PublicKey, msg: &msgs::Stfu) {
251 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
254 fn handle_splice(&self, their_node_id: &PublicKey, msg: &msgs::Splice) {
255 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
258 fn handle_splice_ack(&self, their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
259 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
262 fn handle_splice_locked(&self, their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
263 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
265 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
266 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
268 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
269 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
271 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
272 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
274 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
275 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
277 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
278 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
280 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
281 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
283 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
284 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
286 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
287 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
289 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
290 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
292 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
293 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
294 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
295 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
296 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
297 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
298 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
299 // Set a number of features which various nodes may require to talk to us. It's totally
300 // reasonable to indicate we "support" all kinds of channel features...we just reject all
302 let mut features = InitFeatures::empty();
303 features.set_data_loss_protect_optional();
304 features.set_upfront_shutdown_script_optional();
305 features.set_variable_length_onion_optional();
306 features.set_static_remote_key_optional();
307 features.set_payment_secret_optional();
308 features.set_basic_mpp_optional();
309 features.set_wumbo_optional();
310 features.set_shutdown_any_segwit_optional();
311 features.set_channel_type_optional();
312 features.set_scid_privacy_optional();
313 features.set_zero_conf_optional();
314 features.set_route_blinding_optional();
318 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
319 // We don't enforce any chains upon peer connection for `ErroringMessageHandler` and leave it up
320 // to users of `ErroringMessageHandler` to make decisions on network compatiblility.
321 // There's not really any way to pull in specific networks here, and hardcoding can cause breakages.
325 fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
326 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
329 fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
330 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
333 fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
334 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
337 fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
338 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
341 fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
342 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
345 fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
346 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
349 fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &msgs::TxComplete) {
350 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
353 fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
354 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
357 fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
358 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
361 fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
362 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
365 fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &msgs::TxAbort) {
366 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
370 impl Deref for ErroringMessageHandler {
371 type Target = ErroringMessageHandler;
372 fn deref(&self) -> &Self { self }
375 /// Provides references to trait impls which handle different types of messages.
376 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref, CustomM: Deref> where
377 CM::Target: ChannelMessageHandler,
378 RM::Target: RoutingMessageHandler,
379 OM::Target: OnionMessageHandler,
380 CustomM::Target: CustomMessageHandler,
382 /// A message handler which handles messages specific to channels. Usually this is just a
383 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
385 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
386 pub chan_handler: CM,
387 /// A message handler which handles messages updating our knowledge of the network channel
388 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
390 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
391 pub route_handler: RM,
393 /// A message handler which handles onion messages. This should generally be an
394 /// [`OnionMessenger`], but can also be an [`IgnoringMessageHandler`].
396 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
397 pub onion_message_handler: OM,
399 /// A message handler which handles custom messages. The only LDK-provided implementation is
400 /// [`IgnoringMessageHandler`].
401 pub custom_message_handler: CustomM,
404 /// Provides an object which can be used to send data to and which uniquely identifies a connection
405 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
406 /// implement Hash to meet the PeerManager API.
408 /// For efficiency, [`Clone`] should be relatively cheap for this type.
410 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
411 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
412 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
413 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
414 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
415 /// to simply use another value which is guaranteed to be globally unique instead.
416 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
417 /// Attempts to send some data from the given slice to the peer.
419 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
420 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
421 /// called and further write attempts may occur until that time.
423 /// If the returned size is smaller than `data.len()`, a
424 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
425 /// written. Additionally, until a `send_data` event completes fully, no further
426 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
427 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
430 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
431 /// (indicating that read events should be paused to prevent DoS in the send buffer),
432 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
433 /// `resume_read` of false carries no meaning, and should not cause any action.
434 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
435 /// Disconnect the socket pointed to by this SocketDescriptor.
437 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
438 /// call (doing so is a noop).
439 fn disconnect_socket(&mut self);
442 /// Details of a connected peer as returned by [`PeerManager::list_peers`].
443 pub struct PeerDetails {
444 /// The node id of the peer.
446 /// For outbound connections, this [`PublicKey`] will be the same as the `their_node_id` parameter
447 /// passed in to [`PeerManager::new_outbound_connection`].
448 pub counterparty_node_id: PublicKey,
449 /// The socket address the peer provided in the initial handshake.
451 /// Will only be `Some` if an address had been previously provided to
452 /// [`PeerManager::new_outbound_connection`] or [`PeerManager::new_inbound_connection`].
453 pub socket_address: Option<SocketAddress>,
454 /// The features the peer provided in the initial handshake.
455 pub init_features: InitFeatures,
456 /// Indicates the direction of the peer connection.
458 /// Will be `true` for inbound connections, and `false` for outbound connections.
459 pub is_inbound_connection: bool,
462 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
463 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
466 pub struct PeerHandleError { }
467 impl fmt::Debug for PeerHandleError {
468 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
469 formatter.write_str("Peer Sent Invalid Data")
472 impl fmt::Display for PeerHandleError {
473 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
474 formatter.write_str("Peer Sent Invalid Data")
478 #[cfg(feature = "std")]
479 impl error::Error for PeerHandleError {
480 fn description(&self) -> &str {
481 "Peer Sent Invalid Data"
485 enum InitSyncTracker{
487 ChannelsSyncing(u64),
488 NodesSyncing(NodeId),
491 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
492 /// forwarding gossip messages to peers altogether.
493 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
495 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
496 /// we have fewer than this many messages in the outbound buffer again.
497 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
498 /// refilled as we send bytes.
499 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
500 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
502 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
504 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
505 /// the socket receive buffer before receiving the ping.
507 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
508 /// including any network delays, outbound traffic, or the same for messages from other peers.
510 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
511 /// per connected peer to respond to a ping, as long as they send us at least one message during
512 /// each tick, ensuring we aren't actually just disconnected.
513 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
516 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
517 /// two connected peers, assuming most LDK-running systems have at least two cores.
518 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
520 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
521 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
522 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
523 /// process before the next ping.
525 /// Note that we continue responding to other messages even after we've sent this many messages, so
526 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
527 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
528 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
531 channel_encryptor: PeerChannelEncryptor,
532 /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
533 /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
534 their_node_id: Option<(PublicKey, NodeId)>,
535 /// The features provided in the peer's [`msgs::Init`] message.
537 /// This is set only after we've processed the [`msgs::Init`] message and called relevant
538 /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
539 /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
541 their_features: Option<InitFeatures>,
542 their_socket_address: Option<SocketAddress>,
544 pending_outbound_buffer: VecDeque<Vec<u8>>,
545 pending_outbound_buffer_first_msg_offset: usize,
546 /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
547 /// prioritize channel messages over them.
549 /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
550 gossip_broadcast_buffer: VecDeque<MessageBuf>,
551 awaiting_write_event: bool,
553 pending_read_buffer: Vec<u8>,
554 pending_read_buffer_pos: usize,
555 pending_read_is_header: bool,
557 sync_status: InitSyncTracker,
559 msgs_sent_since_pong: usize,
560 awaiting_pong_timer_tick_intervals: i64,
561 received_message_since_timer_tick: bool,
562 sent_gossip_timestamp_filter: bool,
564 /// Indicates we've received a `channel_announcement` since the last time we had
565 /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
566 /// `channel_announcement` at all - we set this unconditionally but unset it every time we
567 /// check if we're gossip-processing-backlogged).
568 received_channel_announce_since_backlogged: bool,
570 inbound_connection: bool,
574 /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
575 /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
577 fn handshake_complete(&self) -> bool {
578 self.their_features.is_some()
581 /// Returns true if the channel announcements/updates for the given channel should be
582 /// forwarded to this peer.
583 /// If we are sending our routing table to this peer and we have not yet sent channel
584 /// announcements/updates for the given channel_id then we will send it when we get to that
585 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
586 /// sent the old versions, we should send the update, and so return true here.
587 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
588 if !self.handshake_complete() { return false; }
589 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
590 !self.sent_gossip_timestamp_filter {
593 match self.sync_status {
594 InitSyncTracker::NoSyncRequested => true,
595 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
596 InitSyncTracker::NodesSyncing(_) => true,
600 /// Similar to the above, but for node announcements indexed by node_id.
601 fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
602 if !self.handshake_complete() { return false; }
603 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
604 !self.sent_gossip_timestamp_filter {
607 match self.sync_status {
608 InitSyncTracker::NoSyncRequested => true,
609 InitSyncTracker::ChannelsSyncing(_) => false,
610 InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
614 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
615 /// buffer still has space and we don't need to pause reads to get some writes out.
616 fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
617 if !gossip_processing_backlogged {
618 self.received_channel_announce_since_backlogged = false;
620 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
621 (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
624 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
625 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
626 fn should_buffer_gossip_backfill(&self) -> bool {
627 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
628 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
629 && self.handshake_complete()
632 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
633 /// every time the peer's buffer may have been drained.
634 fn should_buffer_onion_message(&self) -> bool {
635 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
636 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
639 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
640 /// buffer. This is checked every time the peer's buffer may have been drained.
641 fn should_buffer_gossip_broadcast(&self) -> bool {
642 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
643 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
646 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
647 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
648 let total_outbound_buffered =
649 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
651 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
652 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
655 fn set_their_node_id(&mut self, node_id: PublicKey) {
656 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
660 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
661 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
662 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
663 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
664 /// issues such as overly long function definitions.
666 /// This is not exported to bindings users as type aliases aren't supported in most languages.
667 #[cfg(not(c_bindings))]
668 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<
670 Arc<SimpleArcChannelManager<M, T, F, L>>,
671 Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, C, Arc<L>>>,
672 Arc<SimpleArcOnionMessenger<M, T, F, L>>,
674 IgnoringMessageHandler,
678 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
679 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
680 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
681 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
682 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
683 /// helps with issues such as long function definitions.
685 /// This is not exported to bindings users as type aliases aren't supported in most languages.
686 #[cfg(not(c_bindings))]
687 pub type SimpleRefPeerManager<
688 'a, 'b, 'c, 'd, 'e, 'f, 'logger, 'h, 'i, 'j, 'graph, 'k, SD, M, T, F, C, L
691 &'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, M, T, F, L>,
692 &'f P2PGossipSync<&'graph NetworkGraph<&'logger L>, C, &'logger L>,
693 &'h SimpleRefOnionMessenger<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, 'j, 'k, M, T, F, L>,
695 IgnoringMessageHandler,
700 /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or
701 /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather
702 /// than the full set of bounds on [`PeerManager`] itself.
704 /// This is not exported to bindings users as general cover traits aren't useful in other
706 #[allow(missing_docs)]
707 pub trait APeerManager {
708 type Descriptor: SocketDescriptor;
709 type CMT: ChannelMessageHandler + ?Sized;
710 type CM: Deref<Target=Self::CMT>;
711 type RMT: RoutingMessageHandler + ?Sized;
712 type RM: Deref<Target=Self::RMT>;
713 type OMT: OnionMessageHandler + ?Sized;
714 type OM: Deref<Target=Self::OMT>;
715 type LT: Logger + ?Sized;
716 type L: Deref<Target=Self::LT>;
717 type CMHT: CustomMessageHandler + ?Sized;
718 type CMH: Deref<Target=Self::CMHT>;
719 type NST: NodeSigner + ?Sized;
720 type NS: Deref<Target=Self::NST>;
721 /// Gets a reference to the underlying [`PeerManager`].
722 fn as_ref(&self) -> &PeerManager<Self::Descriptor, Self::CM, Self::RM, Self::OM, Self::L, Self::CMH, Self::NS>;
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 }
750 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
751 /// socket events into messages which it passes on to its [`MessageHandler`].
753 /// Locks are taken internally, so you must never assume that reentrancy from a
754 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
756 /// Calls to [`read_event`] will decode relevant messages and pass them to the
757 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
758 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
759 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
760 /// calls only after previous ones have returned.
762 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
763 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
764 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
765 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
766 /// you're using lightning-net-tokio.
768 /// [`read_event`]: PeerManager::read_event
769 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
770 CM::Target: ChannelMessageHandler,
771 RM::Target: RoutingMessageHandler,
772 OM::Target: OnionMessageHandler,
774 CMH::Target: CustomMessageHandler,
775 NS::Target: NodeSigner {
776 message_handler: MessageHandler<CM, RM, OM, CMH>,
777 /// Connection state for each connected peer - we have an outer read-write lock which is taken
778 /// as read while we're doing processing for a peer and taken write when a peer is being added
781 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
782 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
783 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
784 /// the `MessageHandler`s for a given peer is already guaranteed.
785 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
786 /// Only add to this set when noise completes.
787 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
788 /// lock held. Entries may be added with only the `peers` read lock held (though the
789 /// `Descriptor` value must already exist in `peers`).
790 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
791 /// We can only have one thread processing events at once, but if a second call to
792 /// `process_events` happens while a first call is in progress, one of the two calls needs to
793 /// start from the top to ensure any new messages are also handled.
795 /// Because the event handler calls into user code which may block, we don't want to block a
796 /// second thread waiting for another thread to handle events which is then blocked on user
797 /// code, so we store an atomic counter here:
798 /// * 0 indicates no event processor is running
799 /// * 1 indicates an event processor is running
800 /// * > 1 indicates an event processor is running but needs to start again from the top once
801 /// it finishes as another thread tried to start processing events but returned early.
802 event_processing_state: AtomicI32,
804 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
805 /// value increases strictly since we don't assume access to a time source.
806 last_node_announcement_serial: AtomicU32,
808 ephemeral_key_midstate: Sha256Engine,
810 peer_counter: AtomicCounter,
812 gossip_processing_backlogged: AtomicBool,
813 gossip_processing_backlog_lifted: AtomicBool,
818 secp_ctx: Secp256k1<secp256k1::SignOnly>
821 enum MessageHandlingError {
822 PeerHandleError(PeerHandleError),
823 LightningError(LightningError),
826 impl From<PeerHandleError> for MessageHandlingError {
827 fn from(error: PeerHandleError) -> Self {
828 MessageHandlingError::PeerHandleError(error)
832 impl From<LightningError> for MessageHandlingError {
833 fn from(error: LightningError) -> Self {
834 MessageHandlingError::LightningError(error)
838 macro_rules! encode_msg {
840 let mut buffer = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
841 wire::write($msg, &mut buffer).unwrap();
846 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
847 CM::Target: ChannelMessageHandler,
848 OM::Target: OnionMessageHandler,
850 NS::Target: NodeSigner {
851 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
852 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
855 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
856 /// cryptographically secure random bytes.
858 /// `current_time` is used as an always-increasing counter that survives across restarts and is
859 /// incremented irregularly internally. In general it is best to simply use the current UNIX
860 /// timestamp, however if it is not available a persistent counter that increases once per
861 /// minute should suffice.
863 /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
864 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 {
865 Self::new(MessageHandler {
866 chan_handler: channel_message_handler,
867 route_handler: IgnoringMessageHandler{},
868 onion_message_handler,
869 custom_message_handler: IgnoringMessageHandler{},
870 }, current_time, ephemeral_random_data, logger, node_signer)
874 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
875 RM::Target: RoutingMessageHandler,
877 NS::Target: NodeSigner {
878 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
879 /// handler or onion message handler is used and onion and channel messages will be ignored (or
880 /// generate error messages). Note that some other lightning implementations time-out connections
881 /// after some time if no channel is built with the peer.
883 /// `current_time` is used as an always-increasing counter that survives across restarts and is
884 /// incremented irregularly internally. In general it is best to simply use the current UNIX
885 /// timestamp, however if it is not available a persistent counter that increases once per
886 /// minute should suffice.
888 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
889 /// cryptographically secure random bytes.
891 /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
892 pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
893 Self::new(MessageHandler {
894 chan_handler: ErroringMessageHandler::new(),
895 route_handler: routing_message_handler,
896 onion_message_handler: IgnoringMessageHandler{},
897 custom_message_handler: IgnoringMessageHandler{},
898 }, current_time, ephemeral_random_data, logger, node_signer)
902 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
903 /// This works around `format!()` taking a reference to each argument, preventing
904 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
905 /// due to lifetime errors.
906 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
907 impl core::fmt::Display for OptionalFromDebugger<'_> {
908 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
909 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
913 /// A function used to filter out local or private addresses
914 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
915 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
916 fn filter_addresses(ip_address: Option<SocketAddress>) -> Option<SocketAddress> {
918 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
919 Some(SocketAddress::TcpIpV4{addr: [10, _, _, _], port: _}) => None,
920 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
921 Some(SocketAddress::TcpIpV4{addr: [0, _, _, _], port: _}) => None,
922 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
923 Some(SocketAddress::TcpIpV4{addr: [100, 64..=127, _, _], port: _}) => None,
924 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
925 Some(SocketAddress::TcpIpV4{addr: [127, _, _, _], port: _}) => None,
926 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
927 Some(SocketAddress::TcpIpV4{addr: [169, 254, _, _], port: _}) => None,
928 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
929 Some(SocketAddress::TcpIpV4{addr: [172, 16..=31, _, _], port: _}) => None,
930 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
931 Some(SocketAddress::TcpIpV4{addr: [192, 168, _, _], port: _}) => None,
932 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
933 Some(SocketAddress::TcpIpV4{addr: [192, 88, 99, _], port: _}) => None,
934 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
935 Some(SocketAddress::TcpIpV6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
936 // For remaining addresses
937 Some(SocketAddress::TcpIpV6{addr: _, port: _}) => None,
938 Some(..) => ip_address,
943 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
944 CM::Target: ChannelMessageHandler,
945 RM::Target: RoutingMessageHandler,
946 OM::Target: OnionMessageHandler,
948 CMH::Target: CustomMessageHandler,
949 NS::Target: NodeSigner
951 /// Constructs a new `PeerManager` with the given message handlers.
953 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
954 /// cryptographically secure random bytes.
956 /// `current_time` is used as an always-increasing counter that survives across restarts and is
957 /// incremented irregularly internally. In general it is best to simply use the current UNIX
958 /// timestamp, however if it is not available a persistent counter that increases once per
959 /// minute should suffice.
960 pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
961 let mut ephemeral_key_midstate = Sha256::engine();
962 ephemeral_key_midstate.input(ephemeral_random_data);
964 let mut secp_ctx = Secp256k1::signing_only();
965 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).to_byte_array();
966 secp_ctx.seeded_randomize(&ephemeral_hash);
970 peers: FairRwLock::new(new_hash_map()),
971 node_id_to_descriptor: Mutex::new(new_hash_map()),
972 event_processing_state: AtomicI32::new(0),
973 ephemeral_key_midstate,
974 peer_counter: AtomicCounter::new(),
975 gossip_processing_backlogged: AtomicBool::new(false),
976 gossip_processing_backlog_lifted: AtomicBool::new(false),
977 last_node_announcement_serial: AtomicU32::new(current_time),
984 /// Returns a list of [`PeerDetails`] for connected peers that have completed the initial
986 pub fn list_peers(&self) -> Vec<PeerDetails> {
987 let peers = self.peers.read().unwrap();
988 peers.values().filter_map(|peer_mutex| {
989 let p = peer_mutex.lock().unwrap();
990 if !p.handshake_complete() {
993 let details = PeerDetails {
994 // unwrap safety: their_node_id is guaranteed to be `Some` after the handshake
996 counterparty_node_id: p.their_node_id.unwrap().0,
997 socket_address: p.their_socket_address.clone(),
998 // unwrap safety: their_features is guaranteed to be `Some` after the handshake
1000 init_features: p.their_features.clone().unwrap(),
1001 is_inbound_connection: p.inbound_connection,
1007 /// Returns the [`PeerDetails`] of a connected peer that has completed the initial handshake.
1009 /// Will return `None` if the peer is unknown or it hasn't completed the initial handshake.
1010 pub fn peer_by_node_id(&self, their_node_id: &PublicKey) -> Option<PeerDetails> {
1011 let peers = self.peers.read().unwrap();
1012 peers.values().find_map(|peer_mutex| {
1013 let p = peer_mutex.lock().unwrap();
1014 if !p.handshake_complete() {
1018 // unwrap safety: their_node_id is guaranteed to be `Some` after the handshake
1020 let counterparty_node_id = p.their_node_id.unwrap().0;
1022 if counterparty_node_id != *their_node_id {
1026 let details = PeerDetails {
1027 counterparty_node_id,
1028 socket_address: p.their_socket_address.clone(),
1029 // unwrap safety: their_features is guaranteed to be `Some` after the handshake
1031 init_features: p.their_features.clone().unwrap(),
1032 is_inbound_connection: p.inbound_connection,
1038 fn get_ephemeral_key(&self) -> SecretKey {
1039 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
1040 let counter = self.peer_counter.get_increment();
1041 ephemeral_hash.input(&counter.to_le_bytes());
1042 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).to_byte_array()).expect("You broke SHA-256!")
1045 fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
1046 self.message_handler.chan_handler.provided_init_features(their_node_id)
1047 | self.message_handler.route_handler.provided_init_features(their_node_id)
1048 | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
1049 | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
1052 /// Indicates a new outbound connection has been established to a node with the given `node_id`
1053 /// and an optional remote network address.
1055 /// The remote network address adds the option to report a remote IP address back to a connecting
1056 /// peer using the init message.
1057 /// The user should pass the remote network address of the host they are connected to.
1059 /// If an `Err` is returned here you must disconnect the connection immediately.
1061 /// Returns a small number of bytes to send to the remote node (currently always 50).
1063 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1064 /// [`socket_disconnected`].
1066 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1067 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<Vec<u8>, PeerHandleError> {
1068 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
1069 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
1070 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
1072 let mut peers = self.peers.write().unwrap();
1073 match peers.entry(descriptor) {
1074 hash_map::Entry::Occupied(_) => {
1075 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1076 Err(PeerHandleError {})
1078 hash_map::Entry::Vacant(e) => {
1079 e.insert(Mutex::new(Peer {
1080 channel_encryptor: peer_encryptor,
1081 their_node_id: None,
1082 their_features: None,
1083 their_socket_address: remote_network_address,
1085 pending_outbound_buffer: VecDeque::new(),
1086 pending_outbound_buffer_first_msg_offset: 0,
1087 gossip_broadcast_buffer: VecDeque::new(),
1088 awaiting_write_event: false,
1090 pending_read_buffer,
1091 pending_read_buffer_pos: 0,
1092 pending_read_is_header: false,
1094 sync_status: InitSyncTracker::NoSyncRequested,
1096 msgs_sent_since_pong: 0,
1097 awaiting_pong_timer_tick_intervals: 0,
1098 received_message_since_timer_tick: false,
1099 sent_gossip_timestamp_filter: false,
1101 received_channel_announce_since_backlogged: false,
1102 inbound_connection: false,
1109 /// Indicates a new inbound connection has been established to a node with an optional remote
1110 /// network address.
1112 /// The remote network address adds the option to report a remote IP address back to a connecting
1113 /// peer using the init message.
1114 /// The user should pass the remote network address of the host they are connected to.
1116 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
1117 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
1118 /// the connection immediately.
1120 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1121 /// [`socket_disconnected`].
1123 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1124 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<(), PeerHandleError> {
1125 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1126 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1128 let mut peers = self.peers.write().unwrap();
1129 match peers.entry(descriptor) {
1130 hash_map::Entry::Occupied(_) => {
1131 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1132 Err(PeerHandleError {})
1134 hash_map::Entry::Vacant(e) => {
1135 e.insert(Mutex::new(Peer {
1136 channel_encryptor: peer_encryptor,
1137 their_node_id: None,
1138 their_features: None,
1139 their_socket_address: remote_network_address,
1141 pending_outbound_buffer: VecDeque::new(),
1142 pending_outbound_buffer_first_msg_offset: 0,
1143 gossip_broadcast_buffer: VecDeque::new(),
1144 awaiting_write_event: false,
1146 pending_read_buffer,
1147 pending_read_buffer_pos: 0,
1148 pending_read_is_header: false,
1150 sync_status: InitSyncTracker::NoSyncRequested,
1152 msgs_sent_since_pong: 0,
1153 awaiting_pong_timer_tick_intervals: 0,
1154 received_message_since_timer_tick: false,
1155 sent_gossip_timestamp_filter: false,
1157 received_channel_announce_since_backlogged: false,
1158 inbound_connection: true,
1165 fn peer_should_read(&self, peer: &mut Peer) -> bool {
1166 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1169 fn update_gossip_backlogged(&self) {
1170 let new_state = self.message_handler.route_handler.processing_queue_high();
1171 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1172 if prev_state && !new_state {
1173 self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1177 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1178 let mut have_written = false;
1179 while !peer.awaiting_write_event {
1180 if peer.should_buffer_onion_message() {
1181 if let Some((peer_node_id, _)) = peer.their_node_id {
1182 if let Some(next_onion_message) =
1183 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1184 self.enqueue_message(peer, &next_onion_message);
1188 if peer.should_buffer_gossip_broadcast() {
1189 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1190 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(msg));
1193 if peer.should_buffer_gossip_backfill() {
1194 match peer.sync_status {
1195 InitSyncTracker::NoSyncRequested => {},
1196 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1197 if let Some((announce, update_a_option, update_b_option)) =
1198 self.message_handler.route_handler.get_next_channel_announcement(c)
1200 self.enqueue_message(peer, &announce);
1201 if let Some(update_a) = update_a_option {
1202 self.enqueue_message(peer, &update_a);
1204 if let Some(update_b) = update_b_option {
1205 self.enqueue_message(peer, &update_b);
1207 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1209 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1212 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1213 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1214 self.enqueue_message(peer, &msg);
1215 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1217 peer.sync_status = InitSyncTracker::NoSyncRequested;
1220 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1221 InitSyncTracker::NodesSyncing(sync_node_id) => {
1222 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1223 self.enqueue_message(peer, &msg);
1224 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1226 peer.sync_status = InitSyncTracker::NoSyncRequested;
1231 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1232 self.maybe_send_extra_ping(peer);
1235 let should_read = self.peer_should_read(peer);
1236 let next_buff = match peer.pending_outbound_buffer.front() {
1238 if force_one_write && !have_written {
1240 let data_sent = descriptor.send_data(&[], should_read);
1241 debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1249 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1250 let data_sent = descriptor.send_data(pending, should_read);
1251 have_written = true;
1252 peer.pending_outbound_buffer_first_msg_offset += data_sent;
1253 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1254 peer.pending_outbound_buffer_first_msg_offset = 0;
1255 peer.pending_outbound_buffer.pop_front();
1256 const VEC_SIZE: usize = ::core::mem::size_of::<Vec<u8>>();
1257 let large_capacity = peer.pending_outbound_buffer.capacity() > 4096 / VEC_SIZE;
1258 let lots_of_slack = peer.pending_outbound_buffer.len()
1259 < peer.pending_outbound_buffer.capacity() / 2;
1260 if large_capacity && lots_of_slack {
1261 peer.pending_outbound_buffer.shrink_to_fit();
1264 peer.awaiting_write_event = true;
1269 /// Indicates that there is room to write data to the given socket descriptor.
1271 /// May return an Err to indicate that the connection should be closed.
1273 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1274 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1275 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1276 /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1279 /// [`send_data`]: SocketDescriptor::send_data
1280 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1281 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1282 let peers = self.peers.read().unwrap();
1283 match peers.get(descriptor) {
1285 // This is most likely a simple race condition where the user found that the socket
1286 // was writeable, then we told the user to `disconnect_socket()`, then they called
1287 // this method. Return an error to make sure we get disconnected.
1288 return Err(PeerHandleError { });
1290 Some(peer_mutex) => {
1291 let mut peer = peer_mutex.lock().unwrap();
1292 peer.awaiting_write_event = false;
1293 self.do_attempt_write_data(descriptor, &mut peer, false);
1299 /// Indicates that data was read from the given socket descriptor.
1301 /// May return an Err to indicate that the connection should be closed.
1303 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1304 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1305 /// [`send_data`] calls to handle responses.
1307 /// If `Ok(true)` is returned, further read_events should not be triggered until a
1308 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1311 /// In order to avoid processing too many messages at once per peer, `data` should be on the
1314 /// [`send_data`]: SocketDescriptor::send_data
1315 /// [`process_events`]: PeerManager::process_events
1316 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1317 match self.do_read_event(peer_descriptor, data) {
1320 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1321 self.disconnect_event_internal(peer_descriptor);
1327 /// Append a message to a peer's pending outbound/write buffer
1328 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1329 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1330 if is_gossip_msg(message.type_id()) {
1331 log_gossip!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1333 log_trace!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1335 peer.msgs_sent_since_pong += 1;
1336 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1339 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1340 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: MessageBuf) {
1341 peer.msgs_sent_since_pong += 1;
1342 debug_assert!(peer.gossip_broadcast_buffer.len() <= OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP);
1343 peer.gossip_broadcast_buffer.push_back(encoded_message);
1346 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1347 let mut pause_read = false;
1348 let peers = self.peers.read().unwrap();
1349 let mut msgs_to_forward = Vec::new();
1350 let mut peer_node_id = None;
1351 match peers.get(peer_descriptor) {
1353 // This is most likely a simple race condition where the user read some bytes
1354 // from the socket, then we told the user to `disconnect_socket()`, then they
1355 // called this method. Return an error to make sure we get disconnected.
1356 return Err(PeerHandleError { });
1358 Some(peer_mutex) => {
1359 let mut read_pos = 0;
1360 while read_pos < data.len() {
1361 macro_rules! try_potential_handleerror {
1362 ($peer: expr, $thing: expr) => {{
1364 let logger = WithContext::from(&self.logger, peer_node_id.map(|(id, _)| id), None, None);
1369 msgs::ErrorAction::DisconnectPeer { .. } => {
1370 // We may have an `ErrorMessage` to send to the peer,
1371 // but writing to the socket while reading can lead to
1372 // re-entrant code and possibly unexpected behavior. The
1373 // message send is optimistic anyway, and in this case
1374 // we immediately disconnect the peer.
1375 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1376 return Err(PeerHandleError { });
1378 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1379 // We have a `WarningMessage` to send to the peer, but
1380 // writing to the socket while reading can lead to
1381 // re-entrant code and possibly unexpected behavior. The
1382 // message send is optimistic anyway, and in this case
1383 // we immediately disconnect the peer.
1384 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1385 return Err(PeerHandleError { });
1387 msgs::ErrorAction::IgnoreAndLog(level) => {
1388 log_given_level!(logger, level, "Error handling {}message{}; ignoring: {}",
1389 if level == Level::Gossip { "gossip " } else { "" },
1390 OptionalFromDebugger(&peer_node_id), e.err);
1393 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1394 msgs::ErrorAction::IgnoreError => {
1395 log_debug!(logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1398 msgs::ErrorAction::SendErrorMessage { msg } => {
1399 log_debug!(logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1400 self.enqueue_message($peer, &msg);
1403 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1404 log_given_level!(logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1405 self.enqueue_message($peer, &msg);
1414 let mut peer_lock = peer_mutex.lock().unwrap();
1415 let peer = &mut *peer_lock;
1416 let mut msg_to_handle = None;
1417 if peer_node_id.is_none() {
1418 peer_node_id = peer.their_node_id.clone();
1421 assert!(peer.pending_read_buffer.len() > 0);
1422 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1425 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1426 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]);
1427 read_pos += data_to_copy;
1428 peer.pending_read_buffer_pos += data_to_copy;
1431 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1432 peer.pending_read_buffer_pos = 0;
1434 macro_rules! insert_node_id {
1436 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1437 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1438 hash_map::Entry::Occupied(e) => {
1439 log_trace!(logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1440 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1441 // Check that the peers map is consistent with the
1442 // node_id_to_descriptor map, as this has been broken
1444 debug_assert!(peers.get(e.get()).is_some());
1445 return Err(PeerHandleError { })
1447 hash_map::Entry::Vacant(entry) => {
1448 log_debug!(logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1449 entry.insert(peer_descriptor.clone())
1455 let next_step = peer.channel_encryptor.get_noise_step();
1457 NextNoiseStep::ActOne => {
1458 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1459 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1460 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1461 peer.pending_outbound_buffer.push_back(act_two);
1462 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1464 NextNoiseStep::ActTwo => {
1465 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1466 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1467 &self.node_signer));
1468 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1469 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1470 peer.pending_read_is_header = true;
1472 peer.set_their_node_id(their_node_id);
1474 let features = self.init_features(&their_node_id);
1475 let networks = self.message_handler.chan_handler.get_chain_hashes();
1476 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1477 self.enqueue_message(peer, &resp);
1479 NextNoiseStep::ActThree => {
1480 let their_node_id = try_potential_handleerror!(peer,
1481 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1482 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1483 peer.pending_read_is_header = true;
1484 peer.set_their_node_id(their_node_id);
1486 let features = self.init_features(&their_node_id);
1487 let networks = self.message_handler.chan_handler.get_chain_hashes();
1488 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1489 self.enqueue_message(peer, &resp);
1491 NextNoiseStep::NoiseComplete => {
1492 if peer.pending_read_is_header {
1493 let msg_len = try_potential_handleerror!(peer,
1494 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1495 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1496 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1497 if msg_len < 2 { // Need at least the message type tag
1498 return Err(PeerHandleError { });
1500 peer.pending_read_is_header = false;
1502 debug_assert!(peer.pending_read_buffer.len() >= 2 + 16);
1503 try_potential_handleerror!(peer,
1504 peer.channel_encryptor.decrypt_message(&mut peer.pending_read_buffer[..]));
1506 let mut reader = io::Cursor::new(&peer.pending_read_buffer[..peer.pending_read_buffer.len() - 16]);
1507 let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1509 // Reset read buffer
1510 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1511 peer.pending_read_buffer.resize(18, 0);
1512 peer.pending_read_is_header = true;
1514 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1515 let message = match message_result {
1519 // Note that to avoid re-entrancy we never call
1520 // `do_attempt_write_data` from here, causing
1521 // the messages enqueued here to not actually
1522 // be sent before the peer is disconnected.
1523 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1524 log_gossip!(logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1527 (msgs::DecodeError::UnsupportedCompression, _) => {
1528 log_gossip!(logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1529 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: ChannelId::new_zero(), data: "Unsupported message compression: zlib".to_owned() });
1532 (_, Some(ty)) if is_gossip_msg(ty) => {
1533 log_gossip!(logger, "Got an invalid value while deserializing a gossip message");
1534 self.enqueue_message(peer, &msgs::WarningMessage {
1535 channel_id: ChannelId::new_zero(),
1536 data: format!("Unreadable/bogus gossip message of type {}", ty),
1540 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1541 log_debug!(logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1542 return Err(PeerHandleError { });
1544 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1545 (msgs::DecodeError::InvalidValue, _) => {
1546 log_debug!(logger, "Got an invalid value while deserializing message");
1547 return Err(PeerHandleError { });
1549 (msgs::DecodeError::ShortRead, _) => {
1550 log_debug!(logger, "Deserialization failed due to shortness of message");
1551 return Err(PeerHandleError { });
1553 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1554 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1555 (msgs::DecodeError::DangerousValue, _) => return Err(PeerHandleError { }),
1560 msg_to_handle = Some(message);
1565 pause_read = !self.peer_should_read(peer);
1567 if let Some(message) = msg_to_handle {
1568 match self.handle_message(&peer_mutex, peer_lock, message) {
1569 Err(handling_error) => match handling_error {
1570 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1571 MessageHandlingError::LightningError(e) => {
1572 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1576 msgs_to_forward.push(msg);
1585 for msg in msgs_to_forward.drain(..) {
1586 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1592 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1594 /// Returns the message back if it needs to be broadcasted to all other peers.
1597 peer_mutex: &Mutex<Peer>,
1598 peer_lock: MutexGuard<Peer>,
1599 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1600 ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1601 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;
1602 let logger = WithContext::from(&self.logger, Some(their_node_id), None, None);
1604 let message = match self.do_handle_message_holding_peer_lock(peer_lock, message, &their_node_id, &logger)? {
1605 Some(processed_message) => processed_message,
1606 None => return Ok(None),
1609 self.do_handle_message_without_peer_lock(peer_mutex, message, &their_node_id, &logger)
1612 // Conducts all message processing that requires us to hold the `peer_lock`.
1614 // Returns `None` if the message was fully processed and otherwise returns the message back to
1615 // allow it to be subsequently processed by `do_handle_message_without_peer_lock`.
1616 fn do_handle_message_holding_peer_lock<'a>(
1618 mut peer_lock: MutexGuard<Peer>,
1619 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>,
1620 their_node_id: &PublicKey,
1621 logger: &WithContext<'a, L>
1622 ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError>
1624 peer_lock.received_message_since_timer_tick = true;
1626 // Need an Init as first message
1627 if let wire::Message::Init(msg) = message {
1628 // Check if we have any compatible chains if the `networks` field is specified.
1629 if let Some(networks) = &msg.networks {
1630 if let Some(our_chains) = self.message_handler.chan_handler.get_chain_hashes() {
1631 let mut have_compatible_chains = false;
1632 'our_chains: for our_chain in our_chains.iter() {
1633 for their_chain in networks {
1634 if our_chain == their_chain {
1635 have_compatible_chains = true;
1640 if !have_compatible_chains {
1641 log_debug!(logger, "Peer does not support any of our supported chains");
1642 return Err(PeerHandleError { }.into());
1647 let our_features = self.init_features(&their_node_id);
1648 if msg.features.requires_unknown_bits_from(&our_features) {
1649 log_debug!(logger, "Peer {} requires features unknown to us: {:?}",
1650 log_pubkey!(their_node_id), msg.features.required_unknown_bits_from(&our_features));
1651 return Err(PeerHandleError { }.into());
1654 if our_features.requires_unknown_bits_from(&msg.features) {
1655 log_debug!(logger, "We require features unknown to our peer {}: {:?}",
1656 log_pubkey!(their_node_id), our_features.required_unknown_bits_from(&msg.features));
1657 return Err(PeerHandleError { }.into());
1660 if peer_lock.their_features.is_some() {
1661 return Err(PeerHandleError { }.into());
1664 log_info!(logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1666 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1667 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1668 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1671 if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1672 log_debug!(logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1673 return Err(PeerHandleError { }.into());
1675 if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1676 log_debug!(logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1677 return Err(PeerHandleError { }.into());
1679 if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1680 log_debug!(logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1681 return Err(PeerHandleError { }.into());
1684 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1685 peer_lock.their_features = Some(msg.features);
1687 } else if peer_lock.their_features.is_none() {
1688 log_debug!(logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1689 return Err(PeerHandleError { }.into());
1692 if let wire::Message::GossipTimestampFilter(_msg) = message {
1693 // When supporting gossip messages, start initial gossip sync only after we receive
1694 // a GossipTimestampFilter
1695 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1696 !peer_lock.sent_gossip_timestamp_filter {
1697 peer_lock.sent_gossip_timestamp_filter = true;
1698 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1703 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1704 peer_lock.received_channel_announce_since_backlogged = true;
1710 // Conducts all message processing that doesn't require us to hold the `peer_lock`.
1712 // Returns the message back if it needs to be broadcasted to all other peers.
1713 fn do_handle_message_without_peer_lock<'a>(
1715 peer_mutex: &Mutex<Peer>,
1716 message: wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>,
1717 their_node_id: &PublicKey,
1718 logger: &WithContext<'a, L>
1719 ) -> Result<Option<wire::Message<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError>
1721 if is_gossip_msg(message.type_id()) {
1722 log_gossip!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1724 log_trace!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1727 let mut should_forward = None;
1730 // Setup and Control messages:
1731 wire::Message::Init(_) => {
1734 wire::Message::GossipTimestampFilter(_) => {
1737 wire::Message::Error(msg) => {
1738 log_debug!(logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1739 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1740 if msg.channel_id.is_zero() {
1741 return Err(PeerHandleError { }.into());
1744 wire::Message::Warning(msg) => {
1745 log_debug!(logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1748 wire::Message::Ping(msg) => {
1749 if msg.ponglen < 65532 {
1750 let resp = msgs::Pong { byteslen: msg.ponglen };
1751 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1754 wire::Message::Pong(_msg) => {
1755 let mut peer_lock = peer_mutex.lock().unwrap();
1756 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1757 peer_lock.msgs_sent_since_pong = 0;
1760 // Channel messages:
1761 wire::Message::OpenChannel(msg) => {
1762 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1764 wire::Message::OpenChannelV2(msg) => {
1765 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1767 wire::Message::AcceptChannel(msg) => {
1768 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1770 wire::Message::AcceptChannelV2(msg) => {
1771 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1774 wire::Message::FundingCreated(msg) => {
1775 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1777 wire::Message::FundingSigned(msg) => {
1778 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1780 wire::Message::ChannelReady(msg) => {
1781 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1784 // Quiescence messages:
1785 wire::Message::Stfu(msg) => {
1786 self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
1790 // Splicing messages:
1791 wire::Message::Splice(msg) => {
1792 self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
1795 wire::Message::SpliceAck(msg) => {
1796 self.message_handler.chan_handler.handle_splice_ack(&their_node_id, &msg);
1799 wire::Message::SpliceLocked(msg) => {
1800 self.message_handler.chan_handler.handle_splice_locked(&their_node_id, &msg);
1803 // Interactive transaction construction messages:
1804 wire::Message::TxAddInput(msg) => {
1805 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1807 wire::Message::TxAddOutput(msg) => {
1808 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1810 wire::Message::TxRemoveInput(msg) => {
1811 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1813 wire::Message::TxRemoveOutput(msg) => {
1814 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1816 wire::Message::TxComplete(msg) => {
1817 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1819 wire::Message::TxSignatures(msg) => {
1820 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1822 wire::Message::TxInitRbf(msg) => {
1823 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1825 wire::Message::TxAckRbf(msg) => {
1826 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1828 wire::Message::TxAbort(msg) => {
1829 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1832 wire::Message::Shutdown(msg) => {
1833 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1835 wire::Message::ClosingSigned(msg) => {
1836 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1839 // Commitment messages:
1840 wire::Message::UpdateAddHTLC(msg) => {
1841 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1843 wire::Message::UpdateFulfillHTLC(msg) => {
1844 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1846 wire::Message::UpdateFailHTLC(msg) => {
1847 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1849 wire::Message::UpdateFailMalformedHTLC(msg) => {
1850 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1853 wire::Message::CommitmentSigned(msg) => {
1854 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1856 wire::Message::RevokeAndACK(msg) => {
1857 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1859 wire::Message::UpdateFee(msg) => {
1860 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1862 wire::Message::ChannelReestablish(msg) => {
1863 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1866 // Routing messages:
1867 wire::Message::AnnouncementSignatures(msg) => {
1868 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1870 wire::Message::ChannelAnnouncement(msg) => {
1871 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1872 .map_err(|e| -> MessageHandlingError { e.into() })? {
1873 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1875 self.update_gossip_backlogged();
1877 wire::Message::NodeAnnouncement(msg) => {
1878 if self.message_handler.route_handler.handle_node_announcement(&msg)
1879 .map_err(|e| -> MessageHandlingError { e.into() })? {
1880 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1882 self.update_gossip_backlogged();
1884 wire::Message::ChannelUpdate(msg) => {
1885 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1886 if self.message_handler.route_handler.handle_channel_update(&msg)
1887 .map_err(|e| -> MessageHandlingError { e.into() })? {
1888 should_forward = Some(wire::Message::ChannelUpdate(msg));
1890 self.update_gossip_backlogged();
1892 wire::Message::QueryShortChannelIds(msg) => {
1893 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1895 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1896 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1898 wire::Message::QueryChannelRange(msg) => {
1899 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1901 wire::Message::ReplyChannelRange(msg) => {
1902 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1906 wire::Message::OnionMessage(msg) => {
1907 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1910 // Unknown messages:
1911 wire::Message::Unknown(type_id) if message.is_even() => {
1912 log_debug!(logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1913 return Err(PeerHandleError { }.into());
1915 wire::Message::Unknown(type_id) => {
1916 log_trace!(logger, "Received unknown odd message of type {}, ignoring", type_id);
1918 wire::Message::Custom(custom) => {
1919 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1925 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>) {
1927 wire::Message::ChannelAnnouncement(ref msg) => {
1928 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1929 let encoded_msg = encode_msg!(msg);
1931 for (_, peer_mutex) in peers.iter() {
1932 let mut peer = peer_mutex.lock().unwrap();
1933 if !peer.handshake_complete() ||
1934 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1937 debug_assert!(peer.their_node_id.is_some());
1938 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1939 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1940 if peer.buffer_full_drop_gossip_broadcast() {
1941 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1944 if let Some((_, their_node_id)) = peer.their_node_id {
1945 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1949 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1952 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1955 wire::Message::NodeAnnouncement(ref msg) => {
1956 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1957 let encoded_msg = encode_msg!(msg);
1959 for (_, peer_mutex) in peers.iter() {
1960 let mut peer = peer_mutex.lock().unwrap();
1961 if !peer.handshake_complete() ||
1962 !peer.should_forward_node_announcement(msg.contents.node_id) {
1965 debug_assert!(peer.their_node_id.is_some());
1966 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1967 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1968 if peer.buffer_full_drop_gossip_broadcast() {
1969 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1972 if let Some((_, their_node_id)) = peer.their_node_id {
1973 if their_node_id == msg.contents.node_id {
1977 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1980 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1983 wire::Message::ChannelUpdate(ref msg) => {
1984 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1985 let encoded_msg = encode_msg!(msg);
1987 for (_, peer_mutex) in peers.iter() {
1988 let mut peer = peer_mutex.lock().unwrap();
1989 if !peer.handshake_complete() ||
1990 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1993 debug_assert!(peer.their_node_id.is_some());
1994 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1995 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None, None);
1996 if peer.buffer_full_drop_gossip_broadcast() {
1997 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
2000 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
2003 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
2006 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
2010 /// Checks for any events generated by our handlers and processes them. Includes sending most
2011 /// response messages as well as messages generated by calls to handler functions directly (eg
2012 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
2014 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2017 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
2018 /// or one of the other clients provided in our language bindings.
2020 /// Note that if there are any other calls to this function waiting on lock(s) this may return
2021 /// without doing any work. All available events that need handling will be handled before the
2022 /// other calls return.
2024 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
2025 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
2026 /// [`send_data`]: SocketDescriptor::send_data
2027 pub fn process_events(&self) {
2028 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
2029 // If we're not the first event processor to get here, just return early, the increment
2030 // we just did will be treated as "go around again" at the end.
2035 self.update_gossip_backlogged();
2036 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2038 let mut peers_to_disconnect = new_hash_map();
2041 let peers_lock = self.peers.read().unwrap();
2043 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
2044 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
2046 let peers = &*peers_lock;
2047 macro_rules! get_peer_for_forwarding {
2048 ($node_id: expr) => {
2050 if peers_to_disconnect.get($node_id).is_some() {
2051 // If we've "disconnected" this peer, do not send to it.
2054 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
2055 match descriptor_opt {
2056 Some(descriptor) => match peers.get(&descriptor) {
2057 Some(peer_mutex) => {
2058 let peer_lock = peer_mutex.lock().unwrap();
2059 if !peer_lock.handshake_complete() {
2065 debug_assert!(false, "Inconsistent peers set state!");
2076 for event in events_generated.drain(..) {
2078 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
2079 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id), None), "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
2080 log_pubkey!(node_id),
2081 &msg.common_fields.temporary_channel_id);
2082 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2084 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
2085 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id), None), "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
2086 log_pubkey!(node_id),
2087 &msg.common_fields.temporary_channel_id);
2088 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2090 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
2091 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id), None), "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
2092 log_pubkey!(node_id),
2093 &msg.common_fields.temporary_channel_id);
2094 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2096 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
2097 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id), None), "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}",
2098 log_pubkey!(node_id),
2099 &msg.common_fields.temporary_channel_id);
2100 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2102 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
2103 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id), None), "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
2104 log_pubkey!(node_id),
2105 &msg.temporary_channel_id,
2106 ChannelId::v1_from_funding_txid(msg.funding_txid.as_byte_array(), msg.funding_output_index));
2107 // TODO: If the peer is gone we should generate a DiscardFunding event
2108 // indicating to the wallet that they should just throw away this funding transaction
2109 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2111 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
2112 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
2113 log_pubkey!(node_id),
2115 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2117 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
2118 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendChannelReady event in peer_handler for node {} for channel {}",
2119 log_pubkey!(node_id),
2121 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2123 MessageSendEvent::SendStfu { ref node_id, ref msg} => {
2124 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None);
2125 log_debug!(logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
2126 log_pubkey!(node_id),
2128 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2130 MessageSendEvent::SendSplice { ref node_id, ref msg} => {
2131 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None);
2132 log_debug!(logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
2133 log_pubkey!(node_id),
2135 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2137 MessageSendEvent::SendSpliceAck { ref node_id, ref msg} => {
2138 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None);
2139 log_debug!(logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}",
2140 log_pubkey!(node_id),
2142 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2144 MessageSendEvent::SendSpliceLocked { ref node_id, ref msg} => {
2145 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None);
2146 log_debug!(logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}",
2147 log_pubkey!(node_id),
2149 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2151 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
2152 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
2153 log_pubkey!(node_id),
2155 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2157 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
2158 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAddOutput event in peer_handler for node {} for channel {}",
2159 log_pubkey!(node_id),
2161 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2163 MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => {
2164 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
2165 log_pubkey!(node_id),
2167 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2169 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
2170 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
2171 log_pubkey!(node_id),
2173 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2175 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
2176 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxComplete event in peer_handler for node {} for channel {}",
2177 log_pubkey!(node_id),
2179 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2181 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
2182 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
2183 log_pubkey!(node_id),
2185 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2187 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
2188 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
2189 log_pubkey!(node_id),
2191 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2193 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2194 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2195 log_pubkey!(node_id),
2197 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2199 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2200 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2201 log_pubkey!(node_id),
2203 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2205 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2206 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2207 log_pubkey!(node_id),
2209 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2211 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 } } => {
2212 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(commitment_signed.channel_id), None), "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
2213 log_pubkey!(node_id),
2214 update_add_htlcs.len(),
2215 update_fulfill_htlcs.len(),
2216 update_fail_htlcs.len(),
2217 &commitment_signed.channel_id);
2218 let mut peer = get_peer_for_forwarding!(node_id);
2219 for msg in update_add_htlcs {
2220 self.enqueue_message(&mut *peer, msg);
2222 for msg in update_fulfill_htlcs {
2223 self.enqueue_message(&mut *peer, msg);
2225 for msg in update_fail_htlcs {
2226 self.enqueue_message(&mut *peer, msg);
2228 for msg in update_fail_malformed_htlcs {
2229 self.enqueue_message(&mut *peer, msg);
2231 if let &Some(ref msg) = update_fee {
2232 self.enqueue_message(&mut *peer, msg);
2234 self.enqueue_message(&mut *peer, commitment_signed);
2236 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2237 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2238 log_pubkey!(node_id),
2240 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2242 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2243 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2244 log_pubkey!(node_id),
2246 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2248 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2249 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling Shutdown event in peer_handler for node {} for channel {}",
2250 log_pubkey!(node_id),
2252 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2254 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2255 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id), None), "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2256 log_pubkey!(node_id),
2258 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2260 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2261 log_debug!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2262 log_pubkey!(node_id),
2263 msg.contents.short_channel_id);
2264 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2265 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2267 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2268 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2269 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2270 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2271 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2274 if let Some(msg) = update_msg {
2275 match self.message_handler.route_handler.handle_channel_update(&msg) {
2276 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2277 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2282 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2283 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents);
2284 match self.message_handler.route_handler.handle_channel_update(&msg) {
2285 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2286 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2290 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2291 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2292 match self.message_handler.route_handler.handle_node_announcement(&msg) {
2293 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2294 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2298 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2299 log_trace!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2300 log_pubkey!(node_id), msg.contents.short_channel_id);
2301 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2303 MessageSendEvent::HandleError { node_id, action } => {
2304 let logger = WithContext::from(&self.logger, Some(node_id), None, None);
2306 msgs::ErrorAction::DisconnectPeer { msg } => {
2307 if let Some(msg) = msg.as_ref() {
2308 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2309 log_pubkey!(node_id), msg.data);
2311 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2312 log_pubkey!(node_id));
2314 // We do not have the peers write lock, so we just store that we're
2315 // about to disconnect the peer and do it after we finish
2316 // processing most messages.
2317 let msg = msg.map(|msg| wire::Message::<<<CMH as Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2318 peers_to_disconnect.insert(node_id, msg);
2320 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2321 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2322 log_pubkey!(node_id), msg.data);
2323 // We do not have the peers write lock, so we just store that we're
2324 // about to disconnect the peer and do it after we finish
2325 // processing most messages.
2326 peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2328 msgs::ErrorAction::IgnoreAndLog(level) => {
2329 log_given_level!(logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2331 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2332 msgs::ErrorAction::IgnoreError => {
2333 log_debug!(logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2335 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2336 log_trace!(logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2337 log_pubkey!(node_id),
2339 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2341 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2342 log_given_level!(logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2343 log_pubkey!(node_id),
2345 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2349 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2350 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2352 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2353 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2355 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2356 log_gossip!(WithContext::from(&self.logger, Some(*node_id), None, None), "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
2357 log_pubkey!(node_id),
2358 msg.short_channel_ids.len(),
2360 msg.number_of_blocks,
2362 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2364 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2365 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2370 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2371 if peers_to_disconnect.get(&node_id).is_some() { continue; }
2372 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2375 for (descriptor, peer_mutex) in peers.iter() {
2376 let mut peer = peer_mutex.lock().unwrap();
2377 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2378 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2381 if !peers_to_disconnect.is_empty() {
2382 let mut peers_lock = self.peers.write().unwrap();
2383 let peers = &mut *peers_lock;
2384 for (node_id, msg) in peers_to_disconnect.drain() {
2385 // Note that since we are holding the peers *write* lock we can
2386 // remove from node_id_to_descriptor immediately (as no other
2387 // thread can be holding the peer lock if we have the global write
2390 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2391 if let Some(mut descriptor) = descriptor_opt {
2392 if let Some(peer_mutex) = peers.remove(&descriptor) {
2393 let mut peer = peer_mutex.lock().unwrap();
2394 if let Some(msg) = msg {
2395 self.enqueue_message(&mut *peer, &msg);
2396 // This isn't guaranteed to work, but if there is enough free
2397 // room in the send buffer, put the error message there...
2398 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2400 self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2401 } else { debug_assert!(false, "Missing connection for peer"); }
2406 if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2407 // If another thread incremented the state while we were running we should go
2408 // around again, but only once.
2409 self.event_processing_state.store(1, Ordering::Release);
2416 /// Indicates that the given socket descriptor's connection is now closed.
2417 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2418 self.disconnect_event_internal(descriptor);
2421 fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2422 if !peer.handshake_complete() {
2423 log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2424 descriptor.disconnect_socket();
2428 debug_assert!(peer.their_node_id.is_some());
2429 if let Some((node_id, _)) = peer.their_node_id {
2430 log_trace!(WithContext::from(&self.logger, Some(node_id), None, None), "Disconnecting peer with id {} due to {}", node_id, reason);
2431 self.message_handler.chan_handler.peer_disconnected(&node_id);
2432 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2434 descriptor.disconnect_socket();
2437 fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2438 let mut peers = self.peers.write().unwrap();
2439 let peer_option = peers.remove(descriptor);
2442 // This is most likely a simple race condition where the user found that the socket
2443 // was disconnected, then we told the user to `disconnect_socket()`, then they
2444 // called this method. Either way we're disconnected, return.
2446 Some(peer_lock) => {
2447 let peer = peer_lock.lock().unwrap();
2448 if let Some((node_id, _)) = peer.their_node_id {
2449 log_trace!(WithContext::from(&self.logger, Some(node_id), None, None), "Handling disconnection of peer {}", log_pubkey!(node_id));
2450 let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2451 debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2452 if !peer.handshake_complete() { return; }
2453 self.message_handler.chan_handler.peer_disconnected(&node_id);
2454 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2460 /// Disconnect a peer given its node id.
2462 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2463 /// peer. Thus, be very careful about reentrancy issues.
2465 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2466 pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2467 let mut peers_lock = self.peers.write().unwrap();
2468 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2469 let peer_opt = peers_lock.remove(&descriptor);
2470 if let Some(peer_mutex) = peer_opt {
2471 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2472 } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2476 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2477 /// an indication that TCP sockets have stalled even if we weren't around to time them out
2478 /// using regular ping/pongs.
2479 pub fn disconnect_all_peers(&self) {
2480 let mut peers_lock = self.peers.write().unwrap();
2481 self.node_id_to_descriptor.lock().unwrap().clear();
2482 let peers = &mut *peers_lock;
2483 for (descriptor, peer_mutex) in peers.drain() {
2484 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2488 /// This is called when we're blocked on sending additional gossip messages until we receive a
2489 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2490 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2491 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2492 if peer.awaiting_pong_timer_tick_intervals == 0 {
2493 peer.awaiting_pong_timer_tick_intervals = -1;
2494 let ping = msgs::Ping {
2498 self.enqueue_message(peer, &ping);
2502 /// Send pings to each peer and disconnect those which did not respond to the last round of
2505 /// This may be called on any timescale you want, however, roughly once every ten seconds is
2506 /// preferred. The call rate determines both how often we send a ping to our peers and how much
2507 /// time they have to respond before we disconnect them.
2509 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2512 /// [`send_data`]: SocketDescriptor::send_data
2513 pub fn timer_tick_occurred(&self) {
2514 let mut descriptors_needing_disconnect = Vec::new();
2516 let peers_lock = self.peers.read().unwrap();
2518 self.update_gossip_backlogged();
2519 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2521 for (descriptor, peer_mutex) in peers_lock.iter() {
2522 let mut peer = peer_mutex.lock().unwrap();
2523 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2525 if !peer.handshake_complete() {
2526 // The peer needs to complete its handshake before we can exchange messages. We
2527 // give peers one timer tick to complete handshake, reusing
2528 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2529 // for handshake completion.
2530 if peer.awaiting_pong_timer_tick_intervals != 0 {
2531 descriptors_needing_disconnect.push(descriptor.clone());
2533 peer.awaiting_pong_timer_tick_intervals = 1;
2537 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2538 debug_assert!(peer.their_node_id.is_some());
2540 loop { // Used as a `goto` to skip writing a Ping message.
2541 if peer.awaiting_pong_timer_tick_intervals == -1 {
2542 // Magic value set in `maybe_send_extra_ping`.
2543 peer.awaiting_pong_timer_tick_intervals = 1;
2544 peer.received_message_since_timer_tick = false;
2548 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2549 || peer.awaiting_pong_timer_tick_intervals as u64 >
2550 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2552 descriptors_needing_disconnect.push(descriptor.clone());
2555 peer.received_message_since_timer_tick = false;
2557 if peer.awaiting_pong_timer_tick_intervals > 0 {
2558 peer.awaiting_pong_timer_tick_intervals += 1;
2562 peer.awaiting_pong_timer_tick_intervals = 1;
2563 let ping = msgs::Ping {
2567 self.enqueue_message(&mut *peer, &ping);
2570 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2574 if !descriptors_needing_disconnect.is_empty() {
2576 let mut peers_lock = self.peers.write().unwrap();
2577 for descriptor in descriptors_needing_disconnect {
2578 if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2579 let peer = peer_mutex.lock().unwrap();
2580 if let Some((node_id, _)) = peer.their_node_id {
2581 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2583 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2591 // Messages of up to 64KB should never end up more than half full with addresses, as that would
2592 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2593 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2595 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (SocketAddress::MAX_LEN as u32 + 1) / 2;
2597 // ...by failing to compile if the number of addresses that would be half of a message is
2598 // smaller than 100:
2599 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2601 /// Generates a signed node_announcement from the given arguments, sending it to all connected
2602 /// peers. Note that peers will likely ignore this message unless we have at least one public
2603 /// channel which has at least six confirmations on-chain.
2605 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2606 /// node to humans. They carry no in-protocol meaning.
2608 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2609 /// accepts incoming connections. These will be included in the node_announcement, publicly
2610 /// tying these addresses together and to this node. If you wish to preserve user privacy,
2611 /// addresses should likely contain only Tor Onion addresses.
2613 /// Panics if `addresses` is absurdly large (more than 100).
2615 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2616 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<SocketAddress>) {
2617 if addresses.len() > 100 {
2618 panic!("More than half the message size was taken up by public addresses!");
2621 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2622 // addresses be sorted for future compatibility.
2623 addresses.sort_by_key(|addr| addr.get_id());
2625 let features = self.message_handler.chan_handler.provided_node_features()
2626 | self.message_handler.route_handler.provided_node_features()
2627 | self.message_handler.onion_message_handler.provided_node_features()
2628 | self.message_handler.custom_message_handler.provided_node_features();
2629 let announcement = msgs::UnsignedNodeAnnouncement {
2631 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2632 node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2634 alias: NodeAlias(alias),
2636 excess_address_data: Vec::new(),
2637 excess_data: Vec::new(),
2639 let node_announce_sig = match self.node_signer.sign_gossip_message(
2640 msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2644 log_error!(self.logger, "Failed to generate signature for node_announcement");
2649 let msg = msgs::NodeAnnouncement {
2650 signature: node_announce_sig,
2651 contents: announcement
2654 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2655 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2656 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2660 fn is_gossip_msg(type_id: u16) -> bool {
2662 msgs::ChannelAnnouncement::TYPE |
2663 msgs::ChannelUpdate::TYPE |
2664 msgs::NodeAnnouncement::TYPE |
2665 msgs::QueryChannelRange::TYPE |
2666 msgs::ReplyChannelRange::TYPE |
2667 msgs::QueryShortChannelIds::TYPE |
2668 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2675 use crate::sign::{NodeSigner, Recipient};
2678 use crate::ln::types::ChannelId;
2679 use crate::ln::features::{InitFeatures, NodeFeatures};
2680 use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2681 use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses, ErroringMessageHandler, MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER};
2682 use crate::ln::{msgs, wire};
2683 use crate::ln::msgs::{LightningError, SocketAddress};
2684 use crate::util::test_utils;
2686 use bitcoin::Network;
2687 use bitcoin::blockdata::constants::ChainHash;
2688 use bitcoin::secp256k1::{PublicKey, SecretKey};
2690 use crate::sync::{Arc, Mutex};
2691 use core::convert::Infallible;
2692 use core::sync::atomic::{AtomicBool, Ordering};
2694 #[allow(unused_imports)]
2695 use crate::prelude::*;
2698 struct FileDescriptor {
2700 outbound_data: Arc<Mutex<Vec<u8>>>,
2701 disconnect: Arc<AtomicBool>,
2703 impl PartialEq for FileDescriptor {
2704 fn eq(&self, other: &Self) -> bool {
2708 impl Eq for FileDescriptor { }
2709 impl core::hash::Hash for FileDescriptor {
2710 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2711 self.fd.hash(hasher)
2715 impl SocketDescriptor for FileDescriptor {
2716 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2717 self.outbound_data.lock().unwrap().extend_from_slice(data);
2721 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2724 struct PeerManagerCfg {
2725 chan_handler: test_utils::TestChannelMessageHandler,
2726 routing_handler: test_utils::TestRoutingMessageHandler,
2727 custom_handler: TestCustomMessageHandler,
2728 logger: test_utils::TestLogger,
2729 node_signer: test_utils::TestNodeSigner,
2732 struct TestCustomMessageHandler {
2733 features: InitFeatures,
2736 impl wire::CustomMessageReader for TestCustomMessageHandler {
2737 type CustomMessage = Infallible;
2738 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2743 impl CustomMessageHandler for TestCustomMessageHandler {
2744 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2748 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2750 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2752 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2753 self.features.clone()
2757 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2758 let mut cfgs = Vec::new();
2759 for i in 0..peer_count {
2760 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2762 let mut feature_bits = vec![0u8; 33];
2763 feature_bits[32] = 0b00000001;
2764 InitFeatures::from_le_bytes(feature_bits)
2768 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2769 logger: test_utils::TestLogger::new(),
2770 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2771 custom_handler: TestCustomMessageHandler { features },
2772 node_signer: test_utils::TestNodeSigner::new(node_secret),
2780 fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2781 let mut cfgs = Vec::new();
2782 for i in 0..peer_count {
2783 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2785 let mut feature_bits = vec![0u8; 33 + i + 1];
2786 feature_bits[33 + i] = 0b00000001;
2787 InitFeatures::from_le_bytes(feature_bits)
2791 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2792 logger: test_utils::TestLogger::new(),
2793 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2794 custom_handler: TestCustomMessageHandler { features },
2795 node_signer: test_utils::TestNodeSigner::new(node_secret),
2803 fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2804 let mut cfgs = Vec::new();
2805 for i in 0..peer_count {
2806 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2807 let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2808 let network = ChainHash::from(&[i as u8; 32]);
2811 chan_handler: test_utils::TestChannelMessageHandler::new(network),
2812 logger: test_utils::TestLogger::new(),
2813 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2814 custom_handler: TestCustomMessageHandler { features },
2815 node_signer: test_utils::TestNodeSigner::new(node_secret),
2823 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>> {
2824 let mut peers = Vec::new();
2825 for i in 0..peer_count {
2826 let ephemeral_bytes = [i as u8; 32];
2827 let msg_handler = MessageHandler {
2828 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2829 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2831 let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2838 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) {
2839 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2840 let mut fd_a = FileDescriptor {
2841 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2842 disconnect: Arc::new(AtomicBool::new(false)),
2844 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2845 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2846 let features_a = peer_a.init_features(&id_b);
2847 let features_b = peer_b.init_features(&id_a);
2848 let mut fd_b = FileDescriptor {
2849 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2850 disconnect: Arc::new(AtomicBool::new(false)),
2852 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2853 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2854 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2855 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2856 peer_a.process_events();
2858 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2859 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2861 peer_b.process_events();
2862 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2863 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2865 peer_a.process_events();
2866 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2867 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2869 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().counterparty_node_id, id_b);
2870 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().socket_address, Some(addr_b));
2871 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().init_features, features_b);
2872 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().counterparty_node_id, id_a);
2873 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().socket_address, Some(addr_a));
2874 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().init_features, features_a);
2875 (fd_a.clone(), fd_b.clone())
2879 #[cfg(feature = "std")]
2880 fn fuzz_threaded_connections() {
2881 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2882 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2883 // with our internal map consistency, and is a generally good smoke test of disconnection.
2884 let cfgs = Arc::new(create_peermgr_cfgs(2));
2885 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2886 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2888 let start_time = std::time::Instant::now();
2889 macro_rules! spawn_thread { ($id: expr) => { {
2890 let peers = Arc::clone(&peers);
2891 let cfgs = Arc::clone(&cfgs);
2892 std::thread::spawn(move || {
2894 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2895 let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2896 let mut fd_a = FileDescriptor {
2897 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2898 disconnect: Arc::new(AtomicBool::new(false)),
2900 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2901 let mut fd_b = FileDescriptor {
2902 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2903 disconnect: Arc::new(AtomicBool::new(false)),
2905 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2906 let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2907 peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2908 if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2910 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2911 peers[0].process_events();
2912 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2913 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2914 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2916 peers[1].process_events();
2917 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2918 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2919 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2921 cfgs[0].chan_handler.pending_events.lock().unwrap()
2922 .push(crate::events::MessageSendEvent::SendShutdown {
2923 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2924 msg: msgs::Shutdown {
2925 channel_id: ChannelId::new_zero(),
2926 scriptpubkey: bitcoin::ScriptBuf::new(),
2929 cfgs[1].chan_handler.pending_events.lock().unwrap()
2930 .push(crate::events::MessageSendEvent::SendShutdown {
2931 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2932 msg: msgs::Shutdown {
2933 channel_id: ChannelId::new_zero(),
2934 scriptpubkey: bitcoin::ScriptBuf::new(),
2939 peers[0].timer_tick_occurred();
2940 peers[1].timer_tick_occurred();
2944 peers[0].socket_disconnected(&fd_a);
2945 peers[1].socket_disconnected(&fd_b);
2947 std::thread::sleep(std::time::Duration::from_micros(1));
2951 let thrd_a = spawn_thread!(1);
2952 let thrd_b = spawn_thread!(2);
2954 thrd_a.join().unwrap();
2955 thrd_b.join().unwrap();
2959 fn test_feature_incompatible_peers() {
2960 let cfgs = create_peermgr_cfgs(2);
2961 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2963 let peers = create_network(2, &cfgs);
2964 let incompatible_peers = create_network(2, &incompatible_cfgs);
2965 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2966 for (peer_a, peer_b) in peer_pairs.iter() {
2967 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2968 let mut fd_a = FileDescriptor {
2969 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2970 disconnect: Arc::new(AtomicBool::new(false)),
2972 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2973 let mut fd_b = FileDescriptor {
2974 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2975 disconnect: Arc::new(AtomicBool::new(false)),
2977 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2978 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2979 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2980 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2981 peer_a.process_events();
2983 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2984 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2986 peer_b.process_events();
2987 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2989 // Should fail because of unknown required features
2990 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2995 fn test_chain_incompatible_peers() {
2996 let cfgs = create_peermgr_cfgs(2);
2997 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
2999 let peers = create_network(2, &cfgs);
3000 let incompatible_peers = create_network(2, &incompatible_cfgs);
3001 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
3002 for (peer_a, peer_b) in peer_pairs.iter() {
3003 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
3004 let mut fd_a = FileDescriptor {
3005 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3006 disconnect: Arc::new(AtomicBool::new(false)),
3008 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
3009 let mut fd_b = FileDescriptor {
3010 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3011 disconnect: Arc::new(AtomicBool::new(false)),
3013 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
3014 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
3015 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
3016 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
3017 peer_a.process_events();
3019 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3020 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
3022 peer_b.process_events();
3023 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3025 // Should fail because of incompatible chains
3026 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
3031 fn test_disconnect_peer() {
3032 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3033 // push a DisconnectPeer event to remove the node flagged by id
3034 let cfgs = create_peermgr_cfgs(2);
3035 let peers = create_network(2, &cfgs);
3036 establish_connection(&peers[0], &peers[1]);
3037 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3039 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
3040 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
3042 action: msgs::ErrorAction::DisconnectPeer { msg: None },
3045 peers[0].process_events();
3046 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3050 fn test_send_simple_msg() {
3051 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3052 // push a message from one peer to another.
3053 let cfgs = create_peermgr_cfgs(2);
3054 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3055 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3056 let mut peers = create_network(2, &cfgs);
3057 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3058 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3060 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
3062 let msg = msgs::Shutdown { channel_id: ChannelId::from_bytes([42; 32]), scriptpubkey: bitcoin::ScriptBuf::new() };
3063 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
3064 node_id: their_id, msg: msg.clone()
3066 peers[0].message_handler.chan_handler = &a_chan_handler;
3068 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
3069 peers[1].message_handler.chan_handler = &b_chan_handler;
3071 peers[0].process_events();
3073 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3074 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3078 fn test_non_init_first_msg() {
3079 // Simple test of the first message received over a connection being something other than
3080 // Init. This results in an immediate disconnection, which previously included a spurious
3081 // peer_disconnected event handed to event handlers (which would panic in
3082 // `TestChannelMessageHandler` here).
3083 let cfgs = create_peermgr_cfgs(2);
3084 let peers = create_network(2, &cfgs);
3086 let mut fd_dup = FileDescriptor {
3087 fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
3088 disconnect: Arc::new(AtomicBool::new(false)),
3090 let addr_dup = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1003};
3091 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
3092 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
3094 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
3095 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
3096 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
3097 peers[0].process_events();
3099 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
3100 let (act_three, _) =
3101 dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
3102 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
3104 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
3105 let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg);
3106 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
3110 fn test_disconnect_all_peer() {
3111 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3112 // then calls disconnect_all_peers
3113 let cfgs = create_peermgr_cfgs(2);
3114 let peers = create_network(2, &cfgs);
3115 establish_connection(&peers[0], &peers[1]);
3116 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3118 peers[0].disconnect_all_peers();
3119 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3123 fn test_timer_tick_occurred() {
3124 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
3125 let cfgs = create_peermgr_cfgs(2);
3126 let peers = create_network(2, &cfgs);
3127 establish_connection(&peers[0], &peers[1]);
3128 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3130 // peers[0] awaiting_pong is set to true, but the Peer is still connected
3131 peers[0].timer_tick_occurred();
3132 peers[0].process_events();
3133 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3135 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
3136 peers[0].timer_tick_occurred();
3137 peers[0].process_events();
3138 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3142 fn test_do_attempt_write_data() {
3143 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
3144 let cfgs = create_peermgr_cfgs(2);
3145 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3146 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3147 let peers = create_network(2, &cfgs);
3149 // By calling establish_connect, we trigger do_attempt_write_data between
3150 // the peers. Previously this function would mistakenly enter an infinite loop
3151 // when there were more channel messages available than could fit into a peer's
3152 // buffer. This issue would now be detected by this test (because we use custom
3153 // RoutingMessageHandlers that intentionally return more channel messages
3154 // than can fit into a peer's buffer).
3155 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3157 // Make each peer to read the messages that the other peer just wrote to them. Note that
3158 // due to the max-message-before-ping limits this may take a few iterations to complete.
3159 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
3160 peers[1].process_events();
3161 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3162 assert!(!a_read_data.is_empty());
3164 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
3165 peers[0].process_events();
3167 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3168 assert!(!b_read_data.is_empty());
3169 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
3171 peers[0].process_events();
3172 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
3175 // Check that each peer has received the expected number of channel updates and channel
3177 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3178 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3179 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3180 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3184 fn test_handshake_timeout() {
3185 // Tests that we time out a peer still waiting on handshake completion after a full timer
3187 let cfgs = create_peermgr_cfgs(2);
3188 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3189 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3190 let peers = create_network(2, &cfgs);
3192 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
3193 let mut fd_a = FileDescriptor {
3194 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3195 disconnect: Arc::new(AtomicBool::new(false)),
3197 let mut fd_b = FileDescriptor {
3198 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3199 disconnect: Arc::new(AtomicBool::new(false)),
3201 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3202 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3204 // If we get a single timer tick before completion, that's fine
3205 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3206 peers[0].timer_tick_occurred();
3207 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3209 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3210 peers[0].process_events();
3211 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3212 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3213 peers[1].process_events();
3215 // ...but if we get a second timer tick, we should disconnect the peer
3216 peers[0].timer_tick_occurred();
3217 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3219 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3220 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3224 fn test_inbound_conn_handshake_complete_awaiting_pong() {
3225 // Test that we do not disconnect an outbound peer after the noise handshake completes due
3226 // to a pong timeout for a ping that was never sent if a timer tick fires after we send act
3227 // two of the noise handshake along with our init message but before we receive their init
3229 let logger = test_utils::TestLogger::new();
3230 let node_signer_a = test_utils::TestNodeSigner::new(SecretKey::from_slice(&[42; 32]).unwrap());
3231 let node_signer_b = test_utils::TestNodeSigner::new(SecretKey::from_slice(&[43; 32]).unwrap());
3232 let peer_a = PeerManager::new(MessageHandler {
3233 chan_handler: ErroringMessageHandler::new(),
3234 route_handler: IgnoringMessageHandler {},
3235 onion_message_handler: IgnoringMessageHandler {},
3236 custom_message_handler: IgnoringMessageHandler {},
3237 }, 0, &[0; 32], &logger, &node_signer_a);
3238 let peer_b = PeerManager::new(MessageHandler {
3239 chan_handler: ErroringMessageHandler::new(),
3240 route_handler: IgnoringMessageHandler {},
3241 onion_message_handler: IgnoringMessageHandler {},
3242 custom_message_handler: IgnoringMessageHandler {},
3243 }, 0, &[1; 32], &logger, &node_signer_b);
3245 let a_id = node_signer_a.get_node_id(Recipient::Node).unwrap();
3246 let mut fd_a = FileDescriptor {
3247 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3248 disconnect: Arc::new(AtomicBool::new(false)),
3250 let mut fd_b = FileDescriptor {
3251 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3252 disconnect: Arc::new(AtomicBool::new(false)),
3255 // Exchange messages with both peers until they both complete the init handshake.
3256 let act_one = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3257 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
3259 assert_eq!(peer_a.read_event(&mut fd_a, &act_one).unwrap(), false);
3260 peer_a.process_events();
3262 let act_two = fd_a.outbound_data.lock().unwrap().split_off(0);
3263 assert_eq!(peer_b.read_event(&mut fd_b, &act_two).unwrap(), false);
3264 peer_b.process_events();
3266 // Calling this here triggers the race on inbound connections.
3267 peer_b.timer_tick_occurred();
3269 let act_three_with_init_b = fd_b.outbound_data.lock().unwrap().split_off(0);
3270 assert!(!peer_a.peers.read().unwrap().get(&fd_a).unwrap().lock().unwrap().handshake_complete());
3271 assert_eq!(peer_a.read_event(&mut fd_a, &act_three_with_init_b).unwrap(), false);
3272 peer_a.process_events();
3273 assert!(peer_a.peers.read().unwrap().get(&fd_a).unwrap().lock().unwrap().handshake_complete());
3275 let init_a = fd_a.outbound_data.lock().unwrap().split_off(0);
3276 assert!(!init_a.is_empty());
3278 assert!(!peer_b.peers.read().unwrap().get(&fd_b).unwrap().lock().unwrap().handshake_complete());
3279 assert_eq!(peer_b.read_event(&mut fd_b, &init_a).unwrap(), false);
3280 peer_b.process_events();
3281 assert!(peer_b.peers.read().unwrap().get(&fd_b).unwrap().lock().unwrap().handshake_complete());
3283 // Make sure we're still connected.
3284 assert_eq!(peer_b.peers.read().unwrap().len(), 1);
3286 // B should send a ping on the first timer tick after `handshake_complete`.
3287 assert!(fd_b.outbound_data.lock().unwrap().split_off(0).is_empty());
3288 peer_b.timer_tick_occurred();
3289 peer_b.process_events();
3290 assert!(!fd_b.outbound_data.lock().unwrap().split_off(0).is_empty());
3292 let mut send_warning = || {
3294 let peers = peer_a.peers.read().unwrap();
3295 let mut peer_b = peers.get(&fd_a).unwrap().lock().unwrap();
3296 peer_a.enqueue_message(&mut peer_b, &msgs::WarningMessage {
3297 channel_id: ChannelId([0; 32]),
3298 data: "no disconnect plz".to_string(),
3301 peer_a.process_events();
3302 let msg = fd_a.outbound_data.lock().unwrap().split_off(0);
3303 assert!(!msg.is_empty());
3304 assert_eq!(peer_b.read_event(&mut fd_b, &msg).unwrap(), false);
3305 peer_b.process_events();
3308 // Fire more ticks until we reach the pong timeout. We send any message except pong to
3309 // pretend the connection is still alive.
3311 for _ in 0..MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER {
3312 peer_b.timer_tick_occurred();
3315 assert_eq!(peer_b.peers.read().unwrap().len(), 1);
3317 // One more tick should enforce the pong timeout.
3318 peer_b.timer_tick_occurred();
3319 assert_eq!(peer_b.peers.read().unwrap().len(), 0);
3323 fn test_filter_addresses(){
3324 // Tests the filter_addresses function.
3327 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 0, 0], port: 1000};
3328 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3329 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 255, 201], port: 1000};
3330 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3331 let ip_address = SocketAddress::TcpIpV4{addr: [10, 255, 255, 255], port: 1000};
3332 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3335 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 0, 0], port: 1000};
3336 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3337 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 255, 187], port: 1000};
3338 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3339 let ip_address = SocketAddress::TcpIpV4{addr: [0, 255, 255, 255], port: 1000};
3340 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3343 let ip_address = SocketAddress::TcpIpV4{addr: [100, 64, 0, 0], port: 1000};
3344 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3345 let ip_address = SocketAddress::TcpIpV4{addr: [100, 78, 255, 0], port: 1000};
3346 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3347 let ip_address = SocketAddress::TcpIpV4{addr: [100, 127, 255, 255], port: 1000};
3348 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3351 let ip_address = SocketAddress::TcpIpV4{addr: [127, 0, 0, 0], port: 1000};
3352 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3353 let ip_address = SocketAddress::TcpIpV4{addr: [127, 65, 73, 0], port: 1000};
3354 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3355 let ip_address = SocketAddress::TcpIpV4{addr: [127, 255, 255, 255], port: 1000};
3356 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3359 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 0, 0], port: 1000};
3360 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3361 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 221, 101], port: 1000};
3362 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3363 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 255, 255], port: 1000};
3364 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3367 let ip_address = SocketAddress::TcpIpV4{addr: [172, 16, 0, 0], port: 1000};
3368 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3369 let ip_address = SocketAddress::TcpIpV4{addr: [172, 27, 101, 23], port: 1000};
3370 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3371 let ip_address = SocketAddress::TcpIpV4{addr: [172, 31, 255, 255], port: 1000};
3372 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3375 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 0, 0], port: 1000};
3376 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3377 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 205, 159], port: 1000};
3378 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3379 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 255, 255], port: 1000};
3380 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3382 // For (192.88.99/24)
3383 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 0], port: 1000};
3384 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3385 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 140], port: 1000};
3386 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3387 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 255], port: 1000};
3388 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3390 // For other IPv4 addresses
3391 let ip_address = SocketAddress::TcpIpV4{addr: [188, 255, 99, 0], port: 1000};
3392 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3393 let ip_address = SocketAddress::TcpIpV4{addr: [123, 8, 129, 14], port: 1000};
3394 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3395 let ip_address = SocketAddress::TcpIpV4{addr: [2, 88, 9, 255], port: 1000};
3396 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3399 let ip_address = SocketAddress::TcpIpV6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3400 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3401 let ip_address = SocketAddress::TcpIpV6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3402 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3403 let ip_address = SocketAddress::TcpIpV6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3404 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3406 // For other IPv6 addresses
3407 let ip_address = SocketAddress::TcpIpV6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3408 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3409 let ip_address = SocketAddress::TcpIpV6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3410 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3411 let ip_address = SocketAddress::TcpIpV6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3412 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3415 assert_eq!(filter_addresses(None), None);
3419 #[cfg(feature = "std")]
3420 fn test_process_events_multithreaded() {
3421 use std::time::{Duration, Instant};
3422 // Test that `process_events` getting called on multiple threads doesn't generate too many
3424 // Each time `process_events` goes around the loop we call
3425 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3426 // Because the loop should go around once more after a call which fails to take the
3427 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3428 // should never observe there having been more than 2 loop iterations.
3429 // Further, because the last thread to exit will call `process_events` before returning, we
3430 // should always have at least one count at the end.
3431 let cfg = Arc::new(create_peermgr_cfgs(1));
3432 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3433 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3435 let exit_flag = Arc::new(AtomicBool::new(false));
3436 macro_rules! spawn_thread { () => { {
3437 let thread_cfg = Arc::clone(&cfg);
3438 let thread_peer = Arc::clone(&peer);
3439 let thread_exit = Arc::clone(&exit_flag);
3440 std::thread::spawn(move || {
3441 while !thread_exit.load(Ordering::Acquire) {
3442 thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3443 thread_peer.process_events();
3444 std::thread::sleep(Duration::from_micros(1));
3449 let thread_a = spawn_thread!();
3450 let thread_b = spawn_thread!();
3451 let thread_c = spawn_thread!();
3453 let start_time = Instant::now();
3454 while start_time.elapsed() < Duration::from_millis(100) {
3455 let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3457 std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3460 exit_flag.store(true, Ordering::Release);
3461 thread_a.join().unwrap();
3462 thread_b.join().unwrap();
3463 thread_c.join().unwrap();
3464 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);