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 #[cfg(not(c_bindings))]
28 use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
29 use crate::util::ser::{VecWriter, Writeable, Writer};
30 use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor, NextNoiseStep, MessageBuf, MSG_BUF_ALLOC_SIZE};
32 use crate::ln::wire::{Encode, Type};
33 #[cfg(not(c_bindings))]
34 use crate::onion_message::messenger::{SimpleArcOnionMessenger, SimpleRefOnionMessenger};
35 use crate::onion_message::messenger::{CustomOnionMessageHandler, PendingOnionMessage};
36 use crate::onion_message::offers::{OffersMessage, OffersMessageHandler};
37 use crate::onion_message::packet::OnionMessageContents;
38 use crate::routing::gossip::{NodeId, NodeAlias};
39 use crate::util::atomic_counter::AtomicCounter;
40 use crate::util::logger::{Logger, WithContext};
41 use crate::util::string::PrintableString;
43 use crate::prelude::*;
45 use alloc::collections::VecDeque;
46 use crate::sync::{Mutex, MutexGuard, FairRwLock};
47 use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering};
48 use core::{cmp, hash, fmt, mem};
50 use core::convert::Infallible;
51 #[cfg(feature = "std")]
53 #[cfg(not(c_bindings))]
55 crate::routing::gossip::{NetworkGraph, P2PGossipSync},
56 crate::sign::KeysManager,
60 use bitcoin::hashes::sha256::Hash as Sha256;
61 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
62 use bitcoin::hashes::{HashEngine, Hash};
64 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
66 /// [BOLT 1] specifies a custom message type range for use with experimental or application-specific
67 /// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the
68 /// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler.
70 /// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
71 /// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message
72 pub trait CustomMessageHandler: wire::CustomMessageReader {
73 /// Handles the given message sent from `sender_node_id`, possibly producing messages for
74 /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`]
76 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
78 /// Returns the list of pending messages that were generated by the handler, clearing the list
79 /// in the process. Each message is paired with the node id of the intended recipient. If no
80 /// connection to the node exists, then the message is simply not sent.
81 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
83 /// Gets the node feature flags which this handler itself supports. All available handlers are
84 /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
85 /// which are broadcasted in our [`NodeAnnouncement`] message.
87 /// [`NodeAnnouncement`]: crate::ln::msgs::NodeAnnouncement
88 fn provided_node_features(&self) -> NodeFeatures;
90 /// Gets the init feature flags which should be sent to the given peer. All available handlers
91 /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
92 /// which are sent in our [`Init`] message.
94 /// [`Init`]: crate::ln::msgs::Init
95 fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
98 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
99 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
100 pub struct IgnoringMessageHandler{}
101 impl EventsProvider for IgnoringMessageHandler {
102 fn process_pending_events<H: Deref>(&self, _handler: H) where H::Target: EventHandler {}
104 impl MessageSendEventsProvider for IgnoringMessageHandler {
105 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
107 impl RoutingMessageHandler for IgnoringMessageHandler {
108 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
109 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
110 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
111 fn get_next_channel_announcement(&self, _starting_point: u64) ->
112 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
113 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
114 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
115 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
116 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
117 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
118 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
119 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
120 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
121 InitFeatures::empty()
123 fn processing_queue_high(&self) -> bool { false }
125 impl OnionMessageHandler for IgnoringMessageHandler {
126 fn get_and_clear_connections_needed(&self) -> Vec<(PublicKey, Vec<SocketAddress>)> { Vec::new() }
127 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
128 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
129 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
130 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
131 fn timer_tick_occurred(&self) {}
132 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
133 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
134 InitFeatures::empty()
137 impl OffersMessageHandler for IgnoringMessageHandler {
138 fn handle_message(&self, _msg: OffersMessage) -> Option<OffersMessage> { None }
140 impl CustomOnionMessageHandler for IgnoringMessageHandler {
141 type CustomMessage = Infallible;
142 fn handle_custom_message(&self, _msg: Infallible) -> Option<Infallible> {
143 // Since we always return `None` in the read the handle method should never be called.
146 fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
149 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Infallible>> {
154 impl OnionMessageContents for Infallible {
155 fn tlv_type(&self) -> u64 { unreachable!(); }
158 impl Deref for IgnoringMessageHandler {
159 type Target = IgnoringMessageHandler;
160 fn deref(&self) -> &Self { self }
163 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
164 // method that takes self for it.
165 impl wire::Type for Infallible {
166 fn type_id(&self) -> u16 {
170 impl Writeable for Infallible {
171 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
176 impl wire::CustomMessageReader for IgnoringMessageHandler {
177 type CustomMessage = Infallible;
178 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
183 impl CustomMessageHandler for IgnoringMessageHandler {
184 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
185 // Since we always return `None` in the read the handle method should never be called.
189 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
191 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
193 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
194 InitFeatures::empty()
198 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
199 /// You can provide one of these as the route_handler in a MessageHandler.
200 pub struct ErroringMessageHandler {
201 message_queue: Mutex<Vec<MessageSendEvent>>
203 impl ErroringMessageHandler {
204 /// Constructs a new ErroringMessageHandler
205 pub fn new() -> Self {
206 Self { message_queue: Mutex::new(Vec::new()) }
208 fn push_error(&self, node_id: &PublicKey, channel_id: ChannelId) {
209 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
210 action: msgs::ErrorAction::SendErrorMessage {
211 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
213 node_id: node_id.clone(),
217 impl MessageSendEventsProvider for ErroringMessageHandler {
218 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
219 let mut res = Vec::new();
220 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
224 impl ChannelMessageHandler for ErroringMessageHandler {
225 // Any messages which are related to a specific channel generate an error message to let the
226 // peer know we don't care about channels.
227 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
228 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
230 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
231 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
233 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
234 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
236 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
237 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
239 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
240 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
242 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
243 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
245 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
246 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
248 fn handle_stfu(&self, their_node_id: &PublicKey, msg: &msgs::Stfu) {
249 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
251 fn handle_splice(&self, their_node_id: &PublicKey, msg: &msgs::Splice) {
252 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
254 fn handle_splice_ack(&self, their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
255 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
257 fn handle_splice_locked(&self, their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
258 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
260 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
261 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
263 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
264 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
266 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
267 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
269 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
270 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
272 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
273 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
275 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
276 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
278 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
279 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
281 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
282 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
284 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
285 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
287 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
288 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
289 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
290 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
291 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
292 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
293 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
294 // Set a number of features which various nodes may require to talk to us. It's totally
295 // reasonable to indicate we "support" all kinds of channel features...we just reject all
297 let mut features = InitFeatures::empty();
298 features.set_data_loss_protect_optional();
299 features.set_upfront_shutdown_script_optional();
300 features.set_variable_length_onion_optional();
301 features.set_static_remote_key_optional();
302 features.set_payment_secret_optional();
303 features.set_basic_mpp_optional();
304 features.set_wumbo_optional();
305 features.set_shutdown_any_segwit_optional();
306 features.set_channel_type_optional();
307 features.set_scid_privacy_optional();
308 features.set_zero_conf_optional();
309 features.set_route_blinding_optional();
313 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
314 // We don't enforce any chains upon peer connection for `ErroringMessageHandler` and leave it up
315 // to users of `ErroringMessageHandler` to make decisions on network compatiblility.
316 // There's not really any way to pull in specific networks here, and hardcoding can cause breakages.
320 fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
321 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
324 fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
325 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
328 fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
329 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
332 fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
333 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
336 fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
337 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
340 fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
341 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
344 fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &msgs::TxComplete) {
345 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
348 fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
349 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
352 fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
353 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
356 fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
357 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
360 fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &msgs::TxAbort) {
361 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
365 impl Deref for ErroringMessageHandler {
366 type Target = ErroringMessageHandler;
367 fn deref(&self) -> &Self { self }
370 /// Provides references to trait impls which handle different types of messages.
371 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref, CustomM: Deref> where
372 CM::Target: ChannelMessageHandler,
373 RM::Target: RoutingMessageHandler,
374 OM::Target: OnionMessageHandler,
375 CustomM::Target: CustomMessageHandler,
377 /// A message handler which handles messages specific to channels. Usually this is just a
378 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
380 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
381 pub chan_handler: CM,
382 /// A message handler which handles messages updating our knowledge of the network channel
383 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
385 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
386 pub route_handler: RM,
388 /// A message handler which handles onion messages. This should generally be an
389 /// [`OnionMessenger`], but can also be an [`IgnoringMessageHandler`].
391 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
392 pub onion_message_handler: OM,
394 /// A message handler which handles custom messages. The only LDK-provided implementation is
395 /// [`IgnoringMessageHandler`].
396 pub custom_message_handler: CustomM,
399 /// Provides an object which can be used to send data to and which uniquely identifies a connection
400 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
401 /// implement Hash to meet the PeerManager API.
403 /// For efficiency, [`Clone`] should be relatively cheap for this type.
405 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
406 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
407 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
408 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
409 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
410 /// to simply use another value which is guaranteed to be globally unique instead.
411 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
412 /// Attempts to send some data from the given slice to the peer.
414 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
415 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
416 /// called and further write attempts may occur until that time.
418 /// If the returned size is smaller than `data.len()`, a
419 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
420 /// written. Additionally, until a `send_data` event completes fully, no further
421 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
422 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
425 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
426 /// (indicating that read events should be paused to prevent DoS in the send buffer),
427 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
428 /// `resume_read` of false carries no meaning, and should not cause any action.
429 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
430 /// Disconnect the socket pointed to by this SocketDescriptor.
432 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
433 /// call (doing so is a noop).
434 fn disconnect_socket(&mut self);
437 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
438 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
441 pub struct PeerHandleError { }
442 impl fmt::Debug for PeerHandleError {
443 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
444 formatter.write_str("Peer Sent Invalid Data")
447 impl fmt::Display for PeerHandleError {
448 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
449 formatter.write_str("Peer Sent Invalid Data")
453 #[cfg(feature = "std")]
454 impl error::Error for PeerHandleError {
455 fn description(&self) -> &str {
456 "Peer Sent Invalid Data"
460 enum InitSyncTracker{
462 ChannelsSyncing(u64),
463 NodesSyncing(NodeId),
466 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
467 /// forwarding gossip messages to peers altogether.
468 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
470 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
471 /// we have fewer than this many messages in the outbound buffer again.
472 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
473 /// refilled as we send bytes.
474 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
475 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
477 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
479 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
480 /// the socket receive buffer before receiving the ping.
482 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
483 /// including any network delays, outbound traffic, or the same for messages from other peers.
485 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
486 /// per connected peer to respond to a ping, as long as they send us at least one message during
487 /// each tick, ensuring we aren't actually just disconnected.
488 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
491 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
492 /// two connected peers, assuming most LDK-running systems have at least two cores.
493 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
495 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
496 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
497 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
498 /// process before the next ping.
500 /// Note that we continue responding to other messages even after we've sent this many messages, so
501 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
502 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
503 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
506 channel_encryptor: PeerChannelEncryptor,
507 /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
508 /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
509 their_node_id: Option<(PublicKey, NodeId)>,
510 /// The features provided in the peer's [`msgs::Init`] message.
512 /// This is set only after we've processed the [`msgs::Init`] message and called relevant
513 /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
514 /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
516 their_features: Option<InitFeatures>,
517 their_socket_address: Option<SocketAddress>,
519 pending_outbound_buffer: VecDeque<Vec<u8>>,
520 pending_outbound_buffer_first_msg_offset: usize,
521 /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
522 /// prioritize channel messages over them.
524 /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
525 gossip_broadcast_buffer: VecDeque<MessageBuf>,
526 awaiting_write_event: bool,
528 pending_read_buffer: Vec<u8>,
529 pending_read_buffer_pos: usize,
530 pending_read_is_header: bool,
532 sync_status: InitSyncTracker,
534 msgs_sent_since_pong: usize,
535 awaiting_pong_timer_tick_intervals: i64,
536 received_message_since_timer_tick: bool,
537 sent_gossip_timestamp_filter: bool,
539 /// Indicates we've received a `channel_announcement` since the last time we had
540 /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
541 /// `channel_announcement` at all - we set this unconditionally but unset it every time we
542 /// check if we're gossip-processing-backlogged).
543 received_channel_announce_since_backlogged: bool,
545 inbound_connection: bool,
549 /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
550 /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
552 fn handshake_complete(&self) -> bool {
553 self.their_features.is_some()
556 /// Returns true if the channel announcements/updates for the given channel should be
557 /// forwarded to this peer.
558 /// If we are sending our routing table to this peer and we have not yet sent channel
559 /// announcements/updates for the given channel_id then we will send it when we get to that
560 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
561 /// sent the old versions, we should send the update, and so return true here.
562 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
563 if !self.handshake_complete() { return false; }
564 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
565 !self.sent_gossip_timestamp_filter {
568 match self.sync_status {
569 InitSyncTracker::NoSyncRequested => true,
570 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
571 InitSyncTracker::NodesSyncing(_) => true,
575 /// Similar to the above, but for node announcements indexed by node_id.
576 fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
577 if !self.handshake_complete() { return false; }
578 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
579 !self.sent_gossip_timestamp_filter {
582 match self.sync_status {
583 InitSyncTracker::NoSyncRequested => true,
584 InitSyncTracker::ChannelsSyncing(_) => false,
585 InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
589 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
590 /// buffer still has space and we don't need to pause reads to get some writes out.
591 fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
592 if !gossip_processing_backlogged {
593 self.received_channel_announce_since_backlogged = false;
595 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
596 (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
599 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
600 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
601 fn should_buffer_gossip_backfill(&self) -> bool {
602 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
603 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
604 && self.handshake_complete()
607 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
608 /// every time the peer's buffer may have been drained.
609 fn should_buffer_onion_message(&self) -> bool {
610 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
611 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
614 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
615 /// buffer. This is checked every time the peer's buffer may have been drained.
616 fn should_buffer_gossip_broadcast(&self) -> bool {
617 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
618 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
621 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
622 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
623 let total_outbound_buffered =
624 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
626 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
627 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
630 fn set_their_node_id(&mut self, node_id: PublicKey) {
631 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
635 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
636 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
637 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
638 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
639 /// issues such as overly long function definitions.
641 /// This is not exported to bindings users as type aliases aren't supported in most languages.
642 #[cfg(not(c_bindings))]
643 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<
645 Arc<SimpleArcChannelManager<M, T, F, L>>,
646 Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, C, Arc<L>>>,
647 Arc<SimpleArcOnionMessenger<M, T, F, L>>,
649 IgnoringMessageHandler,
653 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
654 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
655 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
656 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
657 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
658 /// helps with issues such as 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 SimpleRefPeerManager<
663 'a, 'b, 'c, 'd, 'e, 'f, 'logger, 'h, 'i, 'j, 'graph, 'k, SD, M, T, F, C, L
666 &'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, M, T, F, L>,
667 &'f P2PGossipSync<&'graph NetworkGraph<&'logger L>, C, &'logger L>,
668 &'h SimpleRefOnionMessenger<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, 'j, 'k, M, T, F, L>,
670 IgnoringMessageHandler,
675 /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or
676 /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather
677 /// than the full set of bounds on [`PeerManager`] itself.
679 /// This is not exported to bindings users as general cover traits aren't useful in other
681 #[allow(missing_docs)]
682 pub trait APeerManager {
683 type Descriptor: SocketDescriptor;
684 type CMT: ChannelMessageHandler + ?Sized;
685 type CM: Deref<Target=Self::CMT>;
686 type RMT: RoutingMessageHandler + ?Sized;
687 type RM: Deref<Target=Self::RMT>;
688 type OMT: OnionMessageHandler + ?Sized;
689 type OM: Deref<Target=Self::OMT>;
690 type LT: Logger + ?Sized;
691 type L: Deref<Target=Self::LT>;
692 type CMHT: CustomMessageHandler + ?Sized;
693 type CMH: Deref<Target=Self::CMHT>;
694 type NST: NodeSigner + ?Sized;
695 type NS: Deref<Target=Self::NST>;
696 /// Gets a reference to the underlying [`PeerManager`].
697 fn as_ref(&self) -> &PeerManager<Self::Descriptor, Self::CM, Self::RM, Self::OM, Self::L, Self::CMH, Self::NS>;
698 /// Returns the peer manager's [`OnionMessageHandler`].
699 fn onion_message_handler(&self) -> &Self::OMT;
702 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref>
703 APeerManager for PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
704 CM::Target: ChannelMessageHandler,
705 RM::Target: RoutingMessageHandler,
706 OM::Target: OnionMessageHandler,
708 CMH::Target: CustomMessageHandler,
709 NS::Target: NodeSigner,
711 type Descriptor = Descriptor;
712 type CMT = <CM as Deref>::Target;
714 type RMT = <RM as Deref>::Target;
716 type OMT = <OM as Deref>::Target;
718 type LT = <L as Deref>::Target;
720 type CMHT = <CMH as Deref>::Target;
722 type NST = <NS as Deref>::Target;
724 fn as_ref(&self) -> &PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> { self }
725 fn onion_message_handler(&self) -> &Self::OMT {
726 self.message_handler.onion_message_handler.deref()
730 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
731 /// socket events into messages which it passes on to its [`MessageHandler`].
733 /// Locks are taken internally, so you must never assume that reentrancy from a
734 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
736 /// Calls to [`read_event`] will decode relevant messages and pass them to the
737 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
738 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
739 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
740 /// calls only after previous ones have returned.
742 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
743 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
744 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
745 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
746 /// you're using lightning-net-tokio.
748 /// [`read_event`]: PeerManager::read_event
749 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
750 CM::Target: ChannelMessageHandler,
751 RM::Target: RoutingMessageHandler,
752 OM::Target: OnionMessageHandler,
754 CMH::Target: CustomMessageHandler,
755 NS::Target: NodeSigner {
756 message_handler: MessageHandler<CM, RM, OM, CMH>,
757 /// Connection state for each connected peer - we have an outer read-write lock which is taken
758 /// as read while we're doing processing for a peer and taken write when a peer is being added
761 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
762 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
763 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
764 /// the `MessageHandler`s for a given peer is already guaranteed.
765 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
766 /// Only add to this set when noise completes.
767 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
768 /// lock held. Entries may be added with only the `peers` read lock held (though the
769 /// `Descriptor` value must already exist in `peers`).
770 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
771 /// We can only have one thread processing events at once, but if a second call to
772 /// `process_events` happens while a first call is in progress, one of the two calls needs to
773 /// start from the top to ensure any new messages are also handled.
775 /// Because the event handler calls into user code which may block, we don't want to block a
776 /// second thread waiting for another thread to handle events which is then blocked on user
777 /// code, so we store an atomic counter here:
778 /// * 0 indicates no event processor is running
779 /// * 1 indicates an event processor is running
780 /// * > 1 indicates an event processor is running but needs to start again from the top once
781 /// it finishes as another thread tried to start processing events but returned early.
782 event_processing_state: AtomicI32,
784 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
785 /// value increases strictly since we don't assume access to a time source.
786 last_node_announcement_serial: AtomicU32,
788 ephemeral_key_midstate: Sha256Engine,
790 peer_counter: AtomicCounter,
792 gossip_processing_backlogged: AtomicBool,
793 gossip_processing_backlog_lifted: AtomicBool,
798 secp_ctx: Secp256k1<secp256k1::SignOnly>
801 enum MessageHandlingError {
802 PeerHandleError(PeerHandleError),
803 LightningError(LightningError),
806 impl From<PeerHandleError> for MessageHandlingError {
807 fn from(error: PeerHandleError) -> Self {
808 MessageHandlingError::PeerHandleError(error)
812 impl From<LightningError> for MessageHandlingError {
813 fn from(error: LightningError) -> Self {
814 MessageHandlingError::LightningError(error)
818 macro_rules! encode_msg {
820 let mut buffer = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
821 wire::write($msg, &mut buffer).unwrap();
826 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
827 CM::Target: ChannelMessageHandler,
828 OM::Target: OnionMessageHandler,
830 NS::Target: NodeSigner {
831 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
832 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
835 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
836 /// cryptographically secure random bytes.
838 /// `current_time` is used as an always-increasing counter that survives across restarts and is
839 /// incremented irregularly internally. In general it is best to simply use the current UNIX
840 /// timestamp, however if it is not available a persistent counter that increases once per
841 /// minute should suffice.
843 /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
844 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 {
845 Self::new(MessageHandler {
846 chan_handler: channel_message_handler,
847 route_handler: IgnoringMessageHandler{},
848 onion_message_handler,
849 custom_message_handler: IgnoringMessageHandler{},
850 }, current_time, ephemeral_random_data, logger, node_signer)
854 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
855 RM::Target: RoutingMessageHandler,
857 NS::Target: NodeSigner {
858 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
859 /// handler or onion message handler is used and onion and channel messages will be ignored (or
860 /// generate error messages). Note that some other lightning implementations time-out connections
861 /// after some time if no channel is built with the peer.
863 /// `current_time` is used as an always-increasing counter that survives across restarts and is
864 /// incremented irregularly internally. In general it is best to simply use the current UNIX
865 /// timestamp, however if it is not available a persistent counter that increases once per
866 /// minute should suffice.
868 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
869 /// cryptographically secure random bytes.
871 /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
872 pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
873 Self::new(MessageHandler {
874 chan_handler: ErroringMessageHandler::new(),
875 route_handler: routing_message_handler,
876 onion_message_handler: IgnoringMessageHandler{},
877 custom_message_handler: IgnoringMessageHandler{},
878 }, current_time, ephemeral_random_data, logger, node_signer)
882 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
883 /// This works around `format!()` taking a reference to each argument, preventing
884 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
885 /// due to lifetime errors.
886 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
887 impl core::fmt::Display for OptionalFromDebugger<'_> {
888 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
889 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
893 /// A function used to filter out local or private addresses
894 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
895 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
896 fn filter_addresses(ip_address: Option<SocketAddress>) -> Option<SocketAddress> {
898 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
899 Some(SocketAddress::TcpIpV4{addr: [10, _, _, _], port: _}) => None,
900 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
901 Some(SocketAddress::TcpIpV4{addr: [0, _, _, _], port: _}) => None,
902 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
903 Some(SocketAddress::TcpIpV4{addr: [100, 64..=127, _, _], port: _}) => None,
904 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
905 Some(SocketAddress::TcpIpV4{addr: [127, _, _, _], port: _}) => None,
906 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
907 Some(SocketAddress::TcpIpV4{addr: [169, 254, _, _], port: _}) => None,
908 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
909 Some(SocketAddress::TcpIpV4{addr: [172, 16..=31, _, _], port: _}) => None,
910 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
911 Some(SocketAddress::TcpIpV4{addr: [192, 168, _, _], port: _}) => None,
912 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
913 Some(SocketAddress::TcpIpV4{addr: [192, 88, 99, _], port: _}) => None,
914 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
915 Some(SocketAddress::TcpIpV6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
916 // For remaining addresses
917 Some(SocketAddress::TcpIpV6{addr: _, port: _}) => None,
918 Some(..) => ip_address,
923 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
924 CM::Target: ChannelMessageHandler,
925 RM::Target: RoutingMessageHandler,
926 OM::Target: OnionMessageHandler,
928 CMH::Target: CustomMessageHandler,
929 NS::Target: NodeSigner
931 /// Constructs a new `PeerManager` with the given message handlers.
933 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
934 /// cryptographically secure random bytes.
936 /// `current_time` is used as an always-increasing counter that survives across restarts and is
937 /// incremented irregularly internally. In general it is best to simply use the current UNIX
938 /// timestamp, however if it is not available a persistent counter that increases once per
939 /// minute should suffice.
940 pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
941 let mut ephemeral_key_midstate = Sha256::engine();
942 ephemeral_key_midstate.input(ephemeral_random_data);
944 let mut secp_ctx = Secp256k1::signing_only();
945 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).to_byte_array();
946 secp_ctx.seeded_randomize(&ephemeral_hash);
950 peers: FairRwLock::new(HashMap::new()),
951 node_id_to_descriptor: Mutex::new(HashMap::new()),
952 event_processing_state: AtomicI32::new(0),
953 ephemeral_key_midstate,
954 peer_counter: AtomicCounter::new(),
955 gossip_processing_backlogged: AtomicBool::new(false),
956 gossip_processing_backlog_lifted: AtomicBool::new(false),
957 last_node_announcement_serial: AtomicU32::new(current_time),
964 /// Get a list of tuples mapping from node id to network addresses for peers which have
965 /// completed the initial handshake.
967 /// For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter
968 /// passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial
969 /// handshake has completed and we are sure the remote peer has the private key for the given
972 /// The returned `Option`s will only be `Some` if an address had been previously given via
973 /// [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`].
974 pub fn get_peer_node_ids(&self) -> Vec<(PublicKey, Option<SocketAddress>)> {
975 let peers = self.peers.read().unwrap();
976 peers.values().filter_map(|peer_mutex| {
977 let p = peer_mutex.lock().unwrap();
978 if !p.handshake_complete() {
981 Some((p.their_node_id.unwrap().0, p.their_socket_address.clone()))
985 fn get_ephemeral_key(&self) -> SecretKey {
986 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
987 let counter = self.peer_counter.get_increment();
988 ephemeral_hash.input(&counter.to_le_bytes());
989 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).to_byte_array()).expect("You broke SHA-256!")
992 fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
993 self.message_handler.chan_handler.provided_init_features(their_node_id)
994 | self.message_handler.route_handler.provided_init_features(their_node_id)
995 | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
996 | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
999 /// Indicates a new outbound connection has been established to a node with the given `node_id`
1000 /// and an optional remote network address.
1002 /// The remote network address adds the option to report a remote IP address back to a connecting
1003 /// peer using the init message.
1004 /// The user should pass the remote network address of the host they are connected to.
1006 /// If an `Err` is returned here you must disconnect the connection immediately.
1008 /// Returns a small number of bytes to send to the remote node (currently always 50).
1010 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1011 /// [`socket_disconnected`].
1013 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1014 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<Vec<u8>, PeerHandleError> {
1015 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
1016 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
1017 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
1019 let mut peers = self.peers.write().unwrap();
1020 match peers.entry(descriptor) {
1021 hash_map::Entry::Occupied(_) => {
1022 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1023 Err(PeerHandleError {})
1025 hash_map::Entry::Vacant(e) => {
1026 e.insert(Mutex::new(Peer {
1027 channel_encryptor: peer_encryptor,
1028 their_node_id: None,
1029 their_features: None,
1030 their_socket_address: remote_network_address,
1032 pending_outbound_buffer: VecDeque::new(),
1033 pending_outbound_buffer_first_msg_offset: 0,
1034 gossip_broadcast_buffer: VecDeque::new(),
1035 awaiting_write_event: false,
1037 pending_read_buffer,
1038 pending_read_buffer_pos: 0,
1039 pending_read_is_header: false,
1041 sync_status: InitSyncTracker::NoSyncRequested,
1043 msgs_sent_since_pong: 0,
1044 awaiting_pong_timer_tick_intervals: 0,
1045 received_message_since_timer_tick: false,
1046 sent_gossip_timestamp_filter: false,
1048 received_channel_announce_since_backlogged: false,
1049 inbound_connection: false,
1056 /// Indicates a new inbound connection has been established to a node with an optional remote
1057 /// network address.
1059 /// The remote network address adds the option to report a remote IP address back to a connecting
1060 /// peer using the init message.
1061 /// The user should pass the remote network address of the host they are connected to.
1063 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
1064 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
1065 /// the connection immediately.
1067 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1068 /// [`socket_disconnected`].
1070 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1071 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<(), PeerHandleError> {
1072 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1073 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1075 let mut peers = self.peers.write().unwrap();
1076 match peers.entry(descriptor) {
1077 hash_map::Entry::Occupied(_) => {
1078 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1079 Err(PeerHandleError {})
1081 hash_map::Entry::Vacant(e) => {
1082 e.insert(Mutex::new(Peer {
1083 channel_encryptor: peer_encryptor,
1084 their_node_id: None,
1085 their_features: None,
1086 their_socket_address: remote_network_address,
1088 pending_outbound_buffer: VecDeque::new(),
1089 pending_outbound_buffer_first_msg_offset: 0,
1090 gossip_broadcast_buffer: VecDeque::new(),
1091 awaiting_write_event: false,
1093 pending_read_buffer,
1094 pending_read_buffer_pos: 0,
1095 pending_read_is_header: false,
1097 sync_status: InitSyncTracker::NoSyncRequested,
1099 msgs_sent_since_pong: 0,
1100 awaiting_pong_timer_tick_intervals: 0,
1101 received_message_since_timer_tick: false,
1102 sent_gossip_timestamp_filter: false,
1104 received_channel_announce_since_backlogged: false,
1105 inbound_connection: true,
1112 fn peer_should_read(&self, peer: &mut Peer) -> bool {
1113 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1116 fn update_gossip_backlogged(&self) {
1117 let new_state = self.message_handler.route_handler.processing_queue_high();
1118 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1119 if prev_state && !new_state {
1120 self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1124 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1125 let mut have_written = false;
1126 while !peer.awaiting_write_event {
1127 if peer.should_buffer_onion_message() {
1128 if let Some((peer_node_id, _)) = peer.their_node_id {
1129 if let Some(next_onion_message) =
1130 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1131 self.enqueue_message(peer, &next_onion_message);
1135 if peer.should_buffer_gossip_broadcast() {
1136 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1137 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(msg));
1140 if peer.should_buffer_gossip_backfill() {
1141 match peer.sync_status {
1142 InitSyncTracker::NoSyncRequested => {},
1143 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1144 if let Some((announce, update_a_option, update_b_option)) =
1145 self.message_handler.route_handler.get_next_channel_announcement(c)
1147 self.enqueue_message(peer, &announce);
1148 if let Some(update_a) = update_a_option {
1149 self.enqueue_message(peer, &update_a);
1151 if let Some(update_b) = update_b_option {
1152 self.enqueue_message(peer, &update_b);
1154 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1156 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1159 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1160 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1161 self.enqueue_message(peer, &msg);
1162 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1164 peer.sync_status = InitSyncTracker::NoSyncRequested;
1167 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1168 InitSyncTracker::NodesSyncing(sync_node_id) => {
1169 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1170 self.enqueue_message(peer, &msg);
1171 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1173 peer.sync_status = InitSyncTracker::NoSyncRequested;
1178 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1179 self.maybe_send_extra_ping(peer);
1182 let should_read = self.peer_should_read(peer);
1183 let next_buff = match peer.pending_outbound_buffer.front() {
1185 if force_one_write && !have_written {
1187 let data_sent = descriptor.send_data(&[], should_read);
1188 debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1196 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1197 let data_sent = descriptor.send_data(pending, should_read);
1198 have_written = true;
1199 peer.pending_outbound_buffer_first_msg_offset += data_sent;
1200 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1201 peer.pending_outbound_buffer_first_msg_offset = 0;
1202 peer.pending_outbound_buffer.pop_front();
1203 const VEC_SIZE: usize = ::core::mem::size_of::<Vec<u8>>();
1204 let large_capacity = peer.pending_outbound_buffer.capacity() > 4096 / VEC_SIZE;
1205 let lots_of_slack = peer.pending_outbound_buffer.len()
1206 < peer.pending_outbound_buffer.capacity() / 2;
1207 if large_capacity && lots_of_slack {
1208 peer.pending_outbound_buffer.shrink_to_fit();
1211 peer.awaiting_write_event = true;
1216 /// Indicates that there is room to write data to the given socket descriptor.
1218 /// May return an Err to indicate that the connection should be closed.
1220 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1221 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1222 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1223 /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1226 /// [`send_data`]: SocketDescriptor::send_data
1227 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1228 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1229 let peers = self.peers.read().unwrap();
1230 match peers.get(descriptor) {
1232 // This is most likely a simple race condition where the user found that the socket
1233 // was writeable, then we told the user to `disconnect_socket()`, then they called
1234 // this method. Return an error to make sure we get disconnected.
1235 return Err(PeerHandleError { });
1237 Some(peer_mutex) => {
1238 let mut peer = peer_mutex.lock().unwrap();
1239 peer.awaiting_write_event = false;
1240 self.do_attempt_write_data(descriptor, &mut peer, false);
1246 /// Indicates that data was read from the given socket descriptor.
1248 /// May return an Err to indicate that the connection should be closed.
1250 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1251 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1252 /// [`send_data`] calls to handle responses.
1254 /// If `Ok(true)` is returned, further read_events should not be triggered until a
1255 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1258 /// In order to avoid processing too many messages at once per peer, `data` should be on the
1261 /// [`send_data`]: SocketDescriptor::send_data
1262 /// [`process_events`]: PeerManager::process_events
1263 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1264 match self.do_read_event(peer_descriptor, data) {
1267 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1268 self.disconnect_event_internal(peer_descriptor);
1274 /// Append a message to a peer's pending outbound/write buffer
1275 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1276 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1277 if is_gossip_msg(message.type_id()) {
1278 log_gossip!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1280 log_trace!(logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1282 peer.msgs_sent_since_pong += 1;
1283 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1286 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1287 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: MessageBuf) {
1288 peer.msgs_sent_since_pong += 1;
1289 debug_assert!(peer.gossip_broadcast_buffer.len() <= OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP);
1290 peer.gossip_broadcast_buffer.push_back(encoded_message);
1293 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1294 let mut pause_read = false;
1295 let peers = self.peers.read().unwrap();
1296 let mut msgs_to_forward = Vec::new();
1297 let mut peer_node_id = None;
1298 match peers.get(peer_descriptor) {
1300 // This is most likely a simple race condition where the user read some bytes
1301 // from the socket, then we told the user to `disconnect_socket()`, then they
1302 // called this method. Return an error to make sure we get disconnected.
1303 return Err(PeerHandleError { });
1305 Some(peer_mutex) => {
1306 let mut read_pos = 0;
1307 while read_pos < data.len() {
1308 macro_rules! try_potential_handleerror {
1309 ($peer: expr, $thing: expr) => {{
1311 let logger = WithContext::from(&self.logger, peer_node_id.map(|(id, _)| id), None);
1316 msgs::ErrorAction::DisconnectPeer { .. } => {
1317 // We may have an `ErrorMessage` to send to the peer,
1318 // but writing to the socket while reading can lead to
1319 // re-entrant code and possibly unexpected behavior. The
1320 // message send is optimistic anyway, and in this case
1321 // we immediately disconnect the peer.
1322 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1323 return Err(PeerHandleError { });
1325 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1326 // We have a `WarningMessage` to send to the peer, but
1327 // writing to the socket while reading can lead to
1328 // re-entrant code and possibly unexpected behavior. The
1329 // message send is optimistic anyway, and in this case
1330 // we immediately disconnect the peer.
1331 log_debug!(logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1332 return Err(PeerHandleError { });
1334 msgs::ErrorAction::IgnoreAndLog(level) => {
1335 log_given_level!(logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1338 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1339 msgs::ErrorAction::IgnoreError => {
1340 log_debug!(logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1343 msgs::ErrorAction::SendErrorMessage { msg } => {
1344 log_debug!(logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1345 self.enqueue_message($peer, &msg);
1348 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1349 log_given_level!(logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1350 self.enqueue_message($peer, &msg);
1359 let mut peer_lock = peer_mutex.lock().unwrap();
1360 let peer = &mut *peer_lock;
1361 let mut msg_to_handle = None;
1362 if peer_node_id.is_none() {
1363 peer_node_id = peer.their_node_id.clone();
1366 assert!(peer.pending_read_buffer.len() > 0);
1367 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1370 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1371 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]);
1372 read_pos += data_to_copy;
1373 peer.pending_read_buffer_pos += data_to_copy;
1376 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1377 peer.pending_read_buffer_pos = 0;
1379 macro_rules! insert_node_id {
1381 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1382 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1383 hash_map::Entry::Occupied(e) => {
1384 log_trace!(logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1385 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1386 // Check that the peers map is consistent with the
1387 // node_id_to_descriptor map, as this has been broken
1389 debug_assert!(peers.get(e.get()).is_some());
1390 return Err(PeerHandleError { })
1392 hash_map::Entry::Vacant(entry) => {
1393 log_debug!(logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1394 entry.insert(peer_descriptor.clone())
1400 let next_step = peer.channel_encryptor.get_noise_step();
1402 NextNoiseStep::ActOne => {
1403 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1404 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1405 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1406 peer.pending_outbound_buffer.push_back(act_two);
1407 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1409 NextNoiseStep::ActTwo => {
1410 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1411 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1412 &self.node_signer));
1413 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1414 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1415 peer.pending_read_is_header = true;
1417 peer.set_their_node_id(their_node_id);
1419 let features = self.init_features(&their_node_id);
1420 let networks = self.message_handler.chan_handler.get_chain_hashes();
1421 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1422 self.enqueue_message(peer, &resp);
1423 peer.awaiting_pong_timer_tick_intervals = 0;
1425 NextNoiseStep::ActThree => {
1426 let their_node_id = try_potential_handleerror!(peer,
1427 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1428 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1429 peer.pending_read_is_header = true;
1430 peer.set_their_node_id(their_node_id);
1432 let features = self.init_features(&their_node_id);
1433 let networks = self.message_handler.chan_handler.get_chain_hashes();
1434 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1435 self.enqueue_message(peer, &resp);
1436 peer.awaiting_pong_timer_tick_intervals = 0;
1438 NextNoiseStep::NoiseComplete => {
1439 if peer.pending_read_is_header {
1440 let msg_len = try_potential_handleerror!(peer,
1441 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1442 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1443 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1444 if msg_len < 2 { // Need at least the message type tag
1445 return Err(PeerHandleError { });
1447 peer.pending_read_is_header = false;
1449 debug_assert!(peer.pending_read_buffer.len() >= 2 + 16);
1450 try_potential_handleerror!(peer,
1451 peer.channel_encryptor.decrypt_message(&mut peer.pending_read_buffer[..]));
1453 let mut reader = io::Cursor::new(&peer.pending_read_buffer[..peer.pending_read_buffer.len() - 16]);
1454 let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1456 // Reset read buffer
1457 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1458 peer.pending_read_buffer.resize(18, 0);
1459 peer.pending_read_is_header = true;
1461 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1462 let message = match message_result {
1466 // Note that to avoid re-entrancy we never call
1467 // `do_attempt_write_data` from here, causing
1468 // the messages enqueued here to not actually
1469 // be sent before the peer is disconnected.
1470 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1471 log_gossip!(logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1474 (msgs::DecodeError::UnsupportedCompression, _) => {
1475 log_gossip!(logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1476 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: ChannelId::new_zero(), data: "Unsupported message compression: zlib".to_owned() });
1479 (_, Some(ty)) if is_gossip_msg(ty) => {
1480 log_gossip!(logger, "Got an invalid value while deserializing a gossip message");
1481 self.enqueue_message(peer, &msgs::WarningMessage {
1482 channel_id: ChannelId::new_zero(),
1483 data: format!("Unreadable/bogus gossip message of type {}", ty),
1487 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1488 log_debug!(logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1489 return Err(PeerHandleError { });
1491 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1492 (msgs::DecodeError::InvalidValue, _) => {
1493 log_debug!(logger, "Got an invalid value while deserializing message");
1494 return Err(PeerHandleError { });
1496 (msgs::DecodeError::ShortRead, _) => {
1497 log_debug!(logger, "Deserialization failed due to shortness of message");
1498 return Err(PeerHandleError { });
1500 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1501 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1506 msg_to_handle = Some(message);
1511 pause_read = !self.peer_should_read(peer);
1513 if let Some(message) = msg_to_handle {
1514 match self.handle_message(&peer_mutex, peer_lock, message) {
1515 Err(handling_error) => match handling_error {
1516 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1517 MessageHandlingError::LightningError(e) => {
1518 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1522 msgs_to_forward.push(msg);
1531 for msg in msgs_to_forward.drain(..) {
1532 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1538 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1539 /// Returns the message back if it needs to be broadcasted to all other peers.
1542 peer_mutex: &Mutex<Peer>,
1543 mut peer_lock: MutexGuard<Peer>,
1544 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1545 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1546 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;
1547 let logger = WithContext::from(&self.logger, Some(their_node_id), None);
1548 peer_lock.received_message_since_timer_tick = true;
1550 // Need an Init as first message
1551 if let wire::Message::Init(msg) = message {
1552 // Check if we have any compatible chains if the `networks` field is specified.
1553 if let Some(networks) = &msg.networks {
1554 if let Some(our_chains) = self.message_handler.chan_handler.get_chain_hashes() {
1555 let mut have_compatible_chains = false;
1556 'our_chains: for our_chain in our_chains.iter() {
1557 for their_chain in networks {
1558 if our_chain == their_chain {
1559 have_compatible_chains = true;
1564 if !have_compatible_chains {
1565 log_debug!(logger, "Peer does not support any of our supported chains");
1566 return Err(PeerHandleError { }.into());
1571 let our_features = self.init_features(&their_node_id);
1572 if msg.features.requires_unknown_bits_from(&our_features) {
1573 log_debug!(logger, "Peer requires features unknown to us");
1574 return Err(PeerHandleError { }.into());
1577 if our_features.requires_unknown_bits_from(&msg.features) {
1578 log_debug!(logger, "We require features unknown to our peer");
1579 return Err(PeerHandleError { }.into());
1582 if peer_lock.their_features.is_some() {
1583 return Err(PeerHandleError { }.into());
1586 log_info!(logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1588 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1589 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1590 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1593 if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1594 log_debug!(logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1595 return Err(PeerHandleError { }.into());
1597 if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1598 log_debug!(logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1599 return Err(PeerHandleError { }.into());
1601 if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1602 log_debug!(logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1603 return Err(PeerHandleError { }.into());
1606 peer_lock.their_features = Some(msg.features);
1608 } else if peer_lock.their_features.is_none() {
1609 log_debug!(logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1610 return Err(PeerHandleError { }.into());
1613 if let wire::Message::GossipTimestampFilter(_msg) = message {
1614 // When supporting gossip messages, start initial gossip sync only after we receive
1615 // a GossipTimestampFilter
1616 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1617 !peer_lock.sent_gossip_timestamp_filter {
1618 peer_lock.sent_gossip_timestamp_filter = true;
1619 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1624 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1625 peer_lock.received_channel_announce_since_backlogged = true;
1628 mem::drop(peer_lock);
1630 if is_gossip_msg(message.type_id()) {
1631 log_gossip!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1633 log_trace!(logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1636 let mut should_forward = None;
1639 // Setup and Control messages:
1640 wire::Message::Init(_) => {
1643 wire::Message::GossipTimestampFilter(_) => {
1646 wire::Message::Error(msg) => {
1647 log_debug!(logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1648 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1649 if msg.channel_id.is_zero() {
1650 return Err(PeerHandleError { }.into());
1653 wire::Message::Warning(msg) => {
1654 log_debug!(logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1657 wire::Message::Ping(msg) => {
1658 if msg.ponglen < 65532 {
1659 let resp = msgs::Pong { byteslen: msg.ponglen };
1660 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1663 wire::Message::Pong(_msg) => {
1664 let mut peer_lock = peer_mutex.lock().unwrap();
1665 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1666 peer_lock.msgs_sent_since_pong = 0;
1669 // Channel messages:
1670 wire::Message::OpenChannel(msg) => {
1671 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1673 wire::Message::OpenChannelV2(msg) => {
1674 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1676 wire::Message::AcceptChannel(msg) => {
1677 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1679 wire::Message::AcceptChannelV2(msg) => {
1680 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1683 wire::Message::FundingCreated(msg) => {
1684 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1686 wire::Message::FundingSigned(msg) => {
1687 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1689 wire::Message::ChannelReady(msg) => {
1690 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1693 // Quiescence messages:
1694 wire::Message::Stfu(msg) => {
1695 self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
1698 // Splicing messages:
1699 wire::Message::Splice(msg) => {
1700 self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
1702 wire::Message::SpliceAck(msg) => {
1703 self.message_handler.chan_handler.handle_splice_ack(&their_node_id, &msg);
1705 wire::Message::SpliceLocked(msg) => {
1706 self.message_handler.chan_handler.handle_splice_locked(&their_node_id, &msg);
1709 // Interactive transaction construction messages:
1710 wire::Message::TxAddInput(msg) => {
1711 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1713 wire::Message::TxAddOutput(msg) => {
1714 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1716 wire::Message::TxRemoveInput(msg) => {
1717 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1719 wire::Message::TxRemoveOutput(msg) => {
1720 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1722 wire::Message::TxComplete(msg) => {
1723 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1725 wire::Message::TxSignatures(msg) => {
1726 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1728 wire::Message::TxInitRbf(msg) => {
1729 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1731 wire::Message::TxAckRbf(msg) => {
1732 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1734 wire::Message::TxAbort(msg) => {
1735 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1738 wire::Message::Shutdown(msg) => {
1739 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1741 wire::Message::ClosingSigned(msg) => {
1742 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1745 // Commitment messages:
1746 wire::Message::UpdateAddHTLC(msg) => {
1747 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1749 wire::Message::UpdateFulfillHTLC(msg) => {
1750 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1752 wire::Message::UpdateFailHTLC(msg) => {
1753 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1755 wire::Message::UpdateFailMalformedHTLC(msg) => {
1756 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1759 wire::Message::CommitmentSigned(msg) => {
1760 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1762 wire::Message::RevokeAndACK(msg) => {
1763 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1765 wire::Message::UpdateFee(msg) => {
1766 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1768 wire::Message::ChannelReestablish(msg) => {
1769 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1772 // Routing messages:
1773 wire::Message::AnnouncementSignatures(msg) => {
1774 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1776 wire::Message::ChannelAnnouncement(msg) => {
1777 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1778 .map_err(|e| -> MessageHandlingError { e.into() })? {
1779 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1781 self.update_gossip_backlogged();
1783 wire::Message::NodeAnnouncement(msg) => {
1784 if self.message_handler.route_handler.handle_node_announcement(&msg)
1785 .map_err(|e| -> MessageHandlingError { e.into() })? {
1786 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1788 self.update_gossip_backlogged();
1790 wire::Message::ChannelUpdate(msg) => {
1791 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1792 if self.message_handler.route_handler.handle_channel_update(&msg)
1793 .map_err(|e| -> MessageHandlingError { e.into() })? {
1794 should_forward = Some(wire::Message::ChannelUpdate(msg));
1796 self.update_gossip_backlogged();
1798 wire::Message::QueryShortChannelIds(msg) => {
1799 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1801 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1802 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1804 wire::Message::QueryChannelRange(msg) => {
1805 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1807 wire::Message::ReplyChannelRange(msg) => {
1808 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1812 wire::Message::OnionMessage(msg) => {
1813 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1816 // Unknown messages:
1817 wire::Message::Unknown(type_id) if message.is_even() => {
1818 log_debug!(logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1819 return Err(PeerHandleError { }.into());
1821 wire::Message::Unknown(type_id) => {
1822 log_trace!(logger, "Received unknown odd message of type {}, ignoring", type_id);
1824 wire::Message::Custom(custom) => {
1825 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1831 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>) {
1833 wire::Message::ChannelAnnouncement(ref msg) => {
1834 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1835 let encoded_msg = encode_msg!(msg);
1837 for (_, peer_mutex) in peers.iter() {
1838 let mut peer = peer_mutex.lock().unwrap();
1839 if !peer.handshake_complete() ||
1840 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1843 debug_assert!(peer.their_node_id.is_some());
1844 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1845 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1846 if peer.buffer_full_drop_gossip_broadcast() {
1847 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1850 if let Some((_, their_node_id)) = peer.their_node_id {
1851 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1855 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1858 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1861 wire::Message::NodeAnnouncement(ref msg) => {
1862 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1863 let encoded_msg = encode_msg!(msg);
1865 for (_, peer_mutex) in peers.iter() {
1866 let mut peer = peer_mutex.lock().unwrap();
1867 if !peer.handshake_complete() ||
1868 !peer.should_forward_node_announcement(msg.contents.node_id) {
1871 debug_assert!(peer.their_node_id.is_some());
1872 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1873 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1874 if peer.buffer_full_drop_gossip_broadcast() {
1875 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1878 if let Some((_, their_node_id)) = peer.their_node_id {
1879 if their_node_id == msg.contents.node_id {
1883 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1886 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1889 wire::Message::ChannelUpdate(ref msg) => {
1890 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1891 let encoded_msg = encode_msg!(msg);
1893 for (_, peer_mutex) in peers.iter() {
1894 let mut peer = peer_mutex.lock().unwrap();
1895 if !peer.handshake_complete() ||
1896 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1899 debug_assert!(peer.their_node_id.is_some());
1900 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1901 let logger = WithContext::from(&self.logger, peer.their_node_id.map(|p| p.0), None);
1902 if peer.buffer_full_drop_gossip_broadcast() {
1903 log_gossip!(logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1906 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1909 self.enqueue_encoded_gossip_broadcast(&mut *peer, MessageBuf::from_encoded(&encoded_msg));
1912 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1916 /// Checks for any events generated by our handlers and processes them. Includes sending most
1917 /// response messages as well as messages generated by calls to handler functions directly (eg
1918 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1920 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1923 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1924 /// or one of the other clients provided in our language bindings.
1926 /// Note that if there are any other calls to this function waiting on lock(s) this may return
1927 /// without doing any work. All available events that need handling will be handled before the
1928 /// other calls return.
1930 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1931 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1932 /// [`send_data`]: SocketDescriptor::send_data
1933 pub fn process_events(&self) {
1934 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
1935 // If we're not the first event processor to get here, just return early, the increment
1936 // we just did will be treated as "go around again" at the end.
1941 self.update_gossip_backlogged();
1942 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
1944 let mut peers_to_disconnect = HashMap::new();
1947 let peers_lock = self.peers.read().unwrap();
1949 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1950 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1952 let peers = &*peers_lock;
1953 macro_rules! get_peer_for_forwarding {
1954 ($node_id: expr) => {
1956 if peers_to_disconnect.get($node_id).is_some() {
1957 // If we've "disconnected" this peer, do not send to it.
1960 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1961 match descriptor_opt {
1962 Some(descriptor) => match peers.get(&descriptor) {
1963 Some(peer_mutex) => {
1964 let peer_lock = peer_mutex.lock().unwrap();
1965 if !peer_lock.handshake_complete() {
1971 debug_assert!(false, "Inconsistent peers set state!");
1982 for event in events_generated.drain(..) {
1984 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1985 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1986 log_pubkey!(node_id),
1987 &msg.temporary_channel_id);
1988 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1990 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
1991 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
1992 log_pubkey!(node_id),
1993 &msg.temporary_channel_id);
1994 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1996 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1997 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1998 log_pubkey!(node_id),
1999 &msg.temporary_channel_id);
2000 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2002 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
2003 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.temporary_channel_id)), "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}",
2004 log_pubkey!(node_id),
2005 &msg.temporary_channel_id);
2006 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2008 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
2009 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 {})",
2010 log_pubkey!(node_id),
2011 &msg.temporary_channel_id,
2012 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
2013 // TODO: If the peer is gone we should generate a DiscardFunding event
2014 // indicating to the wallet that they should just throw away this funding transaction
2015 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2017 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
2018 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
2019 log_pubkey!(node_id),
2021 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2023 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
2024 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReady event in peer_handler for node {} for channel {}",
2025 log_pubkey!(node_id),
2027 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2029 MessageSendEvent::SendStfu { ref node_id, ref msg} => {
2030 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2031 log_debug!(logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
2032 log_pubkey!(node_id),
2034 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2036 MessageSendEvent::SendSplice { ref node_id, ref msg} => {
2037 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2038 log_debug!(logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
2039 log_pubkey!(node_id),
2041 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2043 MessageSendEvent::SendSpliceAck { ref node_id, ref msg} => {
2044 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2045 log_debug!(logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}",
2046 log_pubkey!(node_id),
2048 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2050 MessageSendEvent::SendSpliceLocked { ref node_id, ref msg} => {
2051 let logger = WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id));
2052 log_debug!(logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}",
2053 log_pubkey!(node_id),
2055 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2057 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
2058 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
2059 log_pubkey!(node_id),
2061 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2063 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
2064 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAddOutput event in peer_handler for node {} for channel {}",
2065 log_pubkey!(node_id),
2067 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2069 MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => {
2070 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
2071 log_pubkey!(node_id),
2073 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2075 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
2076 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
2077 log_pubkey!(node_id),
2079 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2081 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
2082 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxComplete event in peer_handler for node {} for channel {}",
2083 log_pubkey!(node_id),
2085 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2087 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
2088 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
2089 log_pubkey!(node_id),
2091 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2093 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
2094 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
2095 log_pubkey!(node_id),
2097 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2099 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2100 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2101 log_pubkey!(node_id),
2103 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2105 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2106 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendTxAbort 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::SendAnnouncementSignatures { ref node_id, ref msg } => {
2112 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendAnnouncementSignatures 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::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 } } => {
2118 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 {}",
2119 log_pubkey!(node_id),
2120 update_add_htlcs.len(),
2121 update_fulfill_htlcs.len(),
2122 update_fail_htlcs.len(),
2123 &commitment_signed.channel_id);
2124 let mut peer = get_peer_for_forwarding!(node_id);
2125 for msg in update_add_htlcs {
2126 self.enqueue_message(&mut *peer, msg);
2128 for msg in update_fulfill_htlcs {
2129 self.enqueue_message(&mut *peer, msg);
2131 for msg in update_fail_htlcs {
2132 self.enqueue_message(&mut *peer, msg);
2134 for msg in update_fail_malformed_htlcs {
2135 self.enqueue_message(&mut *peer, msg);
2137 if let &Some(ref msg) = update_fee {
2138 self.enqueue_message(&mut *peer, msg);
2140 self.enqueue_message(&mut *peer, commitment_signed);
2142 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2143 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2144 log_pubkey!(node_id),
2146 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2148 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2149 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2150 log_pubkey!(node_id),
2152 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2154 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2155 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling Shutdown event in peer_handler for node {} for channel {}",
2156 log_pubkey!(node_id),
2158 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2160 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2161 log_debug!(WithContext::from(&self.logger, Some(*node_id), Some(msg.channel_id)), "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2162 log_pubkey!(node_id),
2164 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2166 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2167 log_debug!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2168 log_pubkey!(node_id),
2169 msg.contents.short_channel_id);
2170 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2171 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2173 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2174 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2175 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2176 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2177 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2180 if let Some(msg) = update_msg {
2181 match self.message_handler.route_handler.handle_channel_update(&msg) {
2182 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2183 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2188 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2189 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents);
2190 match self.message_handler.route_handler.handle_channel_update(&msg) {
2191 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2192 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2196 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2197 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2198 match self.message_handler.route_handler.handle_node_announcement(&msg) {
2199 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2200 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2204 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2205 log_trace!(WithContext::from(&self.logger, Some(*node_id), None), "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2206 log_pubkey!(node_id), msg.contents.short_channel_id);
2207 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2209 MessageSendEvent::HandleError { node_id, action } => {
2210 let logger = WithContext::from(&self.logger, Some(node_id), None);
2212 msgs::ErrorAction::DisconnectPeer { msg } => {
2213 if let Some(msg) = msg.as_ref() {
2214 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2215 log_pubkey!(node_id), msg.data);
2217 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2218 log_pubkey!(node_id));
2220 // We do not have the peers write lock, so we just store that we're
2221 // about to disconnect the peer and do it after we finish
2222 // processing most messages.
2223 let msg = msg.map(|msg| wire::Message::<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2224 peers_to_disconnect.insert(node_id, msg);
2226 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2227 log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2228 log_pubkey!(node_id), msg.data);
2229 // We do not have the peers write lock, so we just store that we're
2230 // about to disconnect the peer and do it after we finish
2231 // processing most messages.
2232 peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2234 msgs::ErrorAction::IgnoreAndLog(level) => {
2235 log_given_level!(logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2237 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2238 msgs::ErrorAction::IgnoreError => {
2239 log_debug!(logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2241 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2242 log_trace!(logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2243 log_pubkey!(node_id),
2245 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2247 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2248 log_given_level!(logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2249 log_pubkey!(node_id),
2251 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2255 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2256 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2258 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2259 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2261 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2262 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={}",
2263 log_pubkey!(node_id),
2264 msg.short_channel_ids.len(),
2266 msg.number_of_blocks,
2268 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2270 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2271 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2276 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2277 if peers_to_disconnect.get(&node_id).is_some() { continue; }
2278 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2281 for (descriptor, peer_mutex) in peers.iter() {
2282 let mut peer = peer_mutex.lock().unwrap();
2283 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2284 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2287 if !peers_to_disconnect.is_empty() {
2288 let mut peers_lock = self.peers.write().unwrap();
2289 let peers = &mut *peers_lock;
2290 for (node_id, msg) in peers_to_disconnect.drain() {
2291 // Note that since we are holding the peers *write* lock we can
2292 // remove from node_id_to_descriptor immediately (as no other
2293 // thread can be holding the peer lock if we have the global write
2296 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2297 if let Some(mut descriptor) = descriptor_opt {
2298 if let Some(peer_mutex) = peers.remove(&descriptor) {
2299 let mut peer = peer_mutex.lock().unwrap();
2300 if let Some(msg) = msg {
2301 self.enqueue_message(&mut *peer, &msg);
2302 // This isn't guaranteed to work, but if there is enough free
2303 // room in the send buffer, put the error message there...
2304 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2306 self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2307 } else { debug_assert!(false, "Missing connection for peer"); }
2312 if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2313 // If another thread incremented the state while we were running we should go
2314 // around again, but only once.
2315 self.event_processing_state.store(1, Ordering::Release);
2322 /// Indicates that the given socket descriptor's connection is now closed.
2323 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2324 self.disconnect_event_internal(descriptor);
2327 fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2328 if !peer.handshake_complete() {
2329 log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2330 descriptor.disconnect_socket();
2334 debug_assert!(peer.their_node_id.is_some());
2335 if let Some((node_id, _)) = peer.their_node_id {
2336 log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Disconnecting peer with id {} due to {}", node_id, reason);
2337 self.message_handler.chan_handler.peer_disconnected(&node_id);
2338 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2340 descriptor.disconnect_socket();
2343 fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2344 let mut peers = self.peers.write().unwrap();
2345 let peer_option = peers.remove(descriptor);
2348 // This is most likely a simple race condition where the user found that the socket
2349 // was disconnected, then we told the user to `disconnect_socket()`, then they
2350 // called this method. Either way we're disconnected, return.
2352 Some(peer_lock) => {
2353 let peer = peer_lock.lock().unwrap();
2354 if let Some((node_id, _)) = peer.their_node_id {
2355 log_trace!(WithContext::from(&self.logger, Some(node_id), None), "Handling disconnection of peer {}", log_pubkey!(node_id));
2356 let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2357 debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2358 if !peer.handshake_complete() { return; }
2359 self.message_handler.chan_handler.peer_disconnected(&node_id);
2360 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2366 /// Disconnect a peer given its node id.
2368 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2369 /// peer. Thus, be very careful about reentrancy issues.
2371 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2372 pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2373 let mut peers_lock = self.peers.write().unwrap();
2374 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2375 let peer_opt = peers_lock.remove(&descriptor);
2376 if let Some(peer_mutex) = peer_opt {
2377 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2378 } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2382 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2383 /// an indication that TCP sockets have stalled even if we weren't around to time them out
2384 /// using regular ping/pongs.
2385 pub fn disconnect_all_peers(&self) {
2386 let mut peers_lock = self.peers.write().unwrap();
2387 self.node_id_to_descriptor.lock().unwrap().clear();
2388 let peers = &mut *peers_lock;
2389 for (descriptor, peer_mutex) in peers.drain() {
2390 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2394 /// This is called when we're blocked on sending additional gossip messages until we receive a
2395 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2396 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2397 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2398 if peer.awaiting_pong_timer_tick_intervals == 0 {
2399 peer.awaiting_pong_timer_tick_intervals = -1;
2400 let ping = msgs::Ping {
2404 self.enqueue_message(peer, &ping);
2408 /// Send pings to each peer and disconnect those which did not respond to the last round of
2411 /// This may be called on any timescale you want, however, roughly once every ten seconds is
2412 /// preferred. The call rate determines both how often we send a ping to our peers and how much
2413 /// time they have to respond before we disconnect them.
2415 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2418 /// [`send_data`]: SocketDescriptor::send_data
2419 pub fn timer_tick_occurred(&self) {
2420 let mut descriptors_needing_disconnect = Vec::new();
2422 let peers_lock = self.peers.read().unwrap();
2424 self.update_gossip_backlogged();
2425 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2427 for (descriptor, peer_mutex) in peers_lock.iter() {
2428 let mut peer = peer_mutex.lock().unwrap();
2429 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2431 if !peer.handshake_complete() {
2432 // The peer needs to complete its handshake before we can exchange messages. We
2433 // give peers one timer tick to complete handshake, reusing
2434 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2435 // for handshake completion.
2436 if peer.awaiting_pong_timer_tick_intervals != 0 {
2437 descriptors_needing_disconnect.push(descriptor.clone());
2439 peer.awaiting_pong_timer_tick_intervals = 1;
2443 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2444 debug_assert!(peer.their_node_id.is_some());
2446 loop { // Used as a `goto` to skip writing a Ping message.
2447 if peer.awaiting_pong_timer_tick_intervals == -1 {
2448 // Magic value set in `maybe_send_extra_ping`.
2449 peer.awaiting_pong_timer_tick_intervals = 1;
2450 peer.received_message_since_timer_tick = false;
2454 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2455 || peer.awaiting_pong_timer_tick_intervals as u64 >
2456 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2458 descriptors_needing_disconnect.push(descriptor.clone());
2461 peer.received_message_since_timer_tick = false;
2463 if peer.awaiting_pong_timer_tick_intervals > 0 {
2464 peer.awaiting_pong_timer_tick_intervals += 1;
2468 peer.awaiting_pong_timer_tick_intervals = 1;
2469 let ping = msgs::Ping {
2473 self.enqueue_message(&mut *peer, &ping);
2476 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2480 if !descriptors_needing_disconnect.is_empty() {
2482 let mut peers_lock = self.peers.write().unwrap();
2483 for descriptor in descriptors_needing_disconnect {
2484 if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2485 let peer = peer_mutex.lock().unwrap();
2486 if let Some((node_id, _)) = peer.their_node_id {
2487 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2489 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2497 // Messages of up to 64KB should never end up more than half full with addresses, as that would
2498 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2499 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2501 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (SocketAddress::MAX_LEN as u32 + 1) / 2;
2503 // ...by failing to compile if the number of addresses that would be half of a message is
2504 // smaller than 100:
2505 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2507 /// Generates a signed node_announcement from the given arguments, sending it to all connected
2508 /// peers. Note that peers will likely ignore this message unless we have at least one public
2509 /// channel which has at least six confirmations on-chain.
2511 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2512 /// node to humans. They carry no in-protocol meaning.
2514 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2515 /// accepts incoming connections. These will be included in the node_announcement, publicly
2516 /// tying these addresses together and to this node. If you wish to preserve user privacy,
2517 /// addresses should likely contain only Tor Onion addresses.
2519 /// Panics if `addresses` is absurdly large (more than 100).
2521 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2522 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<SocketAddress>) {
2523 if addresses.len() > 100 {
2524 panic!("More than half the message size was taken up by public addresses!");
2527 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2528 // addresses be sorted for future compatibility.
2529 addresses.sort_by_key(|addr| addr.get_id());
2531 let features = self.message_handler.chan_handler.provided_node_features()
2532 | self.message_handler.route_handler.provided_node_features()
2533 | self.message_handler.onion_message_handler.provided_node_features()
2534 | self.message_handler.custom_message_handler.provided_node_features();
2535 let announcement = msgs::UnsignedNodeAnnouncement {
2537 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2538 node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2540 alias: NodeAlias(alias),
2542 excess_address_data: Vec::new(),
2543 excess_data: Vec::new(),
2545 let node_announce_sig = match self.node_signer.sign_gossip_message(
2546 msgs::UnsignedGossipMessage::NodeAnnouncement(announcement.clone())
2550 log_error!(self.logger, "Failed to generate signature for node_announcement");
2555 let msg = msgs::NodeAnnouncement {
2556 signature: node_announce_sig,
2557 contents: announcement
2560 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2561 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2562 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2566 fn is_gossip_msg(type_id: u16) -> bool {
2568 msgs::ChannelAnnouncement::TYPE |
2569 msgs::ChannelUpdate::TYPE |
2570 msgs::NodeAnnouncement::TYPE |
2571 msgs::QueryChannelRange::TYPE |
2572 msgs::ReplyChannelRange::TYPE |
2573 msgs::QueryShortChannelIds::TYPE |
2574 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2581 use crate::sign::{NodeSigner, Recipient};
2584 use crate::ln::ChannelId;
2585 use crate::ln::features::{InitFeatures, NodeFeatures};
2586 use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2587 use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2588 use crate::ln::{msgs, wire};
2589 use crate::ln::msgs::{LightningError, SocketAddress};
2590 use crate::util::test_utils;
2592 use bitcoin::Network;
2593 use bitcoin::blockdata::constants::ChainHash;
2594 use bitcoin::secp256k1::{PublicKey, SecretKey};
2596 use crate::prelude::*;
2597 use crate::sync::{Arc, Mutex};
2598 use core::convert::Infallible;
2599 use core::sync::atomic::{AtomicBool, Ordering};
2602 struct FileDescriptor {
2604 outbound_data: Arc<Mutex<Vec<u8>>>,
2605 disconnect: Arc<AtomicBool>,
2607 impl PartialEq for FileDescriptor {
2608 fn eq(&self, other: &Self) -> bool {
2612 impl Eq for FileDescriptor { }
2613 impl core::hash::Hash for FileDescriptor {
2614 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2615 self.fd.hash(hasher)
2619 impl SocketDescriptor for FileDescriptor {
2620 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2621 self.outbound_data.lock().unwrap().extend_from_slice(data);
2625 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2628 struct PeerManagerCfg {
2629 chan_handler: test_utils::TestChannelMessageHandler,
2630 routing_handler: test_utils::TestRoutingMessageHandler,
2631 custom_handler: TestCustomMessageHandler,
2632 logger: test_utils::TestLogger,
2633 node_signer: test_utils::TestNodeSigner,
2636 struct TestCustomMessageHandler {
2637 features: InitFeatures,
2640 impl wire::CustomMessageReader for TestCustomMessageHandler {
2641 type CustomMessage = Infallible;
2642 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2647 impl CustomMessageHandler for TestCustomMessageHandler {
2648 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2652 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2654 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2656 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2657 self.features.clone()
2661 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2662 let mut cfgs = Vec::new();
2663 for i in 0..peer_count {
2664 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2666 let mut feature_bits = vec![0u8; 33];
2667 feature_bits[32] = 0b00000001;
2668 InitFeatures::from_le_bytes(feature_bits)
2672 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2673 logger: test_utils::TestLogger::new(),
2674 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2675 custom_handler: TestCustomMessageHandler { features },
2676 node_signer: test_utils::TestNodeSigner::new(node_secret),
2684 fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2685 let mut cfgs = Vec::new();
2686 for i in 0..peer_count {
2687 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2689 let mut feature_bits = vec![0u8; 33 + i + 1];
2690 feature_bits[33 + i] = 0b00000001;
2691 InitFeatures::from_le_bytes(feature_bits)
2695 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2696 logger: test_utils::TestLogger::new(),
2697 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2698 custom_handler: TestCustomMessageHandler { features },
2699 node_signer: test_utils::TestNodeSigner::new(node_secret),
2707 fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2708 let mut cfgs = Vec::new();
2709 for i in 0..peer_count {
2710 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2711 let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2712 let network = ChainHash::from(&[i as u8; 32]);
2715 chan_handler: test_utils::TestChannelMessageHandler::new(network),
2716 logger: test_utils::TestLogger::new(),
2717 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2718 custom_handler: TestCustomMessageHandler { features },
2719 node_signer: test_utils::TestNodeSigner::new(node_secret),
2727 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>> {
2728 let mut peers = Vec::new();
2729 for i in 0..peer_count {
2730 let ephemeral_bytes = [i as u8; 32];
2731 let msg_handler = MessageHandler {
2732 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2733 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2735 let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2742 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) {
2743 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2744 let mut fd_a = FileDescriptor {
2745 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2746 disconnect: Arc::new(AtomicBool::new(false)),
2748 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2749 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2750 let mut fd_b = FileDescriptor {
2751 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2752 disconnect: Arc::new(AtomicBool::new(false)),
2754 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2755 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2756 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2757 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2758 peer_a.process_events();
2760 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2761 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2763 peer_b.process_events();
2764 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2765 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2767 peer_a.process_events();
2768 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2769 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2771 assert!(peer_a.get_peer_node_ids().contains(&(id_b, Some(addr_b))));
2772 assert!(peer_b.get_peer_node_ids().contains(&(id_a, Some(addr_a))));
2774 (fd_a.clone(), fd_b.clone())
2778 #[cfg(feature = "std")]
2779 fn fuzz_threaded_connections() {
2780 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2781 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2782 // with our internal map consistency, and is a generally good smoke test of disconnection.
2783 let cfgs = Arc::new(create_peermgr_cfgs(2));
2784 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2785 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2787 let start_time = std::time::Instant::now();
2788 macro_rules! spawn_thread { ($id: expr) => { {
2789 let peers = Arc::clone(&peers);
2790 let cfgs = Arc::clone(&cfgs);
2791 std::thread::spawn(move || {
2793 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2794 let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2795 let mut fd_a = FileDescriptor {
2796 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2797 disconnect: Arc::new(AtomicBool::new(false)),
2799 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2800 let mut fd_b = FileDescriptor {
2801 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2802 disconnect: Arc::new(AtomicBool::new(false)),
2804 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2805 let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2806 peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2807 if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2809 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2810 peers[0].process_events();
2811 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2812 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2813 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2815 peers[1].process_events();
2816 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2817 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2818 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2820 cfgs[0].chan_handler.pending_events.lock().unwrap()
2821 .push(crate::events::MessageSendEvent::SendShutdown {
2822 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2823 msg: msgs::Shutdown {
2824 channel_id: ChannelId::new_zero(),
2825 scriptpubkey: bitcoin::ScriptBuf::new(),
2828 cfgs[1].chan_handler.pending_events.lock().unwrap()
2829 .push(crate::events::MessageSendEvent::SendShutdown {
2830 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2831 msg: msgs::Shutdown {
2832 channel_id: ChannelId::new_zero(),
2833 scriptpubkey: bitcoin::ScriptBuf::new(),
2838 peers[0].timer_tick_occurred();
2839 peers[1].timer_tick_occurred();
2843 peers[0].socket_disconnected(&fd_a);
2844 peers[1].socket_disconnected(&fd_b);
2846 std::thread::sleep(std::time::Duration::from_micros(1));
2850 let thrd_a = spawn_thread!(1);
2851 let thrd_b = spawn_thread!(2);
2853 thrd_a.join().unwrap();
2854 thrd_b.join().unwrap();
2858 fn test_feature_incompatible_peers() {
2859 let cfgs = create_peermgr_cfgs(2);
2860 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2862 let peers = create_network(2, &cfgs);
2863 let incompatible_peers = create_network(2, &incompatible_cfgs);
2864 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2865 for (peer_a, peer_b) in peer_pairs.iter() {
2866 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2867 let mut fd_a = FileDescriptor {
2868 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2869 disconnect: Arc::new(AtomicBool::new(false)),
2871 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2872 let mut fd_b = FileDescriptor {
2873 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2874 disconnect: Arc::new(AtomicBool::new(false)),
2876 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2877 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2878 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2879 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2880 peer_a.process_events();
2882 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2883 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2885 peer_b.process_events();
2886 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2888 // Should fail because of unknown required features
2889 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2894 fn test_chain_incompatible_peers() {
2895 let cfgs = create_peermgr_cfgs(2);
2896 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
2898 let peers = create_network(2, &cfgs);
2899 let incompatible_peers = create_network(2, &incompatible_cfgs);
2900 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2901 for (peer_a, peer_b) in peer_pairs.iter() {
2902 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2903 let mut fd_a = FileDescriptor {
2904 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2905 disconnect: Arc::new(AtomicBool::new(false)),
2907 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2908 let mut fd_b = FileDescriptor {
2909 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2910 disconnect: Arc::new(AtomicBool::new(false)),
2912 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2913 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2914 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2915 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2916 peer_a.process_events();
2918 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2919 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2921 peer_b.process_events();
2922 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2924 // Should fail because of incompatible chains
2925 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2930 fn test_disconnect_peer() {
2931 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2932 // push a DisconnectPeer event to remove the node flagged by id
2933 let cfgs = create_peermgr_cfgs(2);
2934 let peers = create_network(2, &cfgs);
2935 establish_connection(&peers[0], &peers[1]);
2936 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2938 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2939 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2941 action: msgs::ErrorAction::DisconnectPeer { msg: None },
2944 peers[0].process_events();
2945 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2949 fn test_send_simple_msg() {
2950 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2951 // push a message from one peer to another.
2952 let cfgs = create_peermgr_cfgs(2);
2953 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2954 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2955 let mut peers = create_network(2, &cfgs);
2956 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2957 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2959 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2961 let msg = msgs::Shutdown { channel_id: ChannelId::from_bytes([42; 32]), scriptpubkey: bitcoin::ScriptBuf::new() };
2962 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2963 node_id: their_id, msg: msg.clone()
2965 peers[0].message_handler.chan_handler = &a_chan_handler;
2967 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2968 peers[1].message_handler.chan_handler = &b_chan_handler;
2970 peers[0].process_events();
2972 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2973 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2977 fn test_non_init_first_msg() {
2978 // Simple test of the first message received over a connection being something other than
2979 // Init. This results in an immediate disconnection, which previously included a spurious
2980 // peer_disconnected event handed to event handlers (which would panic in
2981 // `TestChannelMessageHandler` here).
2982 let cfgs = create_peermgr_cfgs(2);
2983 let peers = create_network(2, &cfgs);
2985 let mut fd_dup = FileDescriptor {
2986 fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2987 disconnect: Arc::new(AtomicBool::new(false)),
2989 let addr_dup = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1003};
2990 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
2991 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
2993 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
2994 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
2995 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
2996 peers[0].process_events();
2998 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
2999 let (act_three, _) =
3000 dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
3001 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
3003 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
3004 let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg);
3005 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
3009 fn test_disconnect_all_peer() {
3010 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
3011 // then calls disconnect_all_peers
3012 let cfgs = create_peermgr_cfgs(2);
3013 let peers = create_network(2, &cfgs);
3014 establish_connection(&peers[0], &peers[1]);
3015 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3017 peers[0].disconnect_all_peers();
3018 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3022 fn test_timer_tick_occurred() {
3023 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
3024 let cfgs = create_peermgr_cfgs(2);
3025 let peers = create_network(2, &cfgs);
3026 establish_connection(&peers[0], &peers[1]);
3027 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3029 // peers[0] awaiting_pong is set to true, but the Peer is still connected
3030 peers[0].timer_tick_occurred();
3031 peers[0].process_events();
3032 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3034 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
3035 peers[0].timer_tick_occurred();
3036 peers[0].process_events();
3037 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3041 fn test_do_attempt_write_data() {
3042 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
3043 let cfgs = create_peermgr_cfgs(2);
3044 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3045 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3046 let peers = create_network(2, &cfgs);
3048 // By calling establish_connect, we trigger do_attempt_write_data between
3049 // the peers. Previously this function would mistakenly enter an infinite loop
3050 // when there were more channel messages available than could fit into a peer's
3051 // buffer. This issue would now be detected by this test (because we use custom
3052 // RoutingMessageHandlers that intentionally return more channel messages
3053 // than can fit into a peer's buffer).
3054 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3056 // Make each peer to read the messages that the other peer just wrote to them. Note that
3057 // due to the max-message-before-ping limits this may take a few iterations to complete.
3058 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
3059 peers[1].process_events();
3060 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3061 assert!(!a_read_data.is_empty());
3063 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
3064 peers[0].process_events();
3066 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3067 assert!(!b_read_data.is_empty());
3068 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
3070 peers[0].process_events();
3071 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
3074 // Check that each peer has received the expected number of channel updates and channel
3076 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3077 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3078 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3079 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3083 fn test_handshake_timeout() {
3084 // Tests that we time out a peer still waiting on handshake completion after a full timer
3086 let cfgs = create_peermgr_cfgs(2);
3087 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3088 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3089 let peers = create_network(2, &cfgs);
3091 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
3092 let mut fd_a = FileDescriptor {
3093 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3094 disconnect: Arc::new(AtomicBool::new(false)),
3096 let mut fd_b = FileDescriptor {
3097 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3098 disconnect: Arc::new(AtomicBool::new(false)),
3100 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3101 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3103 // If we get a single timer tick before completion, that's fine
3104 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3105 peers[0].timer_tick_occurred();
3106 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3108 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3109 peers[0].process_events();
3110 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3111 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3112 peers[1].process_events();
3114 // ...but if we get a second timer tick, we should disconnect the peer
3115 peers[0].timer_tick_occurred();
3116 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3118 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3119 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3123 fn test_filter_addresses(){
3124 // Tests the filter_addresses function.
3127 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 0, 0], port: 1000};
3128 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3129 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 255, 201], port: 1000};
3130 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3131 let ip_address = SocketAddress::TcpIpV4{addr: [10, 255, 255, 255], port: 1000};
3132 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3135 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 0, 0], port: 1000};
3136 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3137 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 255, 187], port: 1000};
3138 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3139 let ip_address = SocketAddress::TcpIpV4{addr: [0, 255, 255, 255], port: 1000};
3140 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3143 let ip_address = SocketAddress::TcpIpV4{addr: [100, 64, 0, 0], port: 1000};
3144 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3145 let ip_address = SocketAddress::TcpIpV4{addr: [100, 78, 255, 0], port: 1000};
3146 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3147 let ip_address = SocketAddress::TcpIpV4{addr: [100, 127, 255, 255], port: 1000};
3148 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3151 let ip_address = SocketAddress::TcpIpV4{addr: [127, 0, 0, 0], port: 1000};
3152 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3153 let ip_address = SocketAddress::TcpIpV4{addr: [127, 65, 73, 0], port: 1000};
3154 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3155 let ip_address = SocketAddress::TcpIpV4{addr: [127, 255, 255, 255], port: 1000};
3156 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3159 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 0, 0], port: 1000};
3160 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3161 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 221, 101], port: 1000};
3162 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3163 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 255, 255], port: 1000};
3164 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3167 let ip_address = SocketAddress::TcpIpV4{addr: [172, 16, 0, 0], port: 1000};
3168 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3169 let ip_address = SocketAddress::TcpIpV4{addr: [172, 27, 101, 23], port: 1000};
3170 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3171 let ip_address = SocketAddress::TcpIpV4{addr: [172, 31, 255, 255], port: 1000};
3172 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3175 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 0, 0], port: 1000};
3176 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3177 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 205, 159], port: 1000};
3178 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3179 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 255, 255], port: 1000};
3180 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3182 // For (192.88.99/24)
3183 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 0], port: 1000};
3184 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3185 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 140], port: 1000};
3186 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3187 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 255], port: 1000};
3188 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3190 // For other IPv4 addresses
3191 let ip_address = SocketAddress::TcpIpV4{addr: [188, 255, 99, 0], port: 1000};
3192 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3193 let ip_address = SocketAddress::TcpIpV4{addr: [123, 8, 129, 14], port: 1000};
3194 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3195 let ip_address = SocketAddress::TcpIpV4{addr: [2, 88, 9, 255], port: 1000};
3196 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3199 let ip_address = SocketAddress::TcpIpV6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3200 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3201 let ip_address = SocketAddress::TcpIpV6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3202 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3203 let ip_address = SocketAddress::TcpIpV6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3204 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3206 // For other IPv6 addresses
3207 let ip_address = SocketAddress::TcpIpV6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3208 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3209 let ip_address = SocketAddress::TcpIpV6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3210 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3211 let ip_address = SocketAddress::TcpIpV6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3212 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3215 assert_eq!(filter_addresses(None), None);
3219 #[cfg(feature = "std")]
3220 fn test_process_events_multithreaded() {
3221 use std::time::{Duration, Instant};
3222 // Test that `process_events` getting called on multiple threads doesn't generate too many
3224 // Each time `process_events` goes around the loop we call
3225 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3226 // Because the loop should go around once more after a call which fails to take the
3227 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3228 // should never observe there having been more than 2 loop iterations.
3229 // Further, because the last thread to exit will call `process_events` before returning, we
3230 // should always have at least one count at the end.
3231 let cfg = Arc::new(create_peermgr_cfgs(1));
3232 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3233 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3235 let exit_flag = Arc::new(AtomicBool::new(false));
3236 macro_rules! spawn_thread { () => { {
3237 let thread_cfg = Arc::clone(&cfg);
3238 let thread_peer = Arc::clone(&peer);
3239 let thread_exit = Arc::clone(&exit_flag);
3240 std::thread::spawn(move || {
3241 while !thread_exit.load(Ordering::Acquire) {
3242 thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3243 thread_peer.process_events();
3244 std::thread::sleep(Duration::from_micros(1));
3249 let thread_a = spawn_thread!();
3250 let thread_b = spawn_thread!();
3251 let thread_c = spawn_thread!();
3253 let start_time = Instant::now();
3254 while start_time.elapsed() < Duration::from_millis(100) {
3255 let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3257 std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3260 exit_flag.store(true, Ordering::Release);
3261 thread_a.join().unwrap();
3262 thread_b.join().unwrap();
3263 thread_c.join().unwrap();
3264 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);