1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Top level peer message handling and socket handling logic lives here.
12 //! Instead of actually servicing sockets ourselves we require that you implement the
13 //! SocketDescriptor interface and use that to receive actions which you should perform on the
14 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
15 //! call into the provided message handlers (probably a ChannelManager and P2PGossipSync) with
16 //! messages they should handle, and encoding/sending response messages.
18 use bitcoin::blockdata::constants::ChainHash;
19 use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
21 use crate::sign::{NodeSigner, Recipient};
22 use crate::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
23 use crate::ln::ChannelId;
24 use crate::ln::features::{InitFeatures, NodeFeatures};
26 use crate::ln::msgs::{ChannelMessageHandler, LightningError, SocketAddress, OnionMessageHandler, RoutingMessageHandler};
27 use crate::util::ser::{VecWriter, Writeable, Writer};
28 use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor, NextNoiseStep, MessageBuf, MSG_BUF_ALLOC_SIZE};
30 use crate::ln::wire::{Encode, Type};
31 use crate::onion_message::messenger::{CustomOnionMessageHandler, PendingOnionMessage};
32 use crate::onion_message::offers::{OffersMessage, OffersMessageHandler};
33 use crate::onion_message::packet::OnionMessageContents;
34 use crate::routing::gossip::{NodeId, NodeAlias};
35 use crate::util::atomic_counter::AtomicCounter;
36 use crate::util::logger::{Level, Logger, WithContext};
37 use crate::util::string::PrintableString;
39 use crate::prelude::*;
41 use alloc::collections::VecDeque;
42 use crate::sync::{Mutex, MutexGuard, FairRwLock};
43 use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering};
44 use core::{cmp, hash, fmt, mem};
46 use core::convert::Infallible;
47 #[cfg(feature = "std")]
49 #[cfg(not(c_bindings))]
51 crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager},
52 crate::onion_message::messenger::{SimpleArcOnionMessenger, SimpleRefOnionMessenger},
53 crate::routing::gossip::{NetworkGraph, P2PGossipSync},
54 crate::sign::KeysManager,
58 use bitcoin::hashes::sha256::Hash as Sha256;
59 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
60 use bitcoin::hashes::{HashEngine, Hash};
62 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
64 /// [BOLT 1] specifies a custom message type range for use with experimental or application-specific
65 /// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the
66 /// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler.
68 /// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
69 /// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message
70 pub trait CustomMessageHandler: wire::CustomMessageReader {
71 /// Handles the given message sent from `sender_node_id`, possibly producing messages for
72 /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`]
74 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
76 /// Returns the list of pending messages that were generated by the handler, clearing the list
77 /// in the process. Each message is paired with the node id of the intended recipient. If no
78 /// connection to the node exists, then the message is simply not sent.
79 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
81 /// Gets the node feature flags which this handler itself supports. All available handlers are
82 /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
83 /// which are broadcasted in our [`NodeAnnouncement`] message.
85 /// [`NodeAnnouncement`]: crate::ln::msgs::NodeAnnouncement
86 fn provided_node_features(&self) -> NodeFeatures;
88 /// Gets the init feature flags which should be sent to the given peer. All available handlers
89 /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
90 /// which are sent in our [`Init`] message.
92 /// [`Init`]: crate::ln::msgs::Init
93 fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
96 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
97 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
98 pub struct IgnoringMessageHandler{}
99 impl EventsProvider for IgnoringMessageHandler {
100 fn process_pending_events<H: Deref>(&self, _handler: H) where H::Target: EventHandler {}
102 impl MessageSendEventsProvider for IgnoringMessageHandler {
103 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
105 impl RoutingMessageHandler for IgnoringMessageHandler {
106 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
107 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
108 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
109 fn get_next_channel_announcement(&self, _starting_point: u64) ->
110 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
111 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
112 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
113 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
114 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
115 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
116 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
117 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
118 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
119 let mut features = InitFeatures::empty();
120 features.set_gossip_queries_optional();
123 fn processing_queue_high(&self) -> bool { false }
125 impl OnionMessageHandler for IgnoringMessageHandler {
126 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
127 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
128 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
129 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
130 fn timer_tick_occurred(&self) {}
131 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
132 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
133 InitFeatures::empty()
136 impl OffersMessageHandler for IgnoringMessageHandler {
137 fn handle_message(&self, _msg: OffersMessage) -> Option<OffersMessage> { None }
139 impl CustomOnionMessageHandler for IgnoringMessageHandler {
140 type CustomMessage = Infallible;
141 fn handle_custom_message(&self, _msg: Infallible) -> Option<Infallible> {
142 // Since we always return `None` in the read the handle method should never be called.
145 fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
148 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Infallible>> {
153 impl OnionMessageContents for Infallible {
154 fn tlv_type(&self) -> u64 { unreachable!(); }
157 impl Deref for IgnoringMessageHandler {
158 type Target = IgnoringMessageHandler;
159 fn deref(&self) -> &Self { self }
162 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
163 // method that takes self for it.
164 impl wire::Type for Infallible {
165 fn type_id(&self) -> u16 {
169 impl Writeable for Infallible {
170 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
175 impl wire::CustomMessageReader for IgnoringMessageHandler {
176 type CustomMessage = Infallible;
177 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
182 impl CustomMessageHandler for IgnoringMessageHandler {
183 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
184 // Since we always return `None` in the read the handle method should never be called.
188 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
190 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
192 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
193 InitFeatures::empty()
197 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
198 /// You can provide one of these as the route_handler in a MessageHandler.
199 pub struct ErroringMessageHandler {
200 message_queue: Mutex<Vec<MessageSendEvent>>
202 impl ErroringMessageHandler {
203 /// Constructs a new ErroringMessageHandler
204 pub fn new() -> Self {
205 Self { message_queue: Mutex::new(Vec::new()) }
207 fn push_error(&self, node_id: &PublicKey, channel_id: ChannelId) {
208 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
209 action: msgs::ErrorAction::SendErrorMessage {
210 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
212 node_id: node_id.clone(),
216 impl MessageSendEventsProvider for ErroringMessageHandler {
217 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
218 let mut res = Vec::new();
219 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
223 impl ChannelMessageHandler for ErroringMessageHandler {
224 // Any messages which are related to a specific channel generate an error message to let the
225 // peer know we don't care about channels.
226 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
227 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
229 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
230 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
232 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
233 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
235 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
236 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
238 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
239 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
241 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
242 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
244 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
245 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
247 fn handle_stfu(&self, their_node_id: &PublicKey, msg: &msgs::Stfu) {
248 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
250 fn handle_splice(&self, their_node_id: &PublicKey, msg: &msgs::Splice) {
251 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
253 fn handle_splice_ack(&self, their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
254 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
256 fn handle_splice_locked(&self, their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
257 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
259 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
260 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
262 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
263 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
265 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
266 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
268 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
269 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
271 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
272 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
274 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
275 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
277 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
278 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
280 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
281 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
283 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
284 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
286 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
287 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
288 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
289 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
290 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
291 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
292 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
293 // Set a number of features which various nodes may require to talk to us. It's totally
294 // reasonable to indicate we "support" all kinds of channel features...we just reject all
296 let mut features = InitFeatures::empty();
297 features.set_data_loss_protect_optional();
298 features.set_upfront_shutdown_script_optional();
299 features.set_variable_length_onion_optional();
300 features.set_static_remote_key_optional();
301 features.set_payment_secret_optional();
302 features.set_basic_mpp_optional();
303 features.set_wumbo_optional();
304 features.set_shutdown_any_segwit_optional();
305 features.set_channel_type_optional();
306 features.set_scid_privacy_optional();
307 features.set_zero_conf_optional();
308 features.set_route_blinding_optional();
312 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
313 // We don't enforce any chains upon peer connection for `ErroringMessageHandler` and leave it up
314 // to users of `ErroringMessageHandler` to make decisions on network compatiblility.
315 // There's not really any way to pull in specific networks here, and hardcoding can cause breakages.
319 fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
320 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
323 fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
324 ErroringMessageHandler::push_error(self, their_node_id, msg.common_fields.temporary_channel_id);
327 fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
328 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
331 fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
332 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
335 fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
336 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
339 fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
340 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
343 fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &msgs::TxComplete) {
344 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
347 fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
348 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
351 fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
352 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
355 fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
356 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
359 fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &msgs::TxAbort) {
360 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
364 impl Deref for ErroringMessageHandler {
365 type Target = ErroringMessageHandler;
366 fn deref(&self) -> &Self { self }
369 /// Provides references to trait impls which handle different types of messages.
370 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref, CustomM: Deref> where
371 CM::Target: ChannelMessageHandler,
372 RM::Target: RoutingMessageHandler,
373 OM::Target: OnionMessageHandler,
374 CustomM::Target: CustomMessageHandler,
376 /// A message handler which handles messages specific to channels. Usually this is just a
377 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
379 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
380 pub chan_handler: CM,
381 /// A message handler which handles messages updating our knowledge of the network channel
382 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
384 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
385 pub route_handler: RM,
387 /// A message handler which handles onion messages. This should generally be an
388 /// [`OnionMessenger`], but can also be an [`IgnoringMessageHandler`].
390 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
391 pub onion_message_handler: OM,
393 /// A message handler which handles custom messages. The only LDK-provided implementation is
394 /// [`IgnoringMessageHandler`].
395 pub custom_message_handler: CustomM,
398 /// Provides an object which can be used to send data to and which uniquely identifies a connection
399 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
400 /// implement Hash to meet the PeerManager API.
402 /// For efficiency, [`Clone`] should be relatively cheap for this type.
404 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
405 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
406 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
407 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
408 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
409 /// to simply use another value which is guaranteed to be globally unique instead.
410 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
411 /// Attempts to send some data from the given slice to the peer.
413 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
414 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
415 /// called and further write attempts may occur until that time.
417 /// If the returned size is smaller than `data.len()`, a
418 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
419 /// written. Additionally, until a `send_data` event completes fully, no further
420 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
421 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
424 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
425 /// (indicating that read events should be paused to prevent DoS in the send buffer),
426 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
427 /// `resume_read` of false carries no meaning, and should not cause any action.
428 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
429 /// Disconnect the socket pointed to by this SocketDescriptor.
431 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
432 /// call (doing so is a noop).
433 fn disconnect_socket(&mut self);
436 /// Details of a connected peer as returned by [`PeerManager::list_peers`].
437 pub struct PeerDetails {
438 /// The node id of the peer.
440 /// For outbound connections, this [`PublicKey`] will be the same as the `their_node_id` parameter
441 /// passed in to [`PeerManager::new_outbound_connection`].
442 pub counterparty_node_id: PublicKey,
443 /// The socket address the peer provided in the initial handshake.
445 /// Will only be `Some` if an address had been previously provided to
446 /// [`PeerManager::new_outbound_connection`] or [`PeerManager::new_inbound_connection`].
447 pub socket_address: Option<SocketAddress>,
448 /// The features the peer provided in the initial handshake.
449 pub init_features: InitFeatures,
450 /// Indicates the direction of the peer connection.
452 /// Will be `true` for inbound connections, and `false` for outbound connections.
453 pub is_inbound_connection: bool,
456 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
457 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
460 pub struct PeerHandleError { }
461 impl fmt::Debug for PeerHandleError {
462 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
463 formatter.write_str("Peer Sent Invalid Data")
466 impl fmt::Display for PeerHandleError {
467 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
468 formatter.write_str("Peer Sent Invalid Data")
472 #[cfg(feature = "std")]
473 impl error::Error for PeerHandleError {
474 fn description(&self) -> &str {
475 "Peer Sent Invalid Data"
479 enum InitSyncTracker{
481 ChannelsSyncing(u64),
482 NodesSyncing(NodeId),
485 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
486 /// forwarding gossip messages to peers altogether.
487 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
489 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
490 /// we have fewer than this many messages in the outbound buffer again.
491 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
492 /// refilled as we send bytes.
493 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
494 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
496 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
498 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
499 /// the socket receive buffer before receiving the ping.
501 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
502 /// including any network delays, outbound traffic, or the same for messages from other peers.
504 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
505 /// per connected peer to respond to a ping, as long as they send us at least one message during
506 /// each tick, ensuring we aren't actually just disconnected.
507 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
510 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
511 /// two connected peers, assuming most LDK-running systems have at least two cores.
512 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
514 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
515 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
516 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
517 /// process before the next ping.
519 /// Note that we continue responding to other messages even after we've sent this many messages, so
520 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
521 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
522 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
525 channel_encryptor: PeerChannelEncryptor,
526 /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
527 /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
528 their_node_id: Option<(PublicKey, NodeId)>,
529 /// The features provided in the peer's [`msgs::Init`] message.
531 /// This is set only after we've processed the [`msgs::Init`] message and called relevant
532 /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
533 /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
535 their_features: Option<InitFeatures>,
536 their_socket_address: Option<SocketAddress>,
538 pending_outbound_buffer: VecDeque<Vec<u8>>,
539 pending_outbound_buffer_first_msg_offset: usize,
540 /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
541 /// prioritize channel messages over them.
543 /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
544 gossip_broadcast_buffer: VecDeque<MessageBuf>,
545 awaiting_write_event: bool,
547 pending_read_buffer: Vec<u8>,
548 pending_read_buffer_pos: usize,
549 pending_read_is_header: bool,
551 sync_status: InitSyncTracker,
553 msgs_sent_since_pong: usize,
554 awaiting_pong_timer_tick_intervals: i64,
555 received_message_since_timer_tick: bool,
556 sent_gossip_timestamp_filter: bool,
558 /// Indicates we've received a `channel_announcement` since the last time we had
559 /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
560 /// `channel_announcement` at all - we set this unconditionally but unset it every time we
561 /// check if we're gossip-processing-backlogged).
562 received_channel_announce_since_backlogged: bool,
564 inbound_connection: bool,
568 /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
569 /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
571 fn handshake_complete(&self) -> bool {
572 self.their_features.is_some()
575 /// Returns true if the channel announcements/updates for the given channel should be
576 /// forwarded to this peer.
577 /// If we are sending our routing table to this peer and we have not yet sent channel
578 /// announcements/updates for the given channel_id then we will send it when we get to that
579 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
580 /// sent the old versions, we should send the update, and so return true here.
581 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
582 if !self.handshake_complete() { return false; }
583 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
584 !self.sent_gossip_timestamp_filter {
587 match self.sync_status {
588 InitSyncTracker::NoSyncRequested => true,
589 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
590 InitSyncTracker::NodesSyncing(_) => true,
594 /// Similar to the above, but for node announcements indexed by node_id.
595 fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
596 if !self.handshake_complete() { return false; }
597 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
598 !self.sent_gossip_timestamp_filter {
601 match self.sync_status {
602 InitSyncTracker::NoSyncRequested => true,
603 InitSyncTracker::ChannelsSyncing(_) => false,
604 InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
608 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
609 /// buffer still has space and we don't need to pause reads to get some writes out.
610 fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
611 if !gossip_processing_backlogged {
612 self.received_channel_announce_since_backlogged = false;
614 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
615 (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
618 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
619 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
620 fn should_buffer_gossip_backfill(&self) -> bool {
621 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
622 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
623 && self.handshake_complete()
626 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
627 /// every time the peer's buffer may have been drained.
628 fn should_buffer_onion_message(&self) -> bool {
629 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
630 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
633 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
634 /// buffer. This is checked every time the peer's buffer may have been drained.
635 fn should_buffer_gossip_broadcast(&self) -> bool {
636 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
637 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
640 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
641 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
642 let total_outbound_buffered =
643 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
645 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
646 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
649 fn set_their_node_id(&mut self, node_id: PublicKey) {
650 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
654 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
655 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
656 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
657 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
658 /// issues such as overly long function definitions.
660 /// This is not exported to bindings users as type aliases aren't supported in most languages.
661 #[cfg(not(c_bindings))]
662 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<
664 Arc<SimpleArcChannelManager<M, T, F, L>>,
665 Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, C, Arc<L>>>,
666 Arc<SimpleArcOnionMessenger<M, T, F, L>>,
668 IgnoringMessageHandler,
672 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
673 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
674 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
675 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
676 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
677 /// helps with issues such as long function definitions.
679 /// This is not exported to bindings users as type aliases aren't supported in most languages.
680 #[cfg(not(c_bindings))]
681 pub type SimpleRefPeerManager<
682 'a, 'b, 'c, 'd, 'e, 'f, 'logger, 'h, 'i, 'j, 'graph, 'k, SD, M, T, F, C, L
685 &'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, M, T, F, L>,
686 &'f P2PGossipSync<&'graph NetworkGraph<&'logger L>, C, &'logger L>,
687 &'h SimpleRefOnionMessenger<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, 'j, 'k, M, T, F, L>,
689 IgnoringMessageHandler,
694 /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or
695 /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather
696 /// than the full set of bounds on [`PeerManager`] itself.
698 /// This is not exported to bindings users as general cover traits aren't useful in other
700 #[allow(missing_docs)]
701 pub trait APeerManager {
702 type Descriptor: SocketDescriptor;
703 type CMT: ChannelMessageHandler + ?Sized;
704 type CM: Deref<Target=Self::CMT>;
705 type RMT: RoutingMessageHandler + ?Sized;
706 type RM: Deref<Target=Self::RMT>;
707 type OMT: OnionMessageHandler + ?Sized;
708 type OM: Deref<Target=Self::OMT>;
709 type LT: Logger + ?Sized;
710 type L: Deref<Target=Self::LT>;
711 type CMHT: CustomMessageHandler + ?Sized;
712 type CMH: Deref<Target=Self::CMHT>;
713 type NST: NodeSigner + ?Sized;
714 type NS: Deref<Target=Self::NST>;
715 /// Gets a reference to the underlying [`PeerManager`].
716 fn as_ref(&self) -> &PeerManager<Self::Descriptor, Self::CM, Self::RM, Self::OM, Self::L, Self::CMH, Self::NS>;
717 /// Returns the peer manager's [`OnionMessageHandler`].
718 fn onion_message_handler(&self) -> &Self::OMT;
721 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref>
722 APeerManager for PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
723 CM::Target: ChannelMessageHandler,
724 RM::Target: RoutingMessageHandler,
725 OM::Target: OnionMessageHandler,
727 CMH::Target: CustomMessageHandler,
728 NS::Target: NodeSigner,
730 type Descriptor = Descriptor;
731 type CMT = <CM as Deref>::Target;
733 type RMT = <RM as Deref>::Target;
735 type OMT = <OM as Deref>::Target;
737 type LT = <L as Deref>::Target;
739 type CMHT = <CMH as Deref>::Target;
741 type NST = <NS as Deref>::Target;
743 fn as_ref(&self) -> &PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> { self }
744 fn onion_message_handler(&self) -> &Self::OMT {
745 self.message_handler.onion_message_handler.deref()
749 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
750 /// socket events into messages which it passes on to its [`MessageHandler`].
752 /// Locks are taken internally, so you must never assume that reentrancy from a
753 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
755 /// Calls to [`read_event`] will decode relevant messages and pass them to the
756 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
757 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
758 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
759 /// calls only after previous ones have returned.
761 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
762 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
763 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
764 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
765 /// you're using lightning-net-tokio.
767 /// [`read_event`]: PeerManager::read_event
768 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
769 CM::Target: ChannelMessageHandler,
770 RM::Target: RoutingMessageHandler,
771 OM::Target: OnionMessageHandler,
773 CMH::Target: CustomMessageHandler,
774 NS::Target: NodeSigner {
775 message_handler: MessageHandler<CM, RM, OM, CMH>,
776 /// Connection state for each connected peer - we have an outer read-write lock which is taken
777 /// as read while we're doing processing for a peer and taken write when a peer is being added
780 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
781 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
782 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
783 /// the `MessageHandler`s for a given peer is already guaranteed.
784 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
785 /// Only add to this set when noise completes.
786 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
787 /// lock held. Entries may be added with only the `peers` read lock held (though the
788 /// `Descriptor` value must already exist in `peers`).
789 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
790 /// We can only have one thread processing events at once, but if a second call to
791 /// `process_events` happens while a first call is in progress, one of the two calls needs to
792 /// start from the top to ensure any new messages are also handled.
794 /// Because the event handler calls into user code which may block, we don't want to block a
795 /// second thread waiting for another thread to handle events which is then blocked on user
796 /// code, so we store an atomic counter here:
797 /// * 0 indicates no event processor is running
798 /// * 1 indicates an event processor is running
799 /// * > 1 indicates an event processor is running but needs to start again from the top once
800 /// it finishes as another thread tried to start processing events but returned early.
801 event_processing_state: AtomicI32,
803 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
804 /// value increases strictly since we don't assume access to a time source.
805 last_node_announcement_serial: AtomicU32,
807 ephemeral_key_midstate: Sha256Engine,
809 peer_counter: AtomicCounter,
811 gossip_processing_backlogged: AtomicBool,
812 gossip_processing_backlog_lifted: AtomicBool,
817 secp_ctx: Secp256k1<secp256k1::SignOnly>
820 enum MessageHandlingError {
821 PeerHandleError(PeerHandleError),
822 LightningError(LightningError),
825 impl From<PeerHandleError> for MessageHandlingError {
826 fn from(error: PeerHandleError) -> Self {
827 MessageHandlingError::PeerHandleError(error)
831 impl From<LightningError> for MessageHandlingError {
832 fn from(error: LightningError) -> Self {
833 MessageHandlingError::LightningError(error)
837 macro_rules! encode_msg {
839 let mut buffer = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
840 wire::write($msg, &mut buffer).unwrap();
845 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
846 CM::Target: ChannelMessageHandler,
847 OM::Target: OnionMessageHandler,
849 NS::Target: NodeSigner {
850 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
851 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
854 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
855 /// cryptographically secure random bytes.
857 /// `current_time` is used as an always-increasing counter that survives across restarts and is
858 /// incremented irregularly internally. In general it is best to simply use the current UNIX
859 /// timestamp, however if it is not available a persistent counter that increases once per
860 /// minute should suffice.
862 /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
863 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 {
864 Self::new(MessageHandler {
865 chan_handler: channel_message_handler,
866 route_handler: IgnoringMessageHandler{},
867 onion_message_handler,
868 custom_message_handler: IgnoringMessageHandler{},
869 }, current_time, ephemeral_random_data, logger, node_signer)
873 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
874 RM::Target: RoutingMessageHandler,
876 NS::Target: NodeSigner {
877 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
878 /// handler or onion message handler is used and onion and channel messages will be ignored (or
879 /// generate error messages). Note that some other lightning implementations time-out connections
880 /// after some time if no channel is built with the peer.
882 /// `current_time` is used as an always-increasing counter that survives across restarts and is
883 /// incremented irregularly internally. In general it is best to simply use the current UNIX
884 /// timestamp, however if it is not available a persistent counter that increases once per
885 /// minute should suffice.
887 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
888 /// cryptographically secure random bytes.
890 /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
891 pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
892 Self::new(MessageHandler {
893 chan_handler: ErroringMessageHandler::new(),
894 route_handler: routing_message_handler,
895 onion_message_handler: IgnoringMessageHandler{},
896 custom_message_handler: IgnoringMessageHandler{},
897 }, current_time, ephemeral_random_data, logger, node_signer)
901 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
902 /// This works around `format!()` taking a reference to each argument, preventing
903 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
904 /// due to lifetime errors.
905 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
906 impl core::fmt::Display for OptionalFromDebugger<'_> {
907 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
908 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
912 /// A function used to filter out local or private addresses
913 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
914 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
915 fn filter_addresses(ip_address: Option<SocketAddress>) -> Option<SocketAddress> {
917 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
918 Some(SocketAddress::TcpIpV4{addr: [10, _, _, _], port: _}) => None,
919 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
920 Some(SocketAddress::TcpIpV4{addr: [0, _, _, _], port: _}) => None,
921 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
922 Some(SocketAddress::TcpIpV4{addr: [100, 64..=127, _, _], port: _}) => None,
923 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
924 Some(SocketAddress::TcpIpV4{addr: [127, _, _, _], port: _}) => None,
925 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
926 Some(SocketAddress::TcpIpV4{addr: [169, 254, _, _], port: _}) => None,
927 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
928 Some(SocketAddress::TcpIpV4{addr: [172, 16..=31, _, _], port: _}) => None,
929 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
930 Some(SocketAddress::TcpIpV4{addr: [192, 168, _, _], port: _}) => None,
931 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
932 Some(SocketAddress::TcpIpV4{addr: [192, 88, 99, _], port: _}) => None,
933 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
934 Some(SocketAddress::TcpIpV6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
935 // For remaining addresses
936 Some(SocketAddress::TcpIpV6{addr: _, port: _}) => None,
937 Some(..) => ip_address,
942 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
943 CM::Target: ChannelMessageHandler,
944 RM::Target: RoutingMessageHandler,
945 OM::Target: OnionMessageHandler,
947 CMH::Target: CustomMessageHandler,
948 NS::Target: NodeSigner
950 /// Constructs a new `PeerManager` with the given message handlers.
952 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
953 /// cryptographically secure random bytes.
955 /// `current_time` is used as an always-increasing counter that survives across restarts and is
956 /// incremented irregularly internally. In general it is best to simply use the current UNIX
957 /// timestamp, however if it is not available a persistent counter that increases once per
958 /// minute should suffice.
959 pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
960 let mut ephemeral_key_midstate = Sha256::engine();
961 ephemeral_key_midstate.input(ephemeral_random_data);
963 let mut secp_ctx = Secp256k1::signing_only();
964 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).to_byte_array();
965 secp_ctx.seeded_randomize(&ephemeral_hash);
969 peers: FairRwLock::new(new_hash_map()),
970 node_id_to_descriptor: Mutex::new(new_hash_map()),
971 event_processing_state: AtomicI32::new(0),
972 ephemeral_key_midstate,
973 peer_counter: AtomicCounter::new(),
974 gossip_processing_backlogged: AtomicBool::new(false),
975 gossip_processing_backlog_lifted: AtomicBool::new(false),
976 last_node_announcement_serial: AtomicU32::new(current_time),
983 /// Returns a list of [`PeerDetails`] for connected peers that have completed the initial
985 pub fn list_peers(&self) -> Vec<PeerDetails> {
986 let peers = self.peers.read().unwrap();
987 peers.values().filter_map(|peer_mutex| {
988 let p = peer_mutex.lock().unwrap();
989 if !p.handshake_complete() {
992 let details = PeerDetails {
993 // unwrap safety: their_node_id is guaranteed to be `Some` after the handshake
995 counterparty_node_id: p.their_node_id.unwrap().0,
996 socket_address: p.their_socket_address.clone(),
997 // unwrap safety: their_features is guaranteed to be `Some` after the handshake
999 init_features: p.their_features.clone().unwrap(),
1000 is_inbound_connection: p.inbound_connection,
1006 /// Returns the [`PeerDetails`] of a connected peer that has completed the initial handshake.
1008 /// Will return `None` if the peer is unknown or it hasn't completed the initial handshake.
1009 pub fn peer_by_node_id(&self, their_node_id: &PublicKey) -> Option<PeerDetails> {
1010 let peers = self.peers.read().unwrap();
1011 peers.values().find_map(|peer_mutex| {
1012 let p = peer_mutex.lock().unwrap();
1013 if !p.handshake_complete() {
1017 // unwrap safety: their_node_id is guaranteed to be `Some` after the handshake
1019 let counterparty_node_id = p.their_node_id.unwrap().0;
1021 if counterparty_node_id != *their_node_id {
1025 let details = PeerDetails {
1026 counterparty_node_id,
1027 socket_address: p.their_socket_address.clone(),
1028 // unwrap safety: their_features is guaranteed to be `Some` after the handshake
1030 init_features: p.their_features.clone().unwrap(),
1031 is_inbound_connection: p.inbound_connection,
1037 fn get_ephemeral_key(&self) -> SecretKey {
1038 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
1039 let counter = self.peer_counter.get_increment();
1040 ephemeral_hash.input(&counter.to_le_bytes());
1041 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).to_byte_array()).expect("You broke SHA-256!")
1044 fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
1045 self.message_handler.chan_handler.provided_init_features(their_node_id)
1046 | self.message_handler.route_handler.provided_init_features(their_node_id)
1047 | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
1048 | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
1051 /// Indicates a new outbound connection has been established to a node with the given `node_id`
1052 /// and an optional remote network address.
1054 /// The remote network address adds the option to report a remote IP address back to a connecting
1055 /// peer using the init message.
1056 /// The user should pass the remote network address of the host they are connected to.
1058 /// If an `Err` is returned here you must disconnect the connection immediately.
1060 /// Returns a small number of bytes to send to the remote node (currently always 50).
1062 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1063 /// [`socket_disconnected`].
1065 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1066 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<Vec<u8>, PeerHandleError> {
1067 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
1068 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
1069 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
1071 let mut peers = self.peers.write().unwrap();
1072 match peers.entry(descriptor) {
1073 hash_map::Entry::Occupied(_) => {
1074 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1075 Err(PeerHandleError {})
1077 hash_map::Entry::Vacant(e) => {
1078 e.insert(Mutex::new(Peer {
1079 channel_encryptor: peer_encryptor,
1080 their_node_id: None,
1081 their_features: None,
1082 their_socket_address: remote_network_address,
1084 pending_outbound_buffer: VecDeque::new(),
1085 pending_outbound_buffer_first_msg_offset: 0,
1086 gossip_broadcast_buffer: VecDeque::new(),
1087 awaiting_write_event: false,
1089 pending_read_buffer,
1090 pending_read_buffer_pos: 0,
1091 pending_read_is_header: false,
1093 sync_status: InitSyncTracker::NoSyncRequested,
1095 msgs_sent_since_pong: 0,
1096 awaiting_pong_timer_tick_intervals: 0,
1097 received_message_since_timer_tick: false,
1098 sent_gossip_timestamp_filter: false,
1100 received_channel_announce_since_backlogged: false,
1101 inbound_connection: false,
1108 /// Indicates a new inbound connection has been established to a node with an optional remote
1109 /// network address.
1111 /// The remote network address adds the option to report a remote IP address back to a connecting
1112 /// peer using the init message.
1113 /// The user should pass the remote network address of the host they are connected to.
1115 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
1116 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
1117 /// the connection immediately.
1119 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1120 /// [`socket_disconnected`].
1122 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1123 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<(), PeerHandleError> {
1124 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1125 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1127 let mut peers = self.peers.write().unwrap();
1128 match peers.entry(descriptor) {
1129 hash_map::Entry::Occupied(_) => {
1130 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1131 Err(PeerHandleError {})
1133 hash_map::Entry::Vacant(e) => {
1134 e.insert(Mutex::new(Peer {
1135 channel_encryptor: peer_encryptor,
1136 their_node_id: None,
1137 their_features: None,
1138 their_socket_address: remote_network_address,
1140 pending_outbound_buffer: VecDeque::new(),
1141 pending_outbound_buffer_first_msg_offset: 0,
1142 gossip_broadcast_buffer: VecDeque::new(),
1143 awaiting_write_event: false,
1145 pending_read_buffer,
1146 pending_read_buffer_pos: 0,
1147 pending_read_is_header: false,
1149 sync_status: InitSyncTracker::NoSyncRequested,
1151 msgs_sent_since_pong: 0,
1152 awaiting_pong_timer_tick_intervals: 0,
1153 received_message_since_timer_tick: false,
1154 sent_gossip_timestamp_filter: false,
1156 received_channel_announce_since_backlogged: false,
1157 inbound_connection: true,
1164 fn peer_should_read(&self, peer: &mut Peer) -> bool {
1165 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1168 fn update_gossip_backlogged(&self) {
1169 let new_state = self.message_handler.route_handler.processing_queue_high();
1170 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1171 if prev_state && !new_state {
1172 self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1176 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1177 let mut have_written = false;
1178 while !peer.awaiting_write_event {
1179 if peer.should_buffer_onion_message() {
1180 if let Some((peer_node_id, _)) = peer.their_node_id {
1181 if let Some(next_onion_message) =
1182 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1183 self.enqueue_message(peer, &next_onion_message);
1187 if peer.should_buffer_gossip_broadcast() {
1188 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1189 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(msg));
1192 if peer.should_buffer_gossip_backfill() {
1193 match peer.sync_status {
1194 InitSyncTracker::NoSyncRequested => {},
1195 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1196 if let Some((announce, update_a_option, update_b_option)) =
1197 self.message_handler.route_handler.get_next_channel_announcement(c)
1199 self.enqueue_message(peer, &announce);
1200 if let Some(update_a) = update_a_option {
1201 self.enqueue_message(peer, &update_a);
1203 if let Some(update_b) = update_b_option {
1204 self.enqueue_message(peer, &update_b);
1206 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1208 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1211 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1212 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1213 self.enqueue_message(peer, &msg);
1214 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1216 peer.sync_status = InitSyncTracker::NoSyncRequested;
1219 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1220 InitSyncTracker::NodesSyncing(sync_node_id) => {
1221 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1222 self.enqueue_message(peer, &msg);
1223 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1225 peer.sync_status = InitSyncTracker::NoSyncRequested;
1230 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1231 self.maybe_send_extra_ping(peer);
1234 let should_read = self.peer_should_read(peer);
1235 let next_buff = match peer.pending_outbound_buffer.front() {
1237 if force_one_write && !have_written {
1239 let data_sent = descriptor.send_data(&[], should_read);
1240 debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1248 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1249 let data_sent = descriptor.send_data(pending, should_read);
1250 have_written = true;
1251 peer.pending_outbound_buffer_first_msg_offset += data_sent;
1252 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1253 peer.pending_outbound_buffer_first_msg_offset = 0;
1254 peer.pending_outbound_buffer.pop_front();
1255 const VEC_SIZE: usize = ::core::mem::size_of::<Vec<u8>>();
1256 let large_capacity = peer.pending_outbound_buffer.capacity() > 4096 / VEC_SIZE;
1257 let lots_of_slack = peer.pending_outbound_buffer.len()
1258 < peer.pending_outbound_buffer.capacity() / 2;
1259 if large_capacity && lots_of_slack {
1260 peer.pending_outbound_buffer.shrink_to_fit();
1263 peer.awaiting_write_event = true;
1268 /// Indicates that there is room to write data to the given socket descriptor.
1270 /// May return an Err to indicate that the connection should be closed.
1272 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1273 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1274 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1275 /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1278 /// [`send_data`]: SocketDescriptor::send_data
1279 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1280 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1281 let peers = self.peers.read().unwrap();
1282 match peers.get(descriptor) {
1284 // This is most likely a simple race condition where the user found that the socket
1285 // was writeable, then we told the user to `disconnect_socket()`, then they called
1286 // this method. Return an error to make sure we get disconnected.
1287 return Err(PeerHandleError { });
1289 Some(peer_mutex) => {
1290 let mut peer = peer_mutex.lock().unwrap();
1291 peer.awaiting_write_event = false;
1292 self.do_attempt_write_data(descriptor, &mut peer, false);
1298 /// Indicates that data was read from the given socket descriptor.
1300 /// May return an Err to indicate that the connection should be closed.
1302 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1303 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1304 /// [`send_data`] calls to handle responses.
1306 /// If `Ok(true)` is returned, further read_events should not be triggered until a
1307 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1310 /// In order to avoid processing too many messages at once per peer, `data` should be on the
1313 /// [`send_data`]: SocketDescriptor::send_data
1314 /// [`process_events`]: PeerManager::process_events
1315 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1316 match self.do_read_event(peer_descriptor, data) {
1319 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1320 self.disconnect_event_internal(peer_descriptor);
1326 /// Append a message to a peer's pending outbound/write buffer
1327 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1328 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1329 if is_gossip_msg(message.type_id()) {
1330 log_gossip!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1332 log_trace!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1334 peer.msgs_sent_since_pong += 1;
1335 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1338 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1339 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: MessageBuf) {
1340 peer.msgs_sent_since_pong += 1;
1341 debug_assert!(peer.gossip_broadcast_buffer.len() <= OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP);
1342 peer.gossip_broadcast_buffer.push_back(encoded_message);
1345 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1346 let mut pause_read = false;
1347 let peers = self.peers.read().unwrap();
1348 let mut msgs_to_forward = Vec::new();
1349 let mut peer_node_id = None;
1350 match peers.get(peer_descriptor) {
1352 // This is most likely a simple race condition where the user read some bytes
1353 // from the socket, then we told the user to `disconnect_socket()`, then they
1354 // called this method. Return an error to make sure we get disconnected.
1355 return Err(PeerHandleError { });
1357 Some(peer_mutex) => {
1358 let mut read_pos = 0;
1359 while read_pos < data.len() {
1360 macro_rules! try_potential_handleerror {
1361 ($peer: expr, $thing: expr) => {{
1363 let logger = WithContext::from(&self.logger, peer_node_id.map(|(id, _)| id), None);
1368 msgs::ErrorAction::DisconnectPeer { .. } => {
1369 // We may have an `ErrorMessage` to send to the peer,
1370 // but writing to the socket while reading can lead to
1371 // re-entrant code and possibly unexpected behavior. The
1372 // message send is optimistic anyway, and in this case
1373 // we immediately disconnect the peer.
1374 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1375 return Err(PeerHandleError { });
1377 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1378 // We have a `WarningMessage` to send to the peer, but
1379 // writing to the socket while reading can lead to
1380 // re-entrant code and possibly unexpected behavior. The
1381 // message send is optimistic anyway, and in this case
1382 // we immediately disconnect the peer.
1383 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1384 return Err(PeerHandleError { });
1386 msgs::ErrorAction::IgnoreAndLog(level) => {
1387 log_given_level!(logger, level, "Error handling {}message{}; ignoring: {}",
1388 if level == Level::Gossip { "gossip " } else { "" },
1389 OptionalFromDebugger(&peer_node_id), e.err);
1392 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1393 msgs::ErrorAction::IgnoreError => {
1394 log_debug!(logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1397 msgs::ErrorAction::SendErrorMessage { msg } => {
1398 log_debug!(logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1399 self.enqueue_message($peer, &msg);
1402 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1403 log_given_level!(logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1404 self.enqueue_message($peer, &msg);
1413 let mut peer_lock = peer_mutex.lock().unwrap();
1414 let peer = &mut *peer_lock;
1415 let mut msg_to_handle = None;
1416 if peer_node_id.is_none() {
1417 peer_node_id = peer.their_node_id.clone();
1420 assert!(peer.pending_read_buffer.len() > 0);
1421 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1424 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1425 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]);
1426 read_pos += data_to_copy;
1427 peer.pending_read_buffer_pos += data_to_copy;
1430 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1431 peer.pending_read_buffer_pos = 0;
1433 macro_rules! insert_node_id {
1435 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1436 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1437 hash_map::Entry::Occupied(e) => {
1438 log_trace!(logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1439 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1440 // Check that the peers map is consistent with the
1441 // node_id_to_descriptor map, as this has been broken
1443 debug_assert!(peers.get(e.get()).is_some());
1444 return Err(PeerHandleError { })
1446 hash_map::Entry::Vacant(entry) => {
1447 log_debug!(logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1448 entry.insert(peer_descriptor.clone())
1454 let next_step = peer.channel_encryptor.get_noise_step();
1456 NextNoiseStep::ActOne => {
1457 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1458 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1459 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1460 peer.pending_outbound_buffer.push_back(act_two);
1461 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1463 NextNoiseStep::ActTwo => {
1464 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1465 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1466 &self.node_signer));
1467 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1468 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1469 peer.pending_read_is_header = true;
1471 peer.set_their_node_id(their_node_id);
1473 let features = self.init_features(&their_node_id);
1474 let networks = self.message_handler.chan_handler.get_chain_hashes();
1475 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1476 self.enqueue_message(peer, &resp);
1477 peer.awaiting_pong_timer_tick_intervals = 0;
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);
1490 peer.awaiting_pong_timer_tick_intervals = 0;
1492 NextNoiseStep::NoiseComplete => {
1493 if peer.pending_read_is_header {
1494 let msg_len = try_potential_handleerror!(peer,
1495 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1496 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1497 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1498 if msg_len < 2 { // Need at least the message type tag
1499 return Err(PeerHandleError { });
1501 peer.pending_read_is_header = false;
1503 debug_assert!(peer.pending_read_buffer.len() >= 2 + 16);
1504 try_potential_handleerror!(peer,
1505 peer.channel_encryptor.decrypt_message(&mut peer.pending_read_buffer[..]));
1507 let mut reader = io::Cursor::new(&peer.pending_read_buffer[..peer.pending_read_buffer.len() - 16]);
1508 let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1510 // Reset read buffer
1511 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1512 peer.pending_read_buffer.resize(18, 0);
1513 peer.pending_read_is_header = true;
1515 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1516 let message = match message_result {
1520 // Note that to avoid re-entrancy we never call
1521 // `do_attempt_write_data` from here, causing
1522 // the messages enqueued here to not actually
1523 // be sent before the peer is disconnected.
1524 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1525 log_gossip!(logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1528 (msgs::DecodeError::UnsupportedCompression, _) => {
1529 log_gossip!(logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1530 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: ChannelId::new_zero(), data: "Unsupported message compression: zlib".to_owned() });
1533 (_, Some(ty)) if is_gossip_msg(ty) => {
1534 log_gossip!(logger, "Got an invalid value while deserializing a gossip message");
1535 self.enqueue_message(peer, &msgs::WarningMessage {
1536 channel_id: ChannelId::new_zero(),
1537 data: format!("Unreadable/bogus gossip message of type {}", ty),
1541 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1542 log_debug!(logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1543 return Err(PeerHandleError { });
1545 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1546 (msgs::DecodeError::InvalidValue, _) => {
1547 log_debug!(logger, "Got an invalid value while deserializing message");
1548 return Err(PeerHandleError { });
1550 (msgs::DecodeError::ShortRead, _) => {
1551 log_debug!(logger, "Deserialization failed due to shortness of message");
1552 return Err(PeerHandleError { });
1554 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1555 (msgs::DecodeError::Io(_), _) => 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
1593 /// Returns the message back if it needs to be broadcasted to all other peers.
1596 peer_mutex: &Mutex<Peer>,
1597 mut peer_lock: MutexGuard<Peer>,
1598 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1599 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1600 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;
1601 let logger = WithContext::from(&self.logger, Some(their_node_id), None);
1602 peer_lock.received_message_since_timer_tick = true;
1604 // Need an Init as first message
1605 if let wire::Message::Init(msg) = message {
1606 // Check if we have any compatible chains if the `networks` field is specified.
1607 if let Some(networks) = &msg.networks {
1608 if let Some(our_chains) = self.message_handler.chan_handler.get_chain_hashes() {
1609 let mut have_compatible_chains = false;
1610 'our_chains: for our_chain in our_chains.iter() {
1611 for their_chain in networks {
1612 if our_chain == their_chain {
1613 have_compatible_chains = true;
1618 if !have_compatible_chains {
1619 log_debug!(logger, "Peer does not support any of our supported chains");
1620 return Err(PeerHandleError { }.into());
1625 let our_features = self.init_features(&their_node_id);
1626 if msg.features.requires_unknown_bits_from(&our_features) {
1627 log_debug!(logger, "Peer requires features unknown to us");
1628 return Err(PeerHandleError { }.into());
1631 if our_features.requires_unknown_bits_from(&msg.features) {
1632 log_debug!(logger, "We require features unknown to our peer");
1633 return Err(PeerHandleError { }.into());
1636 if peer_lock.their_features.is_some() {
1637 return Err(PeerHandleError { }.into());
1640 log_info!(logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1642 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1643 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1644 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1647 if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1648 log_debug!(logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1649 return Err(PeerHandleError { }.into());
1651 if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1652 log_debug!(logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1653 return Err(PeerHandleError { }.into());
1655 if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1656 log_debug!(logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1657 return Err(PeerHandleError { }.into());
1660 peer_lock.their_features = Some(msg.features);
1662 } else if peer_lock.their_features.is_none() {
1663 log_debug!(logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1664 return Err(PeerHandleError { }.into());
1667 if let wire::Message::GossipTimestampFilter(_msg) = message {
1668 // When supporting gossip messages, start initial gossip sync only after we receive
1669 // a GossipTimestampFilter
1670 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1671 !peer_lock.sent_gossip_timestamp_filter {
1672 peer_lock.sent_gossip_timestamp_filter = true;
1673 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1678 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1679 peer_lock.received_channel_announce_since_backlogged = true;
1682 mem::drop(peer_lock);
1684 if is_gossip_msg(message.type_id()) {
1685 log_gossip!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1687 log_trace!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1690 let mut should_forward = None;
1693 // Setup and Control messages:
1694 wire::Message::Init(_) => {
1697 wire::Message::GossipTimestampFilter(_) => {
1700 wire::Message::Error(msg) => {
1701 log_debug!(logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1702 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1703 if msg.channel_id.is_zero() {
1704 return Err(PeerHandleError { }.into());
1707 wire::Message::Warning(msg) => {
1708 log_debug!(logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1711 wire::Message::Ping(msg) => {
1712 if msg.ponglen < 65532 {
1713 let resp = msgs::Pong { byteslen: msg.ponglen };
1714 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1717 wire::Message::Pong(_msg) => {
1718 let mut peer_lock = peer_mutex.lock().unwrap();
1719 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1720 peer_lock.msgs_sent_since_pong = 0;
1723 // Channel messages:
1724 wire::Message::OpenChannel(msg) => {
1725 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1727 wire::Message::OpenChannelV2(msg) => {
1728 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1730 wire::Message::AcceptChannel(msg) => {
1731 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1733 wire::Message::AcceptChannelV2(msg) => {
1734 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1737 wire::Message::FundingCreated(msg) => {
1738 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1740 wire::Message::FundingSigned(msg) => {
1741 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1743 wire::Message::ChannelReady(msg) => {
1744 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1747 // Quiescence messages:
1748 wire::Message::Stfu(msg) => {
1749 self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
1752 // Splicing messages:
1753 wire::Message::Splice(msg) => {
1754 self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
1756 wire::Message::SpliceAck(msg) => {
1757 self.message_handler.chan_handler.handle_splice_ack(&their_node_id, &msg);
1759 wire::Message::SpliceLocked(msg) => {
1760 self.message_handler.chan_handler.handle_splice_locked(&their_node_id, &msg);
1763 // Interactive transaction construction messages:
1764 wire::Message::TxAddInput(msg) => {
1765 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1767 wire::Message::TxAddOutput(msg) => {
1768 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1770 wire::Message::TxRemoveInput(msg) => {
1771 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1773 wire::Message::TxRemoveOutput(msg) => {
1774 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1776 wire::Message::TxComplete(msg) => {
1777 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1779 wire::Message::TxSignatures(msg) => {
1780 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1782 wire::Message::TxInitRbf(msg) => {
1783 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1785 wire::Message::TxAckRbf(msg) => {
1786 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1788 wire::Message::TxAbort(msg) => {
1789 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1792 wire::Message::Shutdown(msg) => {
1793 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1795 wire::Message::ClosingSigned(msg) => {
1796 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1799 // Commitment messages:
1800 wire::Message::UpdateAddHTLC(msg) => {
1801 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1803 wire::Message::UpdateFulfillHTLC(msg) => {
1804 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1806 wire::Message::UpdateFailHTLC(msg) => {
1807 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1809 wire::Message::UpdateFailMalformedHTLC(msg) => {
1810 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1813 wire::Message::CommitmentSigned(msg) => {
1814 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1816 wire::Message::RevokeAndACK(msg) => {
1817 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1819 wire::Message::UpdateFee(msg) => {
1820 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1822 wire::Message::ChannelReestablish(msg) => {
1823 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1826 // Routing messages:
1827 wire::Message::AnnouncementSignatures(msg) => {
1828 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1830 wire::Message::ChannelAnnouncement(msg) => {
1831 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1832 .map_err(|e| -> MessageHandlingError { e.into() })? {
1833 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1835 self.update_gossip_backlogged();
1837 wire::Message::NodeAnnouncement(msg) => {
1838 if self.message_handler.route_handler.handle_node_announcement(&msg)
1839 .map_err(|e| -> MessageHandlingError { e.into() })? {
1840 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1842 self.update_gossip_backlogged();
1844 wire::Message::ChannelUpdate(msg) => {
1845 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1846 if self.message_handler.route_handler.handle_channel_update(&msg)
1847 .map_err(|e| -> MessageHandlingError { e.into() })? {
1848 should_forward = Some(wire::Message::ChannelUpdate(msg));
1850 self.update_gossip_backlogged();
1852 wire::Message::QueryShortChannelIds(msg) => {
1853 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1855 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1856 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1858 wire::Message::QueryChannelRange(msg) => {
1859 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1861 wire::Message::ReplyChannelRange(msg) => {
1862 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1866 wire::Message::OnionMessage(msg) => {
1867 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1870 // Unknown messages:
1871 wire::Message::Unknown(type_id) if message.is_even() => {
1872 log_debug!(logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1873 return Err(PeerHandleError { }.into());
1875 wire::Message::Unknown(type_id) => {
1876 log_trace!(logger, "Received unknown odd message of type {}, ignoring", type_id);
1878 wire::Message::Custom(custom) => {
1879 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1885 fn forward_broadcast_msg(&self, peers: &HashMap<Descriptor, Mutex<Peer>>, msg: &wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>, except_node: Option<&PublicKey>) {
1887 wire::Message::ChannelAnnouncement(ref msg) => {
1888 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1889 let encoded_msg = encode_msg!(msg);
1891 for (_, peer_mutex) in peers.iter() {
1892 let mut peer = peer_mutex.lock().unwrap();
1893 if !peer.handshake_complete() ||
1894 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1897 debug_assert!(peer.their_node_id.is_some());
1898 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1899 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1900 if peer.buffer_full_drop_gossip_broadcast() {
1901 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1904 if let Some((_, their_node_id)) = peer.their_node_id {
1905 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1909 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1912 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1915 wire::Message::NodeAnnouncement(ref msg) => {
1916 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1917 let encoded_msg = encode_msg!(msg);
1919 for (_, peer_mutex) in peers.iter() {
1920 let mut peer = peer_mutex.lock().unwrap();
1921 if !peer.handshake_complete() ||
1922 !peer.should_forward_node_announcement(msg.contents.node_id) {
1925 debug_assert!(peer.their_node_id.is_some());
1926 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1927 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1928 if peer.buffer_full_drop_gossip_broadcast() {
1929 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1932 if let Some((_, their_node_id)) = peer.their_node_id {
1933 if their_node_id == msg.contents.node_id {
1937 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1940 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1943 wire::Message::ChannelUpdate(ref msg) => {
1944 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1945 let encoded_msg = encode_msg!(msg);
1947 for (_, peer_mutex) in peers.iter() {
1948 let mut peer = peer_mutex.lock().unwrap();
1949 if !peer.handshake_complete() ||
1950 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1953 debug_assert!(peer.their_node_id.is_some());
1954 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1955 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1956 if peer.buffer_full_drop_gossip_broadcast() {
1957 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1960 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1963 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1966 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1970 /// Checks for any events generated by our handlers and processes them. Includes sending most
1971 /// response messages as well as messages generated by calls to handler functions directly (eg
1972 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1974 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1977 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1978 /// or one of the other clients provided in our language bindings.
1980 /// Note that if there are any other calls to this function waiting on lock(s) this may return
1981 /// without doing any work. All available events that need handling will be handled before the
1982 /// other calls return.
1984 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1985 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1986 /// [`send_data`]: SocketDescriptor::send_data
1987 pub fn process_events(&self) {
1988 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
1989 // If we're not the first event processor to get here, just return early, the increment
1990 // we just did will be treated as "go around again" at the end.
1995 self.update_gossip_backlogged();
1996 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
1998 let mut peers_to_disconnect = new_hash_map();
2001 let peers_lock = self.peers.read().unwrap();
2003 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
2004 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
2006 let peers = &*peers_lock;
2007 macro_rules! get_peer_for_forwarding {
2008 ($node_id: expr) => {
2010 if peers_to_disconnect.get($node_id).is_some() {
2011 // If we've "disconnected" this peer, do not send to it.
2014 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
2015 match descriptor_opt {
2016 Some(descriptor) => match peers.get(&descriptor) {
2017 Some(peer_mutex) => {
2018 let peer_lock = peer_mutex.lock().unwrap();
2019 if !peer_lock.handshake_complete() {
2025 debug_assert!(false, "Inconsistent peers set state!");
2036 for event in events_generated.drain(..) {
2038 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
2039 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id)), "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
2040 log_pubkey!(node_id),
2041 &msg.common_fields.temporary_channel_id);
2042 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2044 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
2045 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id)), "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
2046 log_pubkey!(node_id),
2047 &msg.common_fields.temporary_channel_id);
2048 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2050 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
2051 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id)), "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
2052 log_pubkey!(node_id),
2053 &msg.common_fields.temporary_channel_id);
2054 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2056 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
2057 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.common_fields.temporary_channel_id)), "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}",
2058 log_pubkey!(node_id),
2059 &msg.common_fields.temporary_channel_id);
2060 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2062 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
2063 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
2064 log_pubkey!(node_id),
2065 &msg.temporary_channel_id,
2066 ChannelId::v1_from_funding_txid(msg.funding_txid.as_byte_array(), msg.funding_output_index));
2067 // TODO: If the peer is gone we should generate a DiscardFunding event
2068 // indicating to the wallet that they should just throw away this funding transaction
2069 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2071 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
2072 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
2073 log_pubkey!(node_id),
2075 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2077 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
2078 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReady event in peer_handler for node {} for channel {}",
2079 log_pubkey!(node_id),
2081 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2083 MessageSendEvent::SendStfu { ref node_id, ref msg} => {
2084 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2085 log_debug!(logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
2086 log_pubkey!(node_id),
2088 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2090 MessageSendEvent::SendSplice { ref node_id, ref msg} => {
2091 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2092 log_debug!(logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
2093 log_pubkey!(node_id),
2095 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2097 MessageSendEvent::SendSpliceAck { ref node_id, ref msg} => {
2098 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2099 log_debug!(logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}",
2100 log_pubkey!(node_id),
2102 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2104 MessageSendEvent::SendSpliceLocked { ref node_id, ref msg} => {
2105 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2106 log_debug!(logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}",
2107 log_pubkey!(node_id),
2109 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2111 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
2112 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddInput 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::SendTxAddOutput { ref node_id, ref msg } => {
2118 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddOutput 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::SendTxRemoveInput { ref node_id, ref msg } => {
2124 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
2125 log_pubkey!(node_id),
2127 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2129 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
2130 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
2131 log_pubkey!(node_id),
2133 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2135 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
2136 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxComplete event in peer_handler for node {} for channel {}",
2137 log_pubkey!(node_id),
2139 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2141 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
2142 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
2143 log_pubkey!(node_id),
2145 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2147 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
2148 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
2149 log_pubkey!(node_id),
2151 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2153 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2154 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2155 log_pubkey!(node_id),
2157 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2159 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2160 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2161 log_pubkey!(node_id),
2163 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2165 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2166 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2167 log_pubkey!(node_id),
2169 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2171 MessageSendEvent::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 } } => {
2172 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(commitment_signed.channel_id)), "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
2173 log_pubkey!(node_id),
2174 update_add_htlcs.len(),
2175 update_fulfill_htlcs.len(),
2176 update_fail_htlcs.len(),
2177 &commitment_signed.channel_id);
2178 let mut peer = get_peer_for_forwarding!(node_id);
2179 for msg in update_add_htlcs {
2180 self.enqueue_message(&mut *peer, msg);
2182 for msg in update_fulfill_htlcs {
2183 self.enqueue_message(&mut *peer, msg);
2185 for msg in update_fail_htlcs {
2186 self.enqueue_message(&mut *peer, msg);
2188 for msg in update_fail_malformed_htlcs {
2189 self.enqueue_message(&mut *peer, msg);
2191 if let &Some(ref msg) = update_fee {
2192 self.enqueue_message(&mut *peer, msg);
2194 self.enqueue_message(&mut *peer, commitment_signed);
2196 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2197 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2198 log_pubkey!(node_id),
2200 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2202 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2203 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2204 log_pubkey!(node_id),
2206 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2208 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2209 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling Shutdown event in peer_handler for node {} for channel {}",
2210 log_pubkey!(node_id),
2212 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2214 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2215 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2216 log_pubkey!(node_id),
2218 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2220 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2221 log_debug!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2222 log_pubkey!(node_id),
2223 msg.contents.short_channel_id);
2224 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2225 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2227 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2228 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2229 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2230 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2231 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2234 if let Some(msg) = update_msg {
2235 match self.message_handler.route_handler.handle_channel_update(&msg) {
2236 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2237 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2242 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2243 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents);
2244 match self.message_handler.route_handler.handle_channel_update(&msg) {
2245 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2246 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2250 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2251 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2252 match self.message_handler.route_handler.handle_node_announcement(&msg) {
2253 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2254 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2258 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2259 log_trace!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2260 log_pubkey!(node_id), msg.contents.short_channel_id);
2261 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2263 MessageSendEvent::HandleError { node_id, action } => {
2264 let logger = WithContext::from(&self.logger, Some(node_id), None);
2266 msgs::ErrorAction::DisconnectPeer { msg } => {
2267 if let Some(msg) = msg.as_ref() {
2268 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2269 log_pubkey!(node_id), msg.data);
2271 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2272 log_pubkey!(node_id));
2274 // We do not have the peers write lock, so we just store that we're
2275 // about to disconnect the peer and do it after we finish
2276 // processing most messages.
2277 let msg = msg.map(|msg| wire::Message::<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2278 peers_to_disconnect.insert(node_id, msg);
2280 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2281 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2282 log_pubkey!(node_id), msg.data);
2283 // We do not have the peers write lock, so we just store that we're
2284 // about to disconnect the peer and do it after we finish
2285 // processing most messages.
2286 peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2288 msgs::ErrorAction::IgnoreAndLog(level) => {
2289 log_given_level!(logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2291 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2292 msgs::ErrorAction::IgnoreError => {
2293 log_debug!(logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2295 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2296 log_trace!(logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2297 log_pubkey!(node_id),
2299 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2301 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2302 log_given_level!(logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2303 log_pubkey!(node_id),
2305 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2309 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2310 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2312 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2313 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2315 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2316 log_gossip!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
2317 log_pubkey!(node_id),
2318 msg.short_channel_ids.len(),
2320 msg.number_of_blocks,
2322 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2324 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2325 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2330 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2331 if peers_to_disconnect.get(&node_id).is_some() { continue; }
2332 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2335 for (descriptor, peer_mutex) in peers.iter() {
2336 let mut peer = peer_mutex.lock().unwrap();
2337 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2338 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2341 if !peers_to_disconnect.is_empty() {
2342 let mut peers_lock = self.peers.write().unwrap();
2343 let peers = &mut *peers_lock;
2344 for (node_id, msg) in peers_to_disconnect.drain() {
2345 // Note that since we are holding the peers *write* lock we can
2346 // remove from node_id_to_descriptor immediately (as no other
2347 // thread can be holding the peer lock if we have the global write
2350 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2351 if let Some(mut descriptor) = descriptor_opt {
2352 if let Some(peer_mutex) = peers.remove(&descriptor) {
2353 let mut peer = peer_mutex.lock().unwrap();
2354 if let Some(msg) = msg {
2355 self.enqueue_message(&mut *peer, &msg);
2356 // This isn't guaranteed to work, but if there is enough free
2357 // room in the send buffer, put the error message there...
2358 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2360 self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2361 } else { debug_assert!(false, "Missing connection for peer"); }
2366 if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2367 // If another thread incremented the state while we were running we should go
2368 // around again, but only once.
2369 self.event_processing_state.store(1, Ordering::Release);
2376 /// Indicates that the given socket descriptor's connection is now closed.
2377 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2378 self.disconnect_event_internal(descriptor);
2381 fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2382 if !peer.handshake_complete() {
2383 log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2384 descriptor.disconnect_socket();
2388 debug_assert!(peer.their_node_id.is_some());
2389 if let Some((node_id, _)) = peer.their_node_id {
2390 log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Disconnecting peer with id {} due to {}", node_id, reason);
2391 self.message_handler.chan_handler.peer_disconnected(&node_id);
2392 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2394 descriptor.disconnect_socket();
2397 fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2398 let mut peers = self.peers.write().unwrap();
2399 let peer_option = peers.remove(descriptor);
2402 // This is most likely a simple race condition where the user found that the socket
2403 // was disconnected, then we told the user to `disconnect_socket()`, then they
2404 // called this method. Either way we're disconnected, return.
2406 Some(peer_lock) => {
2407 let peer = peer_lock.lock().unwrap();
2408 if let Some((node_id, _)) = peer.their_node_id {
2409 log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Handling disconnection of peer {}", log_pubkey!(node_id));
2410 let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2411 debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2412 if !peer.handshake_complete() { return; }
2413 self.message_handler.chan_handler.peer_disconnected(&node_id);
2414 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2420 /// Disconnect a peer given its node id.
2422 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2423 /// peer. Thus, be very careful about reentrancy issues.
2425 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2426 pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2427 let mut peers_lock = self.peers.write().unwrap();
2428 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2429 let peer_opt = peers_lock.remove(&descriptor);
2430 if let Some(peer_mutex) = peer_opt {
2431 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2432 } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2436 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2437 /// an indication that TCP sockets have stalled even if we weren't around to time them out
2438 /// using regular ping/pongs.
2439 pub fn disconnect_all_peers(&self) {
2440 let mut peers_lock = self.peers.write().unwrap();
2441 self.node_id_to_descriptor.lock().unwrap().clear();
2442 let peers = &mut *peers_lock;
2443 for (descriptor, peer_mutex) in peers.drain() {
2444 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2448 /// This is called when we're blocked on sending additional gossip messages until we receive a
2449 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2450 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2451 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2452 if peer.awaiting_pong_timer_tick_intervals == 0 {
2453 peer.awaiting_pong_timer_tick_intervals = -1;
2454 let ping = msgs::Ping {
2458 self.enqueue_message(peer, &ping);
2462 /// Send pings to each peer and disconnect those which did not respond to the last round of
2465 /// This may be called on any timescale you want, however, roughly once every ten seconds is
2466 /// preferred. The call rate determines both how often we send a ping to our peers and how much
2467 /// time they have to respond before we disconnect them.
2469 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2472 /// [`send_data`]: SocketDescriptor::send_data
2473 pub fn timer_tick_occurred(&self) {
2474 let mut descriptors_needing_disconnect = Vec::new();
2476 let peers_lock = self.peers.read().unwrap();
2478 self.update_gossip_backlogged();
2479 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2481 for (descriptor, peer_mutex) in peers_lock.iter() {
2482 let mut peer = peer_mutex.lock().unwrap();
2483 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2485 if !peer.handshake_complete() {
2486 // The peer needs to complete its handshake before we can exchange messages. We
2487 // give peers one timer tick to complete handshake, reusing
2488 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2489 // for handshake completion.
2490 if peer.awaiting_pong_timer_tick_intervals != 0 {
2491 descriptors_needing_disconnect.push(descriptor.clone());
2493 peer.awaiting_pong_timer_tick_intervals = 1;
2497 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2498 debug_assert!(peer.their_node_id.is_some());
2500 loop { // Used as a `goto` to skip writing a Ping message.
2501 if peer.awaiting_pong_timer_tick_intervals == -1 {
2502 // Magic value set in `maybe_send_extra_ping`.
2503 peer.awaiting_pong_timer_tick_intervals = 1;
2504 peer.received_message_since_timer_tick = false;
2508 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2509 || peer.awaiting_pong_timer_tick_intervals as u64 >
2510 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2512 descriptors_needing_disconnect.push(descriptor.clone());
2515 peer.received_message_since_timer_tick = false;
2517 if peer.awaiting_pong_timer_tick_intervals > 0 {
2518 peer.awaiting_pong_timer_tick_intervals += 1;
2522 peer.awaiting_pong_timer_tick_intervals = 1;
2523 let ping = msgs::Ping {
2527 self.enqueue_message(&mut *peer, &ping);
2530 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2534 if !descriptors_needing_disconnect.is_empty() {
2536 let mut peers_lock = self.peers.write().unwrap();
2537 for descriptor in descriptors_needing_disconnect {
2538 if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2539 let peer = peer_mutex.lock().unwrap();
2540 if let Some((node_id, _)) = peer.their_node_id {
2541 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2543 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2551 // Messages of up to 64KB should never end up more than half full with addresses, as that would
2552 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2553 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2555 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (SocketAddress::MAX_LEN as u32 + 1) / 2;
2557 // ...by failing to compile if the number of addresses that would be half of a message is
2558 // smaller than 100:
2559 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2561 /// Generates a signed node_announcement from the given arguments, sending it to all connected
2562 /// peers. Note that peers will likely ignore this message unless we have at least one public
2563 /// channel which has at least six confirmations on-chain.
2565 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2566 /// node to humans. They carry no in-protocol meaning.
2568 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2569 /// accepts incoming connections. These will be included in the node_announcement, publicly
2570 /// tying these addresses together and to this node. If you wish to preserve user privacy,
2571 /// addresses should likely contain only Tor Onion addresses.
2573 /// Panics if `addresses` is absurdly large (more than 100).
2575 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2576 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<SocketAddress>) {
2577 if addresses.len() > 100 {
2578 panic!("More than half the message size was taken up by public addresses!");
2581 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2582 // addresses be sorted for future compatibility.
2583 addresses.sort_by_key(|addr| addr.get_id());
2585 let features = self.message_handler.chan_handler.provided_node_features()
2586 | self.message_handler.route_handler.provided_node_features()
2587 | self.message_handler.onion_message_handler.provided_node_features()
2588 | self.message_handler.custom_message_handler.provided_node_features();
2589 let announcement = msgs::UnsignedNodeAnnouncement {
2591 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2592 node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2594 alias: NodeAlias(alias),
2596 excess_address_data: Vec::new(),
2597 excess_data: Vec::new(),
2599 let node_announce_sig = match self.node_signer.sign_gossip_message(
2600 msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2604 log_error!(self.logger, "Failed to generate signature for node_announcement");
2609 let msg = msgs::NodeAnnouncement {
2610 signature: node_announce_sig,
2611 contents: announcement
2614 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2615 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2616 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2620 fn is_gossip_msg(type_id: u16) -> bool {
2622 msgs::ChannelAnnouncement::TYPE |
2623 msgs::ChannelUpdate::TYPE |
2624 msgs::NodeAnnouncement::TYPE |
2625 msgs::QueryChannelRange::TYPE |
2626 msgs::ReplyChannelRange::TYPE |
2627 msgs::QueryShortChannelIds::TYPE |
2628 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2635 use crate::sign::{NodeSigner, Recipient};
2638 use crate::ln::ChannelId;
2639 use crate::ln::features::{InitFeatures, NodeFeatures};
2640 use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2641 use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2642 use crate::ln::{msgs, wire};
2643 use crate::ln::msgs::{LightningError, SocketAddress};
2644 use crate::util::test_utils;
2646 use bitcoin::Network;
2647 use bitcoin::blockdata::constants::ChainHash;
2648 use bitcoin::secp256k1::{PublicKey, SecretKey};
2650 use crate::prelude::*;
2651 use crate::sync::{Arc, Mutex};
2652 use core::convert::Infallible;
2653 use core::sync::atomic::{AtomicBool, Ordering};
2656 struct FileDescriptor {
2658 outbound_data: Arc<Mutex<Vec<u8>>>,
2659 disconnect: Arc<AtomicBool>,
2661 impl PartialEq for FileDescriptor {
2662 fn eq(&self, other: &Self) -> bool {
2666 impl Eq for FileDescriptor { }
2667 impl core::hash::Hash for FileDescriptor {
2668 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2669 self.fd.hash(hasher)
2673 impl SocketDescriptor for FileDescriptor {
2674 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2675 self.outbound_data.lock().unwrap().extend_from_slice(data);
2679 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2682 struct PeerManagerCfg {
2683 chan_handler: test_utils::TestChannelMessageHandler,
2684 routing_handler: test_utils::TestRoutingMessageHandler,
2685 custom_handler: TestCustomMessageHandler,
2686 logger: test_utils::TestLogger,
2687 node_signer: test_utils::TestNodeSigner,
2690 struct TestCustomMessageHandler {
2691 features: InitFeatures,
2694 impl wire::CustomMessageReader for TestCustomMessageHandler {
2695 type CustomMessage = Infallible;
2696 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2701 impl CustomMessageHandler for TestCustomMessageHandler {
2702 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2706 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2708 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2710 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2711 self.features.clone()
2715 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2716 let mut cfgs = Vec::new();
2717 for i in 0..peer_count {
2718 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2720 let mut feature_bits = vec![0u8; 33];
2721 feature_bits[32] = 0b00000001;
2722 InitFeatures::from_le_bytes(feature_bits)
2726 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2727 logger: test_utils::TestLogger::new(),
2728 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2729 custom_handler: TestCustomMessageHandler { features },
2730 node_signer: test_utils::TestNodeSigner::new(node_secret),
2738 fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2739 let mut cfgs = Vec::new();
2740 for i in 0..peer_count {
2741 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2743 let mut feature_bits = vec![0u8; 33 + i + 1];
2744 feature_bits[33 + i] = 0b00000001;
2745 InitFeatures::from_le_bytes(feature_bits)
2749 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2750 logger: test_utils::TestLogger::new(),
2751 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2752 custom_handler: TestCustomMessageHandler { features },
2753 node_signer: test_utils::TestNodeSigner::new(node_secret),
2761 fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2762 let mut cfgs = Vec::new();
2763 for i in 0..peer_count {
2764 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2765 let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2766 let network = ChainHash::from(&[i as u8; 32]);
2769 chan_handler: test_utils::TestChannelMessageHandler::new(network),
2770 logger: test_utils::TestLogger::new(),
2771 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2772 custom_handler: TestCustomMessageHandler { features },
2773 node_signer: test_utils::TestNodeSigner::new(node_secret),
2781 fn create_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>> {
2782 let mut peers = Vec::new();
2783 for i in 0..peer_count {
2784 let ephemeral_bytes = [i as u8; 32];
2785 let msg_handler = MessageHandler {
2786 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2787 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2789 let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2796 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) {
2797 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2798 let mut fd_a = FileDescriptor {
2799 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2800 disconnect: Arc::new(AtomicBool::new(false)),
2802 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2803 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2804 let features_a = peer_a.init_features(&id_b);
2805 let features_b = peer_b.init_features(&id_a);
2806 let mut fd_b = FileDescriptor {
2807 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2808 disconnect: Arc::new(AtomicBool::new(false)),
2810 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2811 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2812 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2813 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2814 peer_a.process_events();
2816 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2817 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2819 peer_b.process_events();
2820 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2821 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2823 peer_a.process_events();
2824 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2825 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2827 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().counterparty_node_id, id_b);
2828 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().socket_address, Some(addr_b));
2829 assert_eq!(peer_a.peer_by_node_id(&id_b).unwrap().init_features, features_b);
2830 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().counterparty_node_id, id_a);
2831 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().socket_address, Some(addr_a));
2832 assert_eq!(peer_b.peer_by_node_id(&id_a).unwrap().init_features, features_a);
2833 (fd_a.clone(), fd_b.clone())
2837 #[cfg(feature = "std")]
2838 fn fuzz_threaded_connections() {
2839 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2840 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2841 // with our internal map consistency, and is a generally good smoke test of disconnection.
2842 let cfgs = Arc::new(create_peermgr_cfgs(2));
2843 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2844 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2846 let start_time = std::time::Instant::now();
2847 macro_rules! spawn_thread { ($id: expr) => { {
2848 let peers = Arc::clone(&peers);
2849 let cfgs = Arc::clone(&cfgs);
2850 std::thread::spawn(move || {
2852 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2853 let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2854 let mut fd_a = FileDescriptor {
2855 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2856 disconnect: Arc::new(AtomicBool::new(false)),
2858 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2859 let mut fd_b = FileDescriptor {
2860 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2861 disconnect: Arc::new(AtomicBool::new(false)),
2863 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2864 let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2865 peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2866 if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2868 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2869 peers[0].process_events();
2870 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2871 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2872 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2874 peers[1].process_events();
2875 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2876 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2877 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2879 cfgs[0].chan_handler.pending_events.lock().unwrap()
2880 .push(crate::events::MessageSendEvent::SendShutdown {
2881 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2882 msg: msgs::Shutdown {
2883 channel_id: ChannelId::new_zero(),
2884 scriptpubkey: bitcoin::ScriptBuf::new(),
2887 cfgs[1].chan_handler.pending_events.lock().unwrap()
2888 .push(crate::events::MessageSendEvent::SendShutdown {
2889 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2890 msg: msgs::Shutdown {
2891 channel_id: ChannelId::new_zero(),
2892 scriptpubkey: bitcoin::ScriptBuf::new(),
2897 peers[0].timer_tick_occurred();
2898 peers[1].timer_tick_occurred();
2902 peers[0].socket_disconnected(&fd_a);
2903 peers[1].socket_disconnected(&fd_b);
2905 std::thread::sleep(std::time::Duration::from_micros(1));
2909 let thrd_a = spawn_thread!(1);
2910 let thrd_b = spawn_thread!(2);
2912 thrd_a.join().unwrap();
2913 thrd_b.join().unwrap();
2917 fn test_feature_incompatible_peers() {
2918 let cfgs = create_peermgr_cfgs(2);
2919 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2921 let peers = create_network(2, &cfgs);
2922 let incompatible_peers = create_network(2, &incompatible_cfgs);
2923 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2924 for (peer_a, peer_b) in peer_pairs.iter() {
2925 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2926 let mut fd_a = FileDescriptor {
2927 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2928 disconnect: Arc::new(AtomicBool::new(false)),
2930 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2931 let mut fd_b = FileDescriptor {
2932 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2933 disconnect: Arc::new(AtomicBool::new(false)),
2935 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2936 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2937 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2938 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2939 peer_a.process_events();
2941 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2942 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2944 peer_b.process_events();
2945 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2947 // Should fail because of unknown required features
2948 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2953 fn test_chain_incompatible_peers() {
2954 let cfgs = create_peermgr_cfgs(2);
2955 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
2957 let peers = create_network(2, &cfgs);
2958 let incompatible_peers = create_network(2, &incompatible_cfgs);
2959 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2960 for (peer_a, peer_b) in peer_pairs.iter() {
2961 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2962 let mut fd_a = FileDescriptor {
2963 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2964 disconnect: Arc::new(AtomicBool::new(false)),
2966 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2967 let mut fd_b = FileDescriptor {
2968 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2969 disconnect: Arc::new(AtomicBool::new(false)),
2971 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2972 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2973 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2974 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2975 peer_a.process_events();
2977 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2978 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2980 peer_b.process_events();
2981 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2983 // Should fail because of incompatible chains
2984 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2989 fn test_disconnect_peer() {
2990 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2991 // push a DisconnectPeer event to remove the node flagged by id
2992 let cfgs = create_peermgr_cfgs(2);
2993 let peers = create_network(2, &cfgs);
2994 establish_connection(&peers[0], &peers[1]);
2995 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2997 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2998 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
3000 action: msgs::ErrorAction::DisconnectPeer { msg: None },
3003 peers[0].process_events();
3004 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3008 fn test_send_simple_msg() {
3009 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3010 // push a message from one peer to another.
3011 let cfgs = create_peermgr_cfgs(2);
3012 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3013 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
3014 let mut peers = create_network(2, &cfgs);
3015 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3016 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3018 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
3020 let msg = msgs::Shutdown { channel_id: ChannelId::from_bytes([42; 32]), scriptpubkey: bitcoin::ScriptBuf::new() };
3021 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
3022 node_id: their_id, msg: msg.clone()
3024 peers[0].message_handler.chan_handler = &a_chan_handler;
3026 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
3027 peers[1].message_handler.chan_handler = &b_chan_handler;
3029 peers[0].process_events();
3031 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3032 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3036 fn test_non_init_first_msg() {
3037 // Simple test of the first message received over a connection being something other than
3038 // Init. This results in an immediate disconnection, which previously included a spurious
3039 // peer_disconnected event handed to event handlers (which would panic in
3040 // `TestChannelMessageHandler` here).
3041 let cfgs = create_peermgr_cfgs(2);
3042 let peers = create_network(2, &cfgs);
3044 let mut fd_dup = FileDescriptor {
3045 fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
3046 disconnect: Arc::new(AtomicBool::new(false)),
3048 let addr_dup = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1003};
3049 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
3050 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
3052 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
3053 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
3054 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
3055 peers[0].process_events();
3057 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
3058 let (act_three, _) =
3059 dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
3060 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
3062 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
3063 let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg);
3064 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
3068 fn test_disconnect_all_peer() {
3069 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3070 // then calls disconnect_all_peers
3071 let cfgs = create_peermgr_cfgs(2);
3072 let peers = create_network(2, &cfgs);
3073 establish_connection(&peers[0], &peers[1]);
3074 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3076 peers[0].disconnect_all_peers();
3077 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3081 fn test_timer_tick_occurred() {
3082 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
3083 let cfgs = create_peermgr_cfgs(2);
3084 let peers = create_network(2, &cfgs);
3085 establish_connection(&peers[0], &peers[1]);
3086 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3088 // peers[0] awaiting_pong is set to true, but the Peer is still connected
3089 peers[0].timer_tick_occurred();
3090 peers[0].process_events();
3091 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3093 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
3094 peers[0].timer_tick_occurred();
3095 peers[0].process_events();
3096 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3100 fn test_do_attempt_write_data() {
3101 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
3102 let cfgs = create_peermgr_cfgs(2);
3103 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3104 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3105 let peers = create_network(2, &cfgs);
3107 // By calling establish_connect, we trigger do_attempt_write_data between
3108 // the peers. Previously this function would mistakenly enter an infinite loop
3109 // when there were more channel messages available than could fit into a peer's
3110 // buffer. This issue would now be detected by this test (because we use custom
3111 // RoutingMessageHandlers that intentionally return more channel messages
3112 // than can fit into a peer's buffer).
3113 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3115 // Make each peer to read the messages that the other peer just wrote to them. Note that
3116 // due to the max-message-before-ping limits this may take a few iterations to complete.
3117 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
3118 peers[1].process_events();
3119 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3120 assert!(!a_read_data.is_empty());
3122 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
3123 peers[0].process_events();
3125 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3126 assert!(!b_read_data.is_empty());
3127 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
3129 peers[0].process_events();
3130 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
3133 // Check that each peer has received the expected number of channel updates and channel
3135 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3136 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3137 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3138 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3142 fn test_handshake_timeout() {
3143 // Tests that we time out a peer still waiting on handshake completion after a full timer
3145 let cfgs = create_peermgr_cfgs(2);
3146 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3147 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3148 let peers = create_network(2, &cfgs);
3150 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
3151 let mut fd_a = FileDescriptor {
3152 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3153 disconnect: Arc::new(AtomicBool::new(false)),
3155 let mut fd_b = FileDescriptor {
3156 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3157 disconnect: Arc::new(AtomicBool::new(false)),
3159 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3160 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3162 // If we get a single timer tick before completion, that's fine
3163 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3164 peers[0].timer_tick_occurred();
3165 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3167 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3168 peers[0].process_events();
3169 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3170 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3171 peers[1].process_events();
3173 // ...but if we get a second timer tick, we should disconnect the peer
3174 peers[0].timer_tick_occurred();
3175 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3177 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3178 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3182 fn test_filter_addresses(){
3183 // Tests the filter_addresses function.
3186 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 0, 0], port: 1000};
3187 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3188 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 255, 201], port: 1000};
3189 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3190 let ip_address = SocketAddress::TcpIpV4{addr: [10, 255, 255, 255], port: 1000};
3191 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3194 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 0, 0], port: 1000};
3195 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3196 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 255, 187], port: 1000};
3197 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3198 let ip_address = SocketAddress::TcpIpV4{addr: [0, 255, 255, 255], port: 1000};
3199 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3202 let ip_address = SocketAddress::TcpIpV4{addr: [100, 64, 0, 0], port: 1000};
3203 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3204 let ip_address = SocketAddress::TcpIpV4{addr: [100, 78, 255, 0], port: 1000};
3205 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3206 let ip_address = SocketAddress::TcpIpV4{addr: [100, 127, 255, 255], port: 1000};
3207 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3210 let ip_address = SocketAddress::TcpIpV4{addr: [127, 0, 0, 0], port: 1000};
3211 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3212 let ip_address = SocketAddress::TcpIpV4{addr: [127, 65, 73, 0], port: 1000};
3213 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3214 let ip_address = SocketAddress::TcpIpV4{addr: [127, 255, 255, 255], port: 1000};
3215 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3218 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 0, 0], port: 1000};
3219 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3220 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 221, 101], port: 1000};
3221 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3222 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 255, 255], port: 1000};
3223 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3226 let ip_address = SocketAddress::TcpIpV4{addr: [172, 16, 0, 0], port: 1000};
3227 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3228 let ip_address = SocketAddress::TcpIpV4{addr: [172, 27, 101, 23], port: 1000};
3229 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3230 let ip_address = SocketAddress::TcpIpV4{addr: [172, 31, 255, 255], port: 1000};
3231 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3234 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 0, 0], port: 1000};
3235 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3236 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 205, 159], port: 1000};
3237 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3238 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 255, 255], port: 1000};
3239 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3241 // For (192.88.99/24)
3242 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 0], port: 1000};
3243 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3244 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 140], port: 1000};
3245 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3246 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 255], port: 1000};
3247 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3249 // For other IPv4 addresses
3250 let ip_address = SocketAddress::TcpIpV4{addr: [188, 255, 99, 0], port: 1000};
3251 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3252 let ip_address = SocketAddress::TcpIpV4{addr: [123, 8, 129, 14], port: 1000};
3253 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3254 let ip_address = SocketAddress::TcpIpV4{addr: [2, 88, 9, 255], port: 1000};
3255 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3258 let ip_address = SocketAddress::TcpIpV6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3259 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3260 let ip_address = SocketAddress::TcpIpV6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3261 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3262 let ip_address = SocketAddress::TcpIpV6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3263 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3265 // For other IPv6 addresses
3266 let ip_address = SocketAddress::TcpIpV6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3267 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3268 let ip_address = SocketAddress::TcpIpV6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3269 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3270 let ip_address = SocketAddress::TcpIpV6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3271 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3274 assert_eq!(filter_addresses(None), None);
3278 #[cfg(feature = "std")]
3279 fn test_process_events_multithreaded() {
3280 use std::time::{Duration, Instant};
3281 // Test that `process_events` getting called on multiple threads doesn't generate too many
3283 // Each time `process_events` goes around the loop we call
3284 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3285 // Because the loop should go around once more after a call which fails to take the
3286 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3287 // should never observe there having been more than 2 loop iterations.
3288 // Further, because the last thread to exit will call `process_events` before returning, we
3289 // should always have at least one count at the end.
3290 let cfg = Arc::new(create_peermgr_cfgs(1));
3291 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3292 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3294 let exit_flag = Arc::new(AtomicBool::new(false));
3295 macro_rules! spawn_thread { () => { {
3296 let thread_cfg = Arc::clone(&cfg);
3297 let thread_peer = Arc::clone(&peer);
3298 let thread_exit = Arc::clone(&exit_flag);
3299 std::thread::spawn(move || {
3300 while !thread_exit.load(Ordering::Acquire) {
3301 thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3302 thread_peer.process_events();
3303 std::thread::sleep(Duration::from_micros(1));
3308 let thread_a = spawn_thread!();
3309 let thread_b = spawn_thread!();
3310 let thread_c = spawn_thread!();
3312 let start_time = Instant::now();
3313 while start_time.elapsed() < Duration::from_millis(100) {
3314 let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3316 std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3319 exit_flag.store(true, Ordering::Release);
3320 thread_a.join().unwrap();
3321 thread_b.join().unwrap();
3322 thread_c.join().unwrap();
3323 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);