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::{KeysManager, NodeSigner, Recipient};
22 use crate::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
23 use crate::ln::features::{InitFeatures, NodeFeatures};
25 use crate::ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
26 use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
27 use crate::util::ser::{VecWriter, Writeable, Writer};
28 use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
30 use crate::ln::wire::{Encode, Type};
31 use crate::onion_message::packet::CustomOnionMessageContents;
32 use crate::onion_message::{CustomOnionMessageHandler, OffersMessage, OffersMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
33 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, NodeAlias};
34 use crate::util::atomic_counter::AtomicCounter;
35 use crate::util::logger::Logger;
36 use crate::util::string::PrintableString;
38 use crate::prelude::*;
40 use alloc::collections::LinkedList;
41 use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock};
42 use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering};
43 use core::{cmp, hash, fmt, mem};
45 use core::convert::Infallible;
46 #[cfg(feature = "std")] use std::error;
48 use bitcoin::hashes::sha256::Hash as Sha256;
49 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
50 use bitcoin::hashes::{HashEngine, Hash};
52 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
54 /// [BOLT 1] specifies a custom message type range for use with experimental or application-specific
55 /// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the
56 /// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler.
58 /// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
59 /// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message
60 pub trait CustomMessageHandler: wire::CustomMessageReader {
61 /// Handles the given message sent from `sender_node_id`, possibly producing messages for
62 /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`]
64 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
66 /// Returns the list of pending messages that were generated by the handler, clearing the list
67 /// in the process. Each message is paired with the node id of the intended recipient. If no
68 /// connection to the node exists, then the message is simply not sent.
69 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
71 /// Gets the node feature flags which this handler itself supports. All available handlers are
72 /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
73 /// which are broadcasted in our [`NodeAnnouncement`] message.
75 /// [`NodeAnnouncement`]: crate::ln::msgs::NodeAnnouncement
76 fn provided_node_features(&self) -> NodeFeatures;
78 /// Gets the init feature flags which should be sent to the given peer. All available handlers
79 /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
80 /// which are sent in our [`Init`] message.
82 /// [`Init`]: crate::ln::msgs::Init
83 fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
86 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
87 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
88 pub struct IgnoringMessageHandler{}
89 impl MessageSendEventsProvider for IgnoringMessageHandler {
90 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
92 impl RoutingMessageHandler for IgnoringMessageHandler {
93 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
94 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
95 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
96 fn get_next_channel_announcement(&self, _starting_point: u64) ->
97 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
98 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
99 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
100 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
101 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
102 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
103 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
104 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
105 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
106 InitFeatures::empty()
108 fn processing_queue_high(&self) -> bool { false }
110 impl OnionMessageProvider for IgnoringMessageHandler {
111 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
113 impl OnionMessageHandler for IgnoringMessageHandler {
114 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
115 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
116 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
117 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
118 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
119 InitFeatures::empty()
122 impl OffersMessageHandler for IgnoringMessageHandler {
123 fn handle_message(&self, _msg: OffersMessage) -> Option<OffersMessage> { None }
125 impl CustomOnionMessageHandler for IgnoringMessageHandler {
126 type CustomMessage = Infallible;
127 fn handle_custom_message(&self, _msg: Infallible) -> Option<Infallible> {
128 // Since we always return `None` in the read the handle method should never be called.
131 fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
136 impl CustomOnionMessageContents for Infallible {
137 fn tlv_type(&self) -> u64 { unreachable!(); }
140 impl Deref for IgnoringMessageHandler {
141 type Target = IgnoringMessageHandler;
142 fn deref(&self) -> &Self { self }
145 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
146 // method that takes self for it.
147 impl wire::Type for Infallible {
148 fn type_id(&self) -> u16 {
152 impl Writeable for Infallible {
153 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
158 impl wire::CustomMessageReader for IgnoringMessageHandler {
159 type CustomMessage = Infallible;
160 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
165 impl CustomMessageHandler for IgnoringMessageHandler {
166 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
167 // Since we always return `None` in the read the handle method should never be called.
171 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
173 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
175 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
176 InitFeatures::empty()
180 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
181 /// You can provide one of these as the route_handler in a MessageHandler.
182 pub struct ErroringMessageHandler {
183 message_queue: Mutex<Vec<MessageSendEvent>>
185 impl ErroringMessageHandler {
186 /// Constructs a new ErroringMessageHandler
187 pub fn new() -> Self {
188 Self { message_queue: Mutex::new(Vec::new()) }
190 fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
191 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
192 action: msgs::ErrorAction::SendErrorMessage {
193 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
195 node_id: node_id.clone(),
199 impl MessageSendEventsProvider for ErroringMessageHandler {
200 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
201 let mut res = Vec::new();
202 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
206 impl ChannelMessageHandler for ErroringMessageHandler {
207 // Any messages which are related to a specific channel generate an error message to let the
208 // peer know we don't care about channels.
209 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
210 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
212 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
213 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
215 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
216 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
218 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
219 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
221 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
222 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
224 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
225 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
227 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
228 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
230 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
231 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
233 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
234 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
236 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
237 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
239 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
240 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
242 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
243 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
245 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
246 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
248 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
249 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
251 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
252 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
254 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
255 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
257 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
258 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
259 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
260 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
261 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
262 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
263 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
264 // Set a number of features which various nodes may require to talk to us. It's totally
265 // reasonable to indicate we "support" all kinds of channel features...we just reject all
267 let mut features = InitFeatures::empty();
268 features.set_data_loss_protect_optional();
269 features.set_upfront_shutdown_script_optional();
270 features.set_variable_length_onion_optional();
271 features.set_static_remote_key_optional();
272 features.set_payment_secret_optional();
273 features.set_basic_mpp_optional();
274 features.set_wumbo_optional();
275 features.set_shutdown_any_segwit_optional();
276 features.set_channel_type_optional();
277 features.set_scid_privacy_optional();
278 features.set_zero_conf_optional();
282 fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
283 // We don't enforce any chains upon peer connection for `ErroringMessageHandler` and leave it up
284 // to users of `ErroringMessageHandler` to make decisions on network compatiblility.
285 // There's not really any way to pull in specific networks here, and hardcoding can cause breakages.
289 fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
290 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
293 fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
294 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
297 fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
298 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
301 fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
302 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
305 fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
306 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
309 fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
310 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
313 fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &msgs::TxComplete) {
314 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
317 fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
318 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
321 fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
322 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
325 fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
326 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
329 fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &msgs::TxAbort) {
330 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
334 impl Deref for ErroringMessageHandler {
335 type Target = ErroringMessageHandler;
336 fn deref(&self) -> &Self { self }
339 /// Provides references to trait impls which handle different types of messages.
340 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref, CustomM: Deref> where
341 CM::Target: ChannelMessageHandler,
342 RM::Target: RoutingMessageHandler,
343 OM::Target: OnionMessageHandler,
344 CustomM::Target: CustomMessageHandler,
346 /// A message handler which handles messages specific to channels. Usually this is just a
347 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
349 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
350 pub chan_handler: CM,
351 /// A message handler which handles messages updating our knowledge of the network channel
352 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
354 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
355 pub route_handler: RM,
357 /// A message handler which handles onion messages. This should generally be an
358 /// [`OnionMessenger`], but can also be an [`IgnoringMessageHandler`].
360 /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
361 pub onion_message_handler: OM,
363 /// A message handler which handles custom messages. The only LDK-provided implementation is
364 /// [`IgnoringMessageHandler`].
365 pub custom_message_handler: CustomM,
368 /// Provides an object which can be used to send data to and which uniquely identifies a connection
369 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
370 /// implement Hash to meet the PeerManager API.
372 /// For efficiency, [`Clone`] should be relatively cheap for this type.
374 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
375 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
376 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
377 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
378 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
379 /// to simply use another value which is guaranteed to be globally unique instead.
380 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
381 /// Attempts to send some data from the given slice to the peer.
383 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
384 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
385 /// called and further write attempts may occur until that time.
387 /// If the returned size is smaller than `data.len()`, a
388 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
389 /// written. Additionally, until a `send_data` event completes fully, no further
390 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
391 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
394 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
395 /// (indicating that read events should be paused to prevent DoS in the send buffer),
396 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
397 /// `resume_read` of false carries no meaning, and should not cause any action.
398 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
399 /// Disconnect the socket pointed to by this SocketDescriptor.
401 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
402 /// call (doing so is a noop).
403 fn disconnect_socket(&mut self);
406 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
407 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
410 pub struct PeerHandleError { }
411 impl fmt::Debug for PeerHandleError {
412 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
413 formatter.write_str("Peer Sent Invalid Data")
416 impl fmt::Display for PeerHandleError {
417 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
418 formatter.write_str("Peer Sent Invalid Data")
422 #[cfg(feature = "std")]
423 impl error::Error for PeerHandleError {
424 fn description(&self) -> &str {
425 "Peer Sent Invalid Data"
429 enum InitSyncTracker{
431 ChannelsSyncing(u64),
432 NodesSyncing(NodeId),
435 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
436 /// forwarding gossip messages to peers altogether.
437 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
439 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
440 /// we have fewer than this many messages in the outbound buffer again.
441 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
442 /// refilled as we send bytes.
443 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
444 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
446 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
448 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
449 /// the socket receive buffer before receiving the ping.
451 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
452 /// including any network delays, outbound traffic, or the same for messages from other peers.
454 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
455 /// per connected peer to respond to a ping, as long as they send us at least one message during
456 /// each tick, ensuring we aren't actually just disconnected.
457 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
460 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
461 /// two connected peers, assuming most LDK-running systems have at least two cores.
462 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
464 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
465 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
466 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
467 /// process before the next ping.
469 /// Note that we continue responding to other messages even after we've sent this many messages, so
470 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
471 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
472 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
475 channel_encryptor: PeerChannelEncryptor,
476 /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
477 /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
478 their_node_id: Option<(PublicKey, NodeId)>,
479 /// The features provided in the peer's [`msgs::Init`] message.
481 /// This is set only after we've processed the [`msgs::Init`] message and called relevant
482 /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
483 /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
485 their_features: Option<InitFeatures>,
486 their_net_address: Option<NetAddress>,
488 pending_outbound_buffer: LinkedList<Vec<u8>>,
489 pending_outbound_buffer_first_msg_offset: usize,
490 /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
491 /// prioritize channel messages over them.
493 /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
494 gossip_broadcast_buffer: LinkedList<Vec<u8>>,
495 awaiting_write_event: bool,
497 pending_read_buffer: Vec<u8>,
498 pending_read_buffer_pos: usize,
499 pending_read_is_header: bool,
501 sync_status: InitSyncTracker,
503 msgs_sent_since_pong: usize,
504 awaiting_pong_timer_tick_intervals: i64,
505 received_message_since_timer_tick: bool,
506 sent_gossip_timestamp_filter: bool,
508 /// Indicates we've received a `channel_announcement` since the last time we had
509 /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
510 /// `channel_announcement` at all - we set this unconditionally but unset it every time we
511 /// check if we're gossip-processing-backlogged).
512 received_channel_announce_since_backlogged: bool,
514 inbound_connection: bool,
518 /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
519 /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
521 fn handshake_complete(&self) -> bool {
522 self.their_features.is_some()
525 /// Returns true if the channel announcements/updates for the given channel should be
526 /// forwarded to this peer.
527 /// If we are sending our routing table to this peer and we have not yet sent channel
528 /// announcements/updates for the given channel_id then we will send it when we get to that
529 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
530 /// sent the old versions, we should send the update, and so return true here.
531 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
532 if !self.handshake_complete() { return false; }
533 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
534 !self.sent_gossip_timestamp_filter {
537 match self.sync_status {
538 InitSyncTracker::NoSyncRequested => true,
539 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
540 InitSyncTracker::NodesSyncing(_) => true,
544 /// Similar to the above, but for node announcements indexed by node_id.
545 fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
546 if !self.handshake_complete() { return false; }
547 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
548 !self.sent_gossip_timestamp_filter {
551 match self.sync_status {
552 InitSyncTracker::NoSyncRequested => true,
553 InitSyncTracker::ChannelsSyncing(_) => false,
554 InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
558 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
559 /// buffer still has space and we don't need to pause reads to get some writes out.
560 fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
561 if !gossip_processing_backlogged {
562 self.received_channel_announce_since_backlogged = false;
564 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
565 (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
568 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
569 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
570 fn should_buffer_gossip_backfill(&self) -> bool {
571 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
572 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
573 && self.handshake_complete()
576 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
577 /// every time the peer's buffer may have been drained.
578 fn should_buffer_onion_message(&self) -> bool {
579 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
580 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
583 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
584 /// buffer. This is checked every time the peer's buffer may have been drained.
585 fn should_buffer_gossip_broadcast(&self) -> bool {
586 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
587 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
590 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
591 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
592 let total_outbound_buffered =
593 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
595 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
596 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
599 fn set_their_node_id(&mut self, node_id: PublicKey) {
600 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
604 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
605 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
606 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
607 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
608 /// issues such as overly long function definitions.
610 /// This is not exported to bindings users as `Arc`s don't make sense in bindings.
611 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<
613 Arc<SimpleArcChannelManager<M, T, F, L>>,
614 Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, Arc<C>, Arc<L>>>,
615 Arc<SimpleArcOnionMessenger<L>>,
617 IgnoringMessageHandler,
621 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
622 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
623 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
624 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
625 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
626 /// helps with issues such as long function definitions.
628 /// This is not exported to bindings users as general type aliases don't make sense in bindings.
629 pub type SimpleRefPeerManager<
630 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'l, 'm, 'n, SD, M, T, F, C, L
633 &'n SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'm, M, T, F, L>,
634 &'f P2PGossipSync<&'g NetworkGraph<&'f L>, &'h C, &'f L>,
635 &'i SimpleRefOnionMessenger<'g, 'm, 'n, L>,
637 IgnoringMessageHandler,
642 /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or
643 /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather
644 /// than the full set of bounds on [`PeerManager`] itself.
646 /// This is not exported to bindings users as general cover traits aren't useful in other
648 #[allow(missing_docs)]
649 pub trait APeerManager {
650 type Descriptor: SocketDescriptor;
651 type CMT: ChannelMessageHandler + ?Sized;
652 type CM: Deref<Target=Self::CMT>;
653 type RMT: RoutingMessageHandler + ?Sized;
654 type RM: Deref<Target=Self::RMT>;
655 type OMT: OnionMessageHandler + ?Sized;
656 type OM: Deref<Target=Self::OMT>;
657 type LT: Logger + ?Sized;
658 type L: Deref<Target=Self::LT>;
659 type CMHT: CustomMessageHandler + ?Sized;
660 type CMH: Deref<Target=Self::CMHT>;
661 type NST: NodeSigner + ?Sized;
662 type NS: Deref<Target=Self::NST>;
663 /// Gets a reference to the underlying [`PeerManager`].
664 fn as_ref(&self) -> &PeerManager<Self::Descriptor, Self::CM, Self::RM, Self::OM, Self::L, Self::CMH, Self::NS>;
667 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref>
668 APeerManager for PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
669 CM::Target: ChannelMessageHandler,
670 RM::Target: RoutingMessageHandler,
671 OM::Target: OnionMessageHandler,
673 CMH::Target: CustomMessageHandler,
674 NS::Target: NodeSigner,
676 type Descriptor = Descriptor;
677 type CMT = <CM as Deref>::Target;
679 type RMT = <RM as Deref>::Target;
681 type OMT = <OM as Deref>::Target;
683 type LT = <L as Deref>::Target;
685 type CMHT = <CMH as Deref>::Target;
687 type NST = <NS as Deref>::Target;
689 fn as_ref(&self) -> &PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> { self }
692 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
693 /// socket events into messages which it passes on to its [`MessageHandler`].
695 /// Locks are taken internally, so you must never assume that reentrancy from a
696 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
698 /// Calls to [`read_event`] will decode relevant messages and pass them to the
699 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
700 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
701 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
702 /// calls only after previous ones have returned.
704 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
705 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
706 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
707 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
708 /// you're using lightning-net-tokio.
710 /// [`read_event`]: PeerManager::read_event
711 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
712 CM::Target: ChannelMessageHandler,
713 RM::Target: RoutingMessageHandler,
714 OM::Target: OnionMessageHandler,
716 CMH::Target: CustomMessageHandler,
717 NS::Target: NodeSigner {
718 message_handler: MessageHandler<CM, RM, OM, CMH>,
719 /// Connection state for each connected peer - we have an outer read-write lock which is taken
720 /// as read while we're doing processing for a peer and taken write when a peer is being added
723 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
724 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
725 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
726 /// the `MessageHandler`s for a given peer is already guaranteed.
727 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
728 /// Only add to this set when noise completes.
729 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
730 /// lock held. Entries may be added with only the `peers` read lock held (though the
731 /// `Descriptor` value must already exist in `peers`).
732 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
733 /// We can only have one thread processing events at once, but if a second call to
734 /// `process_events` happens while a first call is in progress, one of the two calls needs to
735 /// start from the top to ensure any new messages are also handled.
737 /// Because the event handler calls into user code which may block, we don't want to block a
738 /// second thread waiting for another thread to handle events which is then blocked on user
739 /// code, so we store an atomic counter here:
740 /// * 0 indicates no event processor is running
741 /// * 1 indicates an event processor is running
742 /// * > 1 indicates an event processor is running but needs to start again from the top once
743 /// it finishes as another thread tried to start processing events but returned early.
744 event_processing_state: AtomicI32,
746 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
747 /// value increases strictly since we don't assume access to a time source.
748 last_node_announcement_serial: AtomicU32,
750 ephemeral_key_midstate: Sha256Engine,
752 peer_counter: AtomicCounter,
754 gossip_processing_backlogged: AtomicBool,
755 gossip_processing_backlog_lifted: AtomicBool,
760 secp_ctx: Secp256k1<secp256k1::SignOnly>
763 enum MessageHandlingError {
764 PeerHandleError(PeerHandleError),
765 LightningError(LightningError),
768 impl From<PeerHandleError> for MessageHandlingError {
769 fn from(error: PeerHandleError) -> Self {
770 MessageHandlingError::PeerHandleError(error)
774 impl From<LightningError> for MessageHandlingError {
775 fn from(error: LightningError) -> Self {
776 MessageHandlingError::LightningError(error)
780 macro_rules! encode_msg {
782 let mut buffer = VecWriter(Vec::new());
783 wire::write($msg, &mut buffer).unwrap();
788 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
789 CM::Target: ChannelMessageHandler,
790 OM::Target: OnionMessageHandler,
792 NS::Target: NodeSigner {
793 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
794 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
797 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
798 /// cryptographically secure random bytes.
800 /// `current_time` is used as an always-increasing counter that survives across restarts and is
801 /// incremented irregularly internally. In general it is best to simply use the current UNIX
802 /// timestamp, however if it is not available a persistent counter that increases once per
803 /// minute should suffice.
805 /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
806 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 {
807 Self::new(MessageHandler {
808 chan_handler: channel_message_handler,
809 route_handler: IgnoringMessageHandler{},
810 onion_message_handler,
811 custom_message_handler: IgnoringMessageHandler{},
812 }, current_time, ephemeral_random_data, logger, node_signer)
816 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
817 RM::Target: RoutingMessageHandler,
819 NS::Target: NodeSigner {
820 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
821 /// handler or onion message handler is used and onion and channel messages will be ignored (or
822 /// generate error messages). Note that some other lightning implementations time-out connections
823 /// after some time if no channel is built with the peer.
825 /// `current_time` is used as an always-increasing counter that survives across restarts and is
826 /// incremented irregularly internally. In general it is best to simply use the current UNIX
827 /// timestamp, however if it is not available a persistent counter that increases once per
828 /// minute should suffice.
830 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
831 /// cryptographically secure random bytes.
833 /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
834 pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
835 Self::new(MessageHandler {
836 chan_handler: ErroringMessageHandler::new(),
837 route_handler: routing_message_handler,
838 onion_message_handler: IgnoringMessageHandler{},
839 custom_message_handler: IgnoringMessageHandler{},
840 }, current_time, ephemeral_random_data, logger, node_signer)
844 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
845 /// This works around `format!()` taking a reference to each argument, preventing
846 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
847 /// due to lifetime errors.
848 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
849 impl core::fmt::Display for OptionalFromDebugger<'_> {
850 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
851 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
855 /// A function used to filter out local or private addresses
856 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
857 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
858 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
860 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
861 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
862 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
863 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
864 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
865 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
866 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
867 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
868 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
869 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
870 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
871 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
872 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
873 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
874 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
875 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
876 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
877 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
878 // For remaining addresses
879 Some(NetAddress::IPv6{addr: _, port: _}) => None,
880 Some(..) => ip_address,
885 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
886 CM::Target: ChannelMessageHandler,
887 RM::Target: RoutingMessageHandler,
888 OM::Target: OnionMessageHandler,
890 CMH::Target: CustomMessageHandler,
891 NS::Target: NodeSigner
893 /// Constructs a new `PeerManager` with the given message handlers.
895 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
896 /// cryptographically secure random bytes.
898 /// `current_time` is used as an always-increasing counter that survives across restarts and is
899 /// incremented irregularly internally. In general it is best to simply use the current UNIX
900 /// timestamp, however if it is not available a persistent counter that increases once per
901 /// minute should suffice.
902 pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
903 let mut ephemeral_key_midstate = Sha256::engine();
904 ephemeral_key_midstate.input(ephemeral_random_data);
906 let mut secp_ctx = Secp256k1::signing_only();
907 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
908 secp_ctx.seeded_randomize(&ephemeral_hash);
912 peers: FairRwLock::new(HashMap::new()),
913 node_id_to_descriptor: Mutex::new(HashMap::new()),
914 event_processing_state: AtomicI32::new(0),
915 ephemeral_key_midstate,
916 peer_counter: AtomicCounter::new(),
917 gossip_processing_backlogged: AtomicBool::new(false),
918 gossip_processing_backlog_lifted: AtomicBool::new(false),
919 last_node_announcement_serial: AtomicU32::new(current_time),
926 /// Get a list of tuples mapping from node id to network addresses for peers which have
927 /// completed the initial handshake.
929 /// For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter
930 /// passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial
931 /// handshake has completed and we are sure the remote peer has the private key for the given
934 /// The returned `Option`s will only be `Some` if an address had been previously given via
935 /// [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`].
936 pub fn get_peer_node_ids(&self) -> Vec<(PublicKey, Option<NetAddress>)> {
937 let peers = self.peers.read().unwrap();
938 peers.values().filter_map(|peer_mutex| {
939 let p = peer_mutex.lock().unwrap();
940 if !p.handshake_complete() {
943 Some((p.their_node_id.unwrap().0, p.their_net_address.clone()))
947 fn get_ephemeral_key(&self) -> SecretKey {
948 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
949 let counter = self.peer_counter.get_increment();
950 ephemeral_hash.input(&counter.to_le_bytes());
951 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
954 fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
955 self.message_handler.chan_handler.provided_init_features(their_node_id)
956 | self.message_handler.route_handler.provided_init_features(their_node_id)
957 | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
958 | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
961 /// Indicates a new outbound connection has been established to a node with the given `node_id`
962 /// and an optional remote network address.
964 /// The remote network address adds the option to report a remote IP address back to a connecting
965 /// peer using the init message.
966 /// The user should pass the remote network address of the host they are connected to.
968 /// If an `Err` is returned here you must disconnect the connection immediately.
970 /// Returns a small number of bytes to send to the remote node (currently always 50).
972 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
973 /// [`socket_disconnected`].
975 /// [`socket_disconnected`]: PeerManager::socket_disconnected
976 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
977 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
978 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
979 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
981 let mut peers = self.peers.write().unwrap();
982 match peers.entry(descriptor) {
983 hash_map::Entry::Occupied(_) => {
984 debug_assert!(false, "PeerManager driver duplicated descriptors!");
985 Err(PeerHandleError {})
987 hash_map::Entry::Vacant(e) => {
988 e.insert(Mutex::new(Peer {
989 channel_encryptor: peer_encryptor,
991 their_features: None,
992 their_net_address: remote_network_address,
994 pending_outbound_buffer: LinkedList::new(),
995 pending_outbound_buffer_first_msg_offset: 0,
996 gossip_broadcast_buffer: LinkedList::new(),
997 awaiting_write_event: false,
1000 pending_read_buffer_pos: 0,
1001 pending_read_is_header: false,
1003 sync_status: InitSyncTracker::NoSyncRequested,
1005 msgs_sent_since_pong: 0,
1006 awaiting_pong_timer_tick_intervals: 0,
1007 received_message_since_timer_tick: false,
1008 sent_gossip_timestamp_filter: false,
1010 received_channel_announce_since_backlogged: false,
1011 inbound_connection: false,
1018 /// Indicates a new inbound connection has been established to a node with an optional remote
1019 /// network address.
1021 /// The remote network address adds the option to report a remote IP address back to a connecting
1022 /// peer using the init message.
1023 /// The user should pass the remote network address of the host they are connected to.
1025 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
1026 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
1027 /// the connection immediately.
1029 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1030 /// [`socket_disconnected`].
1032 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1033 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
1034 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1035 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1037 let mut peers = self.peers.write().unwrap();
1038 match peers.entry(descriptor) {
1039 hash_map::Entry::Occupied(_) => {
1040 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1041 Err(PeerHandleError {})
1043 hash_map::Entry::Vacant(e) => {
1044 e.insert(Mutex::new(Peer {
1045 channel_encryptor: peer_encryptor,
1046 their_node_id: None,
1047 their_features: None,
1048 their_net_address: remote_network_address,
1050 pending_outbound_buffer: LinkedList::new(),
1051 pending_outbound_buffer_first_msg_offset: 0,
1052 gossip_broadcast_buffer: LinkedList::new(),
1053 awaiting_write_event: false,
1055 pending_read_buffer,
1056 pending_read_buffer_pos: 0,
1057 pending_read_is_header: false,
1059 sync_status: InitSyncTracker::NoSyncRequested,
1061 msgs_sent_since_pong: 0,
1062 awaiting_pong_timer_tick_intervals: 0,
1063 received_message_since_timer_tick: false,
1064 sent_gossip_timestamp_filter: false,
1066 received_channel_announce_since_backlogged: false,
1067 inbound_connection: true,
1074 fn peer_should_read(&self, peer: &mut Peer) -> bool {
1075 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1078 fn update_gossip_backlogged(&self) {
1079 let new_state = self.message_handler.route_handler.processing_queue_high();
1080 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1081 if prev_state && !new_state {
1082 self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1086 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1087 let mut have_written = false;
1088 while !peer.awaiting_write_event {
1089 if peer.should_buffer_onion_message() {
1090 if let Some((peer_node_id, _)) = peer.their_node_id {
1091 if let Some(next_onion_message) =
1092 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1093 self.enqueue_message(peer, &next_onion_message);
1097 if peer.should_buffer_gossip_broadcast() {
1098 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1099 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..]));
1102 if peer.should_buffer_gossip_backfill() {
1103 match peer.sync_status {
1104 InitSyncTracker::NoSyncRequested => {},
1105 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1106 if let Some((announce, update_a_option, update_b_option)) =
1107 self.message_handler.route_handler.get_next_channel_announcement(c)
1109 self.enqueue_message(peer, &announce);
1110 if let Some(update_a) = update_a_option {
1111 self.enqueue_message(peer, &update_a);
1113 if let Some(update_b) = update_b_option {
1114 self.enqueue_message(peer, &update_b);
1116 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1118 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1121 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1122 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1123 self.enqueue_message(peer, &msg);
1124 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1126 peer.sync_status = InitSyncTracker::NoSyncRequested;
1129 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1130 InitSyncTracker::NodesSyncing(sync_node_id) => {
1131 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1132 self.enqueue_message(peer, &msg);
1133 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1135 peer.sync_status = InitSyncTracker::NoSyncRequested;
1140 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1141 self.maybe_send_extra_ping(peer);
1144 let should_read = self.peer_should_read(peer);
1145 let next_buff = match peer.pending_outbound_buffer.front() {
1147 if force_one_write && !have_written {
1149 let data_sent = descriptor.send_data(&[], should_read);
1150 debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1158 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1159 let data_sent = descriptor.send_data(pending, should_read);
1160 have_written = true;
1161 peer.pending_outbound_buffer_first_msg_offset += data_sent;
1162 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1163 peer.pending_outbound_buffer_first_msg_offset = 0;
1164 peer.pending_outbound_buffer.pop_front();
1166 peer.awaiting_write_event = true;
1171 /// Indicates that there is room to write data to the given socket descriptor.
1173 /// May return an Err to indicate that the connection should be closed.
1175 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1176 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1177 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1178 /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1181 /// [`send_data`]: SocketDescriptor::send_data
1182 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1183 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1184 let peers = self.peers.read().unwrap();
1185 match peers.get(descriptor) {
1187 // This is most likely a simple race condition where the user found that the socket
1188 // was writeable, then we told the user to `disconnect_socket()`, then they called
1189 // this method. Return an error to make sure we get disconnected.
1190 return Err(PeerHandleError { });
1192 Some(peer_mutex) => {
1193 let mut peer = peer_mutex.lock().unwrap();
1194 peer.awaiting_write_event = false;
1195 self.do_attempt_write_data(descriptor, &mut peer, false);
1201 /// Indicates that data was read from the given socket descriptor.
1203 /// May return an Err to indicate that the connection should be closed.
1205 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1206 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1207 /// [`send_data`] calls to handle responses.
1209 /// If `Ok(true)` is returned, further read_events should not be triggered until a
1210 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1213 /// In order to avoid processing too many messages at once per peer, `data` should be on the
1216 /// [`send_data`]: SocketDescriptor::send_data
1217 /// [`process_events`]: PeerManager::process_events
1218 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1219 match self.do_read_event(peer_descriptor, data) {
1222 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1223 self.disconnect_event_internal(peer_descriptor);
1229 /// Append a message to a peer's pending outbound/write buffer
1230 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1231 if is_gossip_msg(message.type_id()) {
1232 log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1234 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1236 peer.msgs_sent_since_pong += 1;
1237 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1240 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1241 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: Vec<u8>) {
1242 peer.msgs_sent_since_pong += 1;
1243 peer.gossip_broadcast_buffer.push_back(encoded_message);
1246 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1247 let mut pause_read = false;
1248 let peers = self.peers.read().unwrap();
1249 let mut msgs_to_forward = Vec::new();
1250 let mut peer_node_id = None;
1251 match peers.get(peer_descriptor) {
1253 // This is most likely a simple race condition where the user read some bytes
1254 // from the socket, then we told the user to `disconnect_socket()`, then they
1255 // called this method. Return an error to make sure we get disconnected.
1256 return Err(PeerHandleError { });
1258 Some(peer_mutex) => {
1259 let mut read_pos = 0;
1260 while read_pos < data.len() {
1261 macro_rules! try_potential_handleerror {
1262 ($peer: expr, $thing: expr) => {
1267 msgs::ErrorAction::DisconnectPeer { .. } => {
1268 // We may have an `ErrorMessage` to send to the peer,
1269 // but writing to the socket while reading can lead to
1270 // re-entrant code and possibly unexpected behavior. The
1271 // message send is optimistic anyway, and in this case
1272 // we immediately disconnect the peer.
1273 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1274 return Err(PeerHandleError { });
1276 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1277 // We have a `WarningMessage` to send to the peer, but
1278 // writing to the socket while reading can lead to
1279 // re-entrant code and possibly unexpected behavior. The
1280 // message send is optimistic anyway, and in this case
1281 // we immediately disconnect the peer.
1282 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1283 return Err(PeerHandleError { });
1285 msgs::ErrorAction::IgnoreAndLog(level) => {
1286 log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1289 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1290 msgs::ErrorAction::IgnoreError => {
1291 log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1294 msgs::ErrorAction::SendErrorMessage { msg } => {
1295 log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1296 self.enqueue_message($peer, &msg);
1299 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1300 log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1301 self.enqueue_message($peer, &msg);
1310 let mut peer_lock = peer_mutex.lock().unwrap();
1311 let peer = &mut *peer_lock;
1312 let mut msg_to_handle = None;
1313 if peer_node_id.is_none() {
1314 peer_node_id = peer.their_node_id.clone();
1317 assert!(peer.pending_read_buffer.len() > 0);
1318 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1321 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1322 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]);
1323 read_pos += data_to_copy;
1324 peer.pending_read_buffer_pos += data_to_copy;
1327 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1328 peer.pending_read_buffer_pos = 0;
1330 macro_rules! insert_node_id {
1332 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1333 hash_map::Entry::Occupied(e) => {
1334 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1335 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1336 // Check that the peers map is consistent with the
1337 // node_id_to_descriptor map, as this has been broken
1339 debug_assert!(peers.get(e.get()).is_some());
1340 return Err(PeerHandleError { })
1342 hash_map::Entry::Vacant(entry) => {
1343 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1344 entry.insert(peer_descriptor.clone())
1350 let next_step = peer.channel_encryptor.get_noise_step();
1352 NextNoiseStep::ActOne => {
1353 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1354 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1355 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1356 peer.pending_outbound_buffer.push_back(act_two);
1357 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1359 NextNoiseStep::ActTwo => {
1360 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1361 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1362 &self.node_signer));
1363 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1364 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1365 peer.pending_read_is_header = true;
1367 peer.set_their_node_id(their_node_id);
1369 let features = self.init_features(&their_node_id);
1370 let networks = self.message_handler.chan_handler.get_genesis_hashes();
1371 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1372 self.enqueue_message(peer, &resp);
1373 peer.awaiting_pong_timer_tick_intervals = 0;
1375 NextNoiseStep::ActThree => {
1376 let their_node_id = try_potential_handleerror!(peer,
1377 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1378 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1379 peer.pending_read_is_header = true;
1380 peer.set_their_node_id(their_node_id);
1382 let features = self.init_features(&their_node_id);
1383 let networks = self.message_handler.chan_handler.get_genesis_hashes();
1384 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1385 self.enqueue_message(peer, &resp);
1386 peer.awaiting_pong_timer_tick_intervals = 0;
1388 NextNoiseStep::NoiseComplete => {
1389 if peer.pending_read_is_header {
1390 let msg_len = try_potential_handleerror!(peer,
1391 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1392 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1393 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1394 if msg_len < 2 { // Need at least the message type tag
1395 return Err(PeerHandleError { });
1397 peer.pending_read_is_header = false;
1399 let msg_data = try_potential_handleerror!(peer,
1400 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1401 assert!(msg_data.len() >= 2);
1403 // Reset read buffer
1404 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1405 peer.pending_read_buffer.resize(18, 0);
1406 peer.pending_read_is_header = true;
1408 let mut reader = io::Cursor::new(&msg_data[..]);
1409 let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1410 let message = match message_result {
1414 // Note that to avoid re-entrancy we never call
1415 // `do_attempt_write_data` from here, causing
1416 // the messages enqueued here to not actually
1417 // be sent before the peer is disconnected.
1418 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1419 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1422 (msgs::DecodeError::UnsupportedCompression, _) => {
1423 log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1424 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1427 (_, Some(ty)) if is_gossip_msg(ty) => {
1428 log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1429 self.enqueue_message(peer, &msgs::WarningMessage {
1430 channel_id: [0; 32],
1431 data: format!("Unreadable/bogus gossip message of type {}", ty),
1435 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1436 log_debug!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1437 return Err(PeerHandleError { });
1439 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1440 (msgs::DecodeError::InvalidValue, _) => {
1441 log_debug!(self.logger, "Got an invalid value while deserializing message");
1442 return Err(PeerHandleError { });
1444 (msgs::DecodeError::ShortRead, _) => {
1445 log_debug!(self.logger, "Deserialization failed due to shortness of message");
1446 return Err(PeerHandleError { });
1448 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1449 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1454 msg_to_handle = Some(message);
1459 pause_read = !self.peer_should_read(peer);
1461 if let Some(message) = msg_to_handle {
1462 match self.handle_message(&peer_mutex, peer_lock, message) {
1463 Err(handling_error) => match handling_error {
1464 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1465 MessageHandlingError::LightningError(e) => {
1466 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1470 msgs_to_forward.push(msg);
1479 for msg in msgs_to_forward.drain(..) {
1480 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1486 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1487 /// Returns the message back if it needs to be broadcasted to all other peers.
1490 peer_mutex: &Mutex<Peer>,
1491 mut peer_lock: MutexGuard<Peer>,
1492 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1493 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1494 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;
1495 peer_lock.received_message_since_timer_tick = true;
1497 // Need an Init as first message
1498 if let wire::Message::Init(msg) = message {
1499 // Check if we have any compatible chains if the `networks` field is specified.
1500 if let Some(networks) = &msg.networks {
1501 if let Some(our_chains) = self.message_handler.chan_handler.get_genesis_hashes() {
1502 let mut have_compatible_chains = false;
1503 'our_chains: for our_chain in our_chains.iter() {
1504 for their_chain in networks {
1505 if our_chain == their_chain {
1506 have_compatible_chains = true;
1511 if !have_compatible_chains {
1512 log_debug!(self.logger, "Peer does not support any of our supported chains");
1513 return Err(PeerHandleError { }.into());
1518 let our_features = self.init_features(&their_node_id);
1519 if msg.features.requires_unknown_bits_from(&our_features) {
1520 log_debug!(self.logger, "Peer requires features unknown to us");
1521 return Err(PeerHandleError { }.into());
1524 if our_features.requires_unknown_bits_from(&msg.features) {
1525 log_debug!(self.logger, "We require features unknown to our peer");
1526 return Err(PeerHandleError { }.into());
1529 if peer_lock.their_features.is_some() {
1530 return Err(PeerHandleError { }.into());
1533 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1535 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1536 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1537 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1540 if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1541 log_debug!(self.logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1542 return Err(PeerHandleError { }.into());
1544 if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1545 log_debug!(self.logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1546 return Err(PeerHandleError { }.into());
1548 if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1549 log_debug!(self.logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1550 return Err(PeerHandleError { }.into());
1553 peer_lock.their_features = Some(msg.features);
1555 } else if peer_lock.their_features.is_none() {
1556 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1557 return Err(PeerHandleError { }.into());
1560 if let wire::Message::GossipTimestampFilter(_msg) = message {
1561 // When supporting gossip messages, start inital gossip sync only after we receive
1562 // a GossipTimestampFilter
1563 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1564 !peer_lock.sent_gossip_timestamp_filter {
1565 peer_lock.sent_gossip_timestamp_filter = true;
1566 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1571 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1572 peer_lock.received_channel_announce_since_backlogged = true;
1575 mem::drop(peer_lock);
1577 if is_gossip_msg(message.type_id()) {
1578 log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1580 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1583 let mut should_forward = None;
1586 // Setup and Control messages:
1587 wire::Message::Init(_) => {
1590 wire::Message::GossipTimestampFilter(_) => {
1593 wire::Message::Error(msg) => {
1594 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1595 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1596 if msg.channel_id == [0; 32] {
1597 return Err(PeerHandleError { }.into());
1600 wire::Message::Warning(msg) => {
1601 log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1604 wire::Message::Ping(msg) => {
1605 if msg.ponglen < 65532 {
1606 let resp = msgs::Pong { byteslen: msg.ponglen };
1607 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1610 wire::Message::Pong(_msg) => {
1611 let mut peer_lock = peer_mutex.lock().unwrap();
1612 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1613 peer_lock.msgs_sent_since_pong = 0;
1616 // Channel messages:
1617 wire::Message::OpenChannel(msg) => {
1618 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1620 wire::Message::OpenChannelV2(msg) => {
1621 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1623 wire::Message::AcceptChannel(msg) => {
1624 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1626 wire::Message::AcceptChannelV2(msg) => {
1627 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1630 wire::Message::FundingCreated(msg) => {
1631 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1633 wire::Message::FundingSigned(msg) => {
1634 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1636 wire::Message::ChannelReady(msg) => {
1637 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1640 // Interactive transaction construction messages:
1641 wire::Message::TxAddInput(msg) => {
1642 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1644 wire::Message::TxAddOutput(msg) => {
1645 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1647 wire::Message::TxRemoveInput(msg) => {
1648 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1650 wire::Message::TxRemoveOutput(msg) => {
1651 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1653 wire::Message::TxComplete(msg) => {
1654 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1656 wire::Message::TxSignatures(msg) => {
1657 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1659 wire::Message::TxInitRbf(msg) => {
1660 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1662 wire::Message::TxAckRbf(msg) => {
1663 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1665 wire::Message::TxAbort(msg) => {
1666 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1669 wire::Message::Shutdown(msg) => {
1670 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1672 wire::Message::ClosingSigned(msg) => {
1673 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1676 // Commitment messages:
1677 wire::Message::UpdateAddHTLC(msg) => {
1678 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1680 wire::Message::UpdateFulfillHTLC(msg) => {
1681 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1683 wire::Message::UpdateFailHTLC(msg) => {
1684 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1686 wire::Message::UpdateFailMalformedHTLC(msg) => {
1687 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1690 wire::Message::CommitmentSigned(msg) => {
1691 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1693 wire::Message::RevokeAndACK(msg) => {
1694 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1696 wire::Message::UpdateFee(msg) => {
1697 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1699 wire::Message::ChannelReestablish(msg) => {
1700 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1703 // Routing messages:
1704 wire::Message::AnnouncementSignatures(msg) => {
1705 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1707 wire::Message::ChannelAnnouncement(msg) => {
1708 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1709 .map_err(|e| -> MessageHandlingError { e.into() })? {
1710 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1712 self.update_gossip_backlogged();
1714 wire::Message::NodeAnnouncement(msg) => {
1715 if self.message_handler.route_handler.handle_node_announcement(&msg)
1716 .map_err(|e| -> MessageHandlingError { e.into() })? {
1717 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1719 self.update_gossip_backlogged();
1721 wire::Message::ChannelUpdate(msg) => {
1722 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1723 if self.message_handler.route_handler.handle_channel_update(&msg)
1724 .map_err(|e| -> MessageHandlingError { e.into() })? {
1725 should_forward = Some(wire::Message::ChannelUpdate(msg));
1727 self.update_gossip_backlogged();
1729 wire::Message::QueryShortChannelIds(msg) => {
1730 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1732 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1733 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1735 wire::Message::QueryChannelRange(msg) => {
1736 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1738 wire::Message::ReplyChannelRange(msg) => {
1739 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1743 wire::Message::OnionMessage(msg) => {
1744 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1747 // Unknown messages:
1748 wire::Message::Unknown(type_id) if message.is_even() => {
1749 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1750 return Err(PeerHandleError { }.into());
1752 wire::Message::Unknown(type_id) => {
1753 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1755 wire::Message::Custom(custom) => {
1756 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1762 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>) {
1764 wire::Message::ChannelAnnouncement(ref msg) => {
1765 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1766 let encoded_msg = encode_msg!(msg);
1768 for (_, peer_mutex) in peers.iter() {
1769 let mut peer = peer_mutex.lock().unwrap();
1770 if !peer.handshake_complete() ||
1771 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1774 debug_assert!(peer.their_node_id.is_some());
1775 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1776 if peer.buffer_full_drop_gossip_broadcast() {
1777 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1780 if let Some((_, their_node_id)) = peer.their_node_id {
1781 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1785 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1788 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1791 wire::Message::NodeAnnouncement(ref msg) => {
1792 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1793 let encoded_msg = encode_msg!(msg);
1795 for (_, peer_mutex) in peers.iter() {
1796 let mut peer = peer_mutex.lock().unwrap();
1797 if !peer.handshake_complete() ||
1798 !peer.should_forward_node_announcement(msg.contents.node_id) {
1801 debug_assert!(peer.their_node_id.is_some());
1802 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1803 if peer.buffer_full_drop_gossip_broadcast() {
1804 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1807 if let Some((_, their_node_id)) = peer.their_node_id {
1808 if their_node_id == msg.contents.node_id {
1812 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1815 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1818 wire::Message::ChannelUpdate(ref msg) => {
1819 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1820 let encoded_msg = encode_msg!(msg);
1822 for (_, peer_mutex) in peers.iter() {
1823 let mut peer = peer_mutex.lock().unwrap();
1824 if !peer.handshake_complete() ||
1825 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1828 debug_assert!(peer.their_node_id.is_some());
1829 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1830 if peer.buffer_full_drop_gossip_broadcast() {
1831 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1834 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1837 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1840 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1844 /// Checks for any events generated by our handlers and processes them. Includes sending most
1845 /// response messages as well as messages generated by calls to handler functions directly (eg
1846 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1848 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1851 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1852 /// or one of the other clients provided in our language bindings.
1854 /// Note that if there are any other calls to this function waiting on lock(s) this may return
1855 /// without doing any work. All available events that need handling will be handled before the
1856 /// other calls return.
1858 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1859 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1860 /// [`send_data`]: SocketDescriptor::send_data
1861 pub fn process_events(&self) {
1862 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
1863 // If we're not the first event processor to get here, just return early, the increment
1864 // we just did will be treated as "go around again" at the end.
1869 self.update_gossip_backlogged();
1870 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
1872 let mut peers_to_disconnect = HashMap::new();
1873 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1874 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1877 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1878 // buffer by doing things like announcing channels on another node. We should be willing to
1879 // drop optional-ish messages when send buffers get full!
1881 let peers_lock = self.peers.read().unwrap();
1882 let peers = &*peers_lock;
1883 macro_rules! get_peer_for_forwarding {
1884 ($node_id: expr) => {
1886 if peers_to_disconnect.get($node_id).is_some() {
1887 // If we've "disconnected" this peer, do not send to it.
1890 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1891 match descriptor_opt {
1892 Some(descriptor) => match peers.get(&descriptor) {
1893 Some(peer_mutex) => {
1894 let peer_lock = peer_mutex.lock().unwrap();
1895 if !peer_lock.handshake_complete() {
1901 debug_assert!(false, "Inconsistent peers set state!");
1912 for event in events_generated.drain(..) {
1914 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1915 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1916 log_pubkey!(node_id),
1917 log_bytes!(msg.temporary_channel_id));
1918 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1920 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
1921 log_debug!(self.logger, "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
1922 log_pubkey!(node_id),
1923 log_bytes!(msg.temporary_channel_id));
1924 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1926 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1927 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1928 log_pubkey!(node_id),
1929 log_bytes!(msg.temporary_channel_id));
1930 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1932 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
1933 log_debug!(self.logger, "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}",
1934 log_pubkey!(node_id),
1935 log_bytes!(msg.temporary_channel_id));
1936 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1938 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1939 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1940 log_pubkey!(node_id),
1941 log_bytes!(msg.temporary_channel_id),
1942 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1943 // TODO: If the peer is gone we should generate a DiscardFunding event
1944 // indicating to the wallet that they should just throw away this funding transaction
1945 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1947 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1948 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1949 log_pubkey!(node_id),
1950 log_bytes!(msg.channel_id));
1951 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1953 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1954 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1955 log_pubkey!(node_id),
1956 log_bytes!(msg.channel_id));
1957 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1959 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
1960 log_debug!(self.logger, "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
1961 log_pubkey!(node_id),
1962 log_bytes!(msg.channel_id));
1963 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1965 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
1966 log_debug!(self.logger, "Handling SendTxAddOutput event in peer_handler for node {} for channel {}",
1967 log_pubkey!(node_id),
1968 log_bytes!(msg.channel_id));
1969 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1971 MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => {
1972 log_debug!(self.logger, "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
1973 log_pubkey!(node_id),
1974 log_bytes!(msg.channel_id));
1975 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1977 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
1978 log_debug!(self.logger, "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
1979 log_pubkey!(node_id),
1980 log_bytes!(msg.channel_id));
1981 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1983 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
1984 log_debug!(self.logger, "Handling SendTxComplete event in peer_handler for node {} for channel {}",
1985 log_pubkey!(node_id),
1986 log_bytes!(msg.channel_id));
1987 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1989 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
1990 log_debug!(self.logger, "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
1991 log_pubkey!(node_id),
1992 log_bytes!(msg.channel_id));
1993 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1995 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
1996 log_debug!(self.logger, "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
1997 log_pubkey!(node_id),
1998 log_bytes!(msg.channel_id));
1999 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2001 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2002 log_debug!(self.logger, "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2003 log_pubkey!(node_id),
2004 log_bytes!(msg.channel_id));
2005 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2007 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2008 log_debug!(self.logger, "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2009 log_pubkey!(node_id),
2010 log_bytes!(msg.channel_id));
2011 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2013 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2014 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2015 log_pubkey!(node_id),
2016 log_bytes!(msg.channel_id));
2017 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2019 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 } } => {
2020 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
2021 log_pubkey!(node_id),
2022 update_add_htlcs.len(),
2023 update_fulfill_htlcs.len(),
2024 update_fail_htlcs.len(),
2025 log_bytes!(commitment_signed.channel_id));
2026 let mut peer = get_peer_for_forwarding!(node_id);
2027 for msg in update_add_htlcs {
2028 self.enqueue_message(&mut *peer, msg);
2030 for msg in update_fulfill_htlcs {
2031 self.enqueue_message(&mut *peer, msg);
2033 for msg in update_fail_htlcs {
2034 self.enqueue_message(&mut *peer, msg);
2036 for msg in update_fail_malformed_htlcs {
2037 self.enqueue_message(&mut *peer, msg);
2039 if let &Some(ref msg) = update_fee {
2040 self.enqueue_message(&mut *peer, msg);
2042 self.enqueue_message(&mut *peer, commitment_signed);
2044 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2045 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2046 log_pubkey!(node_id),
2047 log_bytes!(msg.channel_id));
2048 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2050 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2051 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2052 log_pubkey!(node_id),
2053 log_bytes!(msg.channel_id));
2054 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2056 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2057 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
2058 log_pubkey!(node_id),
2059 log_bytes!(msg.channel_id));
2060 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2062 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2063 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2064 log_pubkey!(node_id),
2065 log_bytes!(msg.channel_id));
2066 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2068 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2069 log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2070 log_pubkey!(node_id),
2071 msg.contents.short_channel_id);
2072 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2073 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2075 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2076 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2077 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2078 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2079 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2082 if let Some(msg) = update_msg {
2083 match self.message_handler.route_handler.handle_channel_update(&msg) {
2084 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2085 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2090 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2091 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2092 match self.message_handler.route_handler.handle_channel_update(&msg) {
2093 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2094 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2098 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2099 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2100 match self.message_handler.route_handler.handle_node_announcement(&msg) {
2101 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2102 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2106 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2107 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2108 log_pubkey!(node_id), msg.contents.short_channel_id);
2109 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2111 MessageSendEvent::HandleError { node_id, action } => {
2113 msgs::ErrorAction::DisconnectPeer { msg } => {
2114 if let Some(msg) = msg.as_ref() {
2115 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2116 log_pubkey!(node_id), msg.data);
2118 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2119 log_pubkey!(node_id));
2121 // We do not have the peers write lock, so we just store that we're
2122 // about to disconenct the peer and do it after we finish
2123 // processing most messages.
2124 let msg = msg.map(|msg| wire::Message::<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2125 peers_to_disconnect.insert(node_id, msg);
2127 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2128 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2129 log_pubkey!(node_id), msg.data);
2130 // We do not have the peers write lock, so we just store that we're
2131 // about to disconenct the peer and do it after we finish
2132 // processing most messages.
2133 peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2135 msgs::ErrorAction::IgnoreAndLog(level) => {
2136 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2138 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2139 msgs::ErrorAction::IgnoreError => {
2140 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2142 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2143 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2144 log_pubkey!(node_id),
2146 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2148 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2149 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2150 log_pubkey!(node_id),
2152 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2156 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2157 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2159 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2160 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2162 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2163 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
2164 log_pubkey!(node_id),
2165 msg.short_channel_ids.len(),
2167 msg.number_of_blocks,
2169 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2171 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2172 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2177 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2178 if peers_to_disconnect.get(&node_id).is_some() { continue; }
2179 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2182 for (descriptor, peer_mutex) in peers.iter() {
2183 let mut peer = peer_mutex.lock().unwrap();
2184 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2185 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2188 if !peers_to_disconnect.is_empty() {
2189 let mut peers_lock = self.peers.write().unwrap();
2190 let peers = &mut *peers_lock;
2191 for (node_id, msg) in peers_to_disconnect.drain() {
2192 // Note that since we are holding the peers *write* lock we can
2193 // remove from node_id_to_descriptor immediately (as no other
2194 // thread can be holding the peer lock if we have the global write
2197 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2198 if let Some(mut descriptor) = descriptor_opt {
2199 if let Some(peer_mutex) = peers.remove(&descriptor) {
2200 let mut peer = peer_mutex.lock().unwrap();
2201 if let Some(msg) = msg {
2202 self.enqueue_message(&mut *peer, &msg);
2203 // This isn't guaranteed to work, but if there is enough free
2204 // room in the send buffer, put the error message there...
2205 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2207 self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2208 } else { debug_assert!(false, "Missing connection for peer"); }
2213 if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2214 // If another thread incremented the state while we were running we should go
2215 // around again, but only once.
2216 self.event_processing_state.store(1, Ordering::Release);
2223 /// Indicates that the given socket descriptor's connection is now closed.
2224 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2225 self.disconnect_event_internal(descriptor);
2228 fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2229 if !peer.handshake_complete() {
2230 log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2231 descriptor.disconnect_socket();
2235 debug_assert!(peer.their_node_id.is_some());
2236 if let Some((node_id, _)) = peer.their_node_id {
2237 log_trace!(self.logger, "Disconnecting peer with id {} due to {}", node_id, reason);
2238 self.message_handler.chan_handler.peer_disconnected(&node_id);
2239 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2241 descriptor.disconnect_socket();
2244 fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2245 let mut peers = self.peers.write().unwrap();
2246 let peer_option = peers.remove(descriptor);
2249 // This is most likely a simple race condition where the user found that the socket
2250 // was disconnected, then we told the user to `disconnect_socket()`, then they
2251 // called this method. Either way we're disconnected, return.
2253 Some(peer_lock) => {
2254 let peer = peer_lock.lock().unwrap();
2255 if let Some((node_id, _)) = peer.their_node_id {
2256 log_trace!(self.logger, "Handling disconnection of peer {}", log_pubkey!(node_id));
2257 let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2258 debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2259 if !peer.handshake_complete() { return; }
2260 self.message_handler.chan_handler.peer_disconnected(&node_id);
2261 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2267 /// Disconnect a peer given its node id.
2269 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2270 /// peer. Thus, be very careful about reentrancy issues.
2272 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2273 pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2274 let mut peers_lock = self.peers.write().unwrap();
2275 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2276 let peer_opt = peers_lock.remove(&descriptor);
2277 if let Some(peer_mutex) = peer_opt {
2278 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2279 } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2283 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2284 /// an indication that TCP sockets have stalled even if we weren't around to time them out
2285 /// using regular ping/pongs.
2286 pub fn disconnect_all_peers(&self) {
2287 let mut peers_lock = self.peers.write().unwrap();
2288 self.node_id_to_descriptor.lock().unwrap().clear();
2289 let peers = &mut *peers_lock;
2290 for (descriptor, peer_mutex) in peers.drain() {
2291 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2295 /// This is called when we're blocked on sending additional gossip messages until we receive a
2296 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2297 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2298 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2299 if peer.awaiting_pong_timer_tick_intervals == 0 {
2300 peer.awaiting_pong_timer_tick_intervals = -1;
2301 let ping = msgs::Ping {
2305 self.enqueue_message(peer, &ping);
2309 /// Send pings to each peer and disconnect those which did not respond to the last round of
2312 /// This may be called on any timescale you want, however, roughly once every ten seconds is
2313 /// preferred. The call rate determines both how often we send a ping to our peers and how much
2314 /// time they have to respond before we disconnect them.
2316 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2319 /// [`send_data`]: SocketDescriptor::send_data
2320 pub fn timer_tick_occurred(&self) {
2321 let mut descriptors_needing_disconnect = Vec::new();
2323 let peers_lock = self.peers.read().unwrap();
2325 self.update_gossip_backlogged();
2326 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2328 for (descriptor, peer_mutex) in peers_lock.iter() {
2329 let mut peer = peer_mutex.lock().unwrap();
2330 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2332 if !peer.handshake_complete() {
2333 // The peer needs to complete its handshake before we can exchange messages. We
2334 // give peers one timer tick to complete handshake, reusing
2335 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2336 // for handshake completion.
2337 if peer.awaiting_pong_timer_tick_intervals != 0 {
2338 descriptors_needing_disconnect.push(descriptor.clone());
2340 peer.awaiting_pong_timer_tick_intervals = 1;
2344 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2345 debug_assert!(peer.their_node_id.is_some());
2347 loop { // Used as a `goto` to skip writing a Ping message.
2348 if peer.awaiting_pong_timer_tick_intervals == -1 {
2349 // Magic value set in `maybe_send_extra_ping`.
2350 peer.awaiting_pong_timer_tick_intervals = 1;
2351 peer.received_message_since_timer_tick = false;
2355 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2356 || peer.awaiting_pong_timer_tick_intervals as u64 >
2357 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2359 descriptors_needing_disconnect.push(descriptor.clone());
2362 peer.received_message_since_timer_tick = false;
2364 if peer.awaiting_pong_timer_tick_intervals > 0 {
2365 peer.awaiting_pong_timer_tick_intervals += 1;
2369 peer.awaiting_pong_timer_tick_intervals = 1;
2370 let ping = msgs::Ping {
2374 self.enqueue_message(&mut *peer, &ping);
2377 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2381 if !descriptors_needing_disconnect.is_empty() {
2383 let mut peers_lock = self.peers.write().unwrap();
2384 for descriptor in descriptors_needing_disconnect {
2385 if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2386 let peer = peer_mutex.lock().unwrap();
2387 if let Some((node_id, _)) = peer.their_node_id {
2388 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2390 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2398 // Messages of up to 64KB should never end up more than half full with addresses, as that would
2399 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2400 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2402 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
2405 // ...by failing to compile if the number of addresses that would be half of a message is
2406 // smaller than 100:
2407 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2409 /// Generates a signed node_announcement from the given arguments, sending it to all connected
2410 /// peers. Note that peers will likely ignore this message unless we have at least one public
2411 /// channel which has at least six confirmations on-chain.
2413 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2414 /// node to humans. They carry no in-protocol meaning.
2416 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2417 /// accepts incoming connections. These will be included in the node_announcement, publicly
2418 /// tying these addresses together and to this node. If you wish to preserve user privacy,
2419 /// addresses should likely contain only Tor Onion addresses.
2421 /// Panics if `addresses` is absurdly large (more than 100).
2423 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2424 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
2425 if addresses.len() > 100 {
2426 panic!("More than half the message size was taken up by public addresses!");
2429 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2430 // addresses be sorted for future compatibility.
2431 addresses.sort_by_key(|addr| addr.get_id());
2433 let features = self.message_handler.chan_handler.provided_node_features()
2434 | self.message_handler.route_handler.provided_node_features()
2435 | self.message_handler.onion_message_handler.provided_node_features()
2436 | self.message_handler.custom_message_handler.provided_node_features();
2437 let announcement = msgs::UnsignedNodeAnnouncement {
2439 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2440 node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2442 alias: NodeAlias(alias),
2444 excess_address_data: Vec::new(),
2445 excess_data: Vec::new(),
2447 let node_announce_sig = match self.node_signer.sign_gossip_message(
2448 msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2452 log_error!(self.logger, "Failed to generate signature for node_announcement");
2457 let msg = msgs::NodeAnnouncement {
2458 signature: node_announce_sig,
2459 contents: announcement
2462 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2463 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2464 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2468 fn is_gossip_msg(type_id: u16) -> bool {
2470 msgs::ChannelAnnouncement::TYPE |
2471 msgs::ChannelUpdate::TYPE |
2472 msgs::NodeAnnouncement::TYPE |
2473 msgs::QueryChannelRange::TYPE |
2474 msgs::ReplyChannelRange::TYPE |
2475 msgs::QueryShortChannelIds::TYPE |
2476 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2483 use crate::sign::{NodeSigner, Recipient};
2486 use crate::ln::features::{InitFeatures, NodeFeatures};
2487 use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2488 use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2489 use crate::ln::{msgs, wire};
2490 use crate::ln::msgs::{LightningError, NetAddress};
2491 use crate::util::test_utils;
2493 use bitcoin::Network;
2494 use bitcoin::blockdata::constants::ChainHash;
2495 use bitcoin::secp256k1::{PublicKey, SecretKey};
2497 use crate::prelude::*;
2498 use crate::sync::{Arc, Mutex};
2499 use core::convert::Infallible;
2500 use core::sync::atomic::{AtomicBool, Ordering};
2503 struct FileDescriptor {
2505 outbound_data: Arc<Mutex<Vec<u8>>>,
2506 disconnect: Arc<AtomicBool>,
2508 impl PartialEq for FileDescriptor {
2509 fn eq(&self, other: &Self) -> bool {
2513 impl Eq for FileDescriptor { }
2514 impl core::hash::Hash for FileDescriptor {
2515 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2516 self.fd.hash(hasher)
2520 impl SocketDescriptor for FileDescriptor {
2521 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2522 self.outbound_data.lock().unwrap().extend_from_slice(data);
2526 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2529 struct PeerManagerCfg {
2530 chan_handler: test_utils::TestChannelMessageHandler,
2531 routing_handler: test_utils::TestRoutingMessageHandler,
2532 custom_handler: TestCustomMessageHandler,
2533 logger: test_utils::TestLogger,
2534 node_signer: test_utils::TestNodeSigner,
2537 struct TestCustomMessageHandler {
2538 features: InitFeatures,
2541 impl wire::CustomMessageReader for TestCustomMessageHandler {
2542 type CustomMessage = Infallible;
2543 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2548 impl CustomMessageHandler for TestCustomMessageHandler {
2549 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2553 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2555 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2557 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2558 self.features.clone()
2562 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2563 let mut cfgs = Vec::new();
2564 for i in 0..peer_count {
2565 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2567 let mut feature_bits = vec![0u8; 33];
2568 feature_bits[32] = 0b00000001;
2569 InitFeatures::from_le_bytes(feature_bits)
2573 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2574 logger: test_utils::TestLogger::new(),
2575 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2576 custom_handler: TestCustomMessageHandler { features },
2577 node_signer: test_utils::TestNodeSigner::new(node_secret),
2585 fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2586 let mut cfgs = Vec::new();
2587 for i in 0..peer_count {
2588 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2590 let mut feature_bits = vec![0u8; 33 + i + 1];
2591 feature_bits[33 + i] = 0b00000001;
2592 InitFeatures::from_le_bytes(feature_bits)
2596 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2597 logger: test_utils::TestLogger::new(),
2598 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2599 custom_handler: TestCustomMessageHandler { features },
2600 node_signer: test_utils::TestNodeSigner::new(node_secret),
2608 fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2609 let mut cfgs = Vec::new();
2610 for i in 0..peer_count {
2611 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2612 let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2613 let network = ChainHash::from(&[i as u8; 32][..]);
2616 chan_handler: test_utils::TestChannelMessageHandler::new(network),
2617 logger: test_utils::TestLogger::new(),
2618 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2619 custom_handler: TestCustomMessageHandler { features },
2620 node_signer: test_utils::TestNodeSigner::new(node_secret),
2628 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>> {
2629 let mut peers = Vec::new();
2630 for i in 0..peer_count {
2631 let ephemeral_bytes = [i as u8; 32];
2632 let msg_handler = MessageHandler {
2633 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2634 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2636 let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2643 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) {
2644 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2645 let mut fd_a = FileDescriptor {
2646 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2647 disconnect: Arc::new(AtomicBool::new(false)),
2649 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2650 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2651 let mut fd_b = FileDescriptor {
2652 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2653 disconnect: Arc::new(AtomicBool::new(false)),
2655 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2656 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2657 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2658 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2659 peer_a.process_events();
2661 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2662 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2664 peer_b.process_events();
2665 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2666 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2668 peer_a.process_events();
2669 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2670 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2672 assert!(peer_a.get_peer_node_ids().contains(&(id_b, Some(addr_b))));
2673 assert!(peer_b.get_peer_node_ids().contains(&(id_a, Some(addr_a))));
2675 (fd_a.clone(), fd_b.clone())
2679 #[cfg(feature = "std")]
2680 fn fuzz_threaded_connections() {
2681 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2682 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2683 // with our internal map consistency, and is a generally good smoke test of disconnection.
2684 let cfgs = Arc::new(create_peermgr_cfgs(2));
2685 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2686 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2688 let start_time = std::time::Instant::now();
2689 macro_rules! spawn_thread { ($id: expr) => { {
2690 let peers = Arc::clone(&peers);
2691 let cfgs = Arc::clone(&cfgs);
2692 std::thread::spawn(move || {
2694 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2695 let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2696 let mut fd_a = FileDescriptor {
2697 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2698 disconnect: Arc::new(AtomicBool::new(false)),
2700 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2701 let mut fd_b = FileDescriptor {
2702 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2703 disconnect: Arc::new(AtomicBool::new(false)),
2705 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2706 let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2707 peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2708 if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2710 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2711 peers[0].process_events();
2712 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2713 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2714 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2716 peers[1].process_events();
2717 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2718 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2719 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2721 cfgs[0].chan_handler.pending_events.lock().unwrap()
2722 .push(crate::events::MessageSendEvent::SendShutdown {
2723 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2724 msg: msgs::Shutdown {
2725 channel_id: [0; 32],
2726 scriptpubkey: bitcoin::Script::new(),
2729 cfgs[1].chan_handler.pending_events.lock().unwrap()
2730 .push(crate::events::MessageSendEvent::SendShutdown {
2731 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2732 msg: msgs::Shutdown {
2733 channel_id: [0; 32],
2734 scriptpubkey: bitcoin::Script::new(),
2739 peers[0].timer_tick_occurred();
2740 peers[1].timer_tick_occurred();
2744 peers[0].socket_disconnected(&fd_a);
2745 peers[1].socket_disconnected(&fd_b);
2747 std::thread::sleep(std::time::Duration::from_micros(1));
2751 let thrd_a = spawn_thread!(1);
2752 let thrd_b = spawn_thread!(2);
2754 thrd_a.join().unwrap();
2755 thrd_b.join().unwrap();
2759 fn test_feature_incompatible_peers() {
2760 let cfgs = create_peermgr_cfgs(2);
2761 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2763 let peers = create_network(2, &cfgs);
2764 let incompatible_peers = create_network(2, &incompatible_cfgs);
2765 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2766 for (peer_a, peer_b) in peer_pairs.iter() {
2767 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2768 let mut fd_a = FileDescriptor {
2769 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2770 disconnect: Arc::new(AtomicBool::new(false)),
2772 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2773 let mut fd_b = FileDescriptor {
2774 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2775 disconnect: Arc::new(AtomicBool::new(false)),
2777 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2778 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2779 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2780 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2781 peer_a.process_events();
2783 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2784 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2786 peer_b.process_events();
2787 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2789 // Should fail because of unknown required features
2790 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2795 fn test_chain_incompatible_peers() {
2796 let cfgs = create_peermgr_cfgs(2);
2797 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
2799 let peers = create_network(2, &cfgs);
2800 let incompatible_peers = create_network(2, &incompatible_cfgs);
2801 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2802 for (peer_a, peer_b) in peer_pairs.iter() {
2803 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2804 let mut fd_a = FileDescriptor {
2805 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2806 disconnect: Arc::new(AtomicBool::new(false)),
2808 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2809 let mut fd_b = FileDescriptor {
2810 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2811 disconnect: Arc::new(AtomicBool::new(false)),
2813 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2814 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2815 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2816 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2817 peer_a.process_events();
2819 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2820 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2822 peer_b.process_events();
2823 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2825 // Should fail because of incompatible chains
2826 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2831 fn test_disconnect_peer() {
2832 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2833 // push a DisconnectPeer event to remove the node flagged by id
2834 let cfgs = create_peermgr_cfgs(2);
2835 let peers = create_network(2, &cfgs);
2836 establish_connection(&peers[0], &peers[1]);
2837 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2839 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2840 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2842 action: msgs::ErrorAction::DisconnectPeer { msg: None },
2845 peers[0].process_events();
2846 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2850 fn test_send_simple_msg() {
2851 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2852 // push a message from one peer to another.
2853 let cfgs = create_peermgr_cfgs(2);
2854 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2855 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2856 let mut peers = create_network(2, &cfgs);
2857 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2858 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2860 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2862 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2863 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2864 node_id: their_id, msg: msg.clone()
2866 peers[0].message_handler.chan_handler = &a_chan_handler;
2868 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2869 peers[1].message_handler.chan_handler = &b_chan_handler;
2871 peers[0].process_events();
2873 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2874 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2878 fn test_non_init_first_msg() {
2879 // Simple test of the first message received over a connection being something other than
2880 // Init. This results in an immediate disconnection, which previously included a spurious
2881 // peer_disconnected event handed to event handlers (which would panic in
2882 // `TestChannelMessageHandler` here).
2883 let cfgs = create_peermgr_cfgs(2);
2884 let peers = create_network(2, &cfgs);
2886 let mut fd_dup = FileDescriptor {
2887 fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2888 disconnect: Arc::new(AtomicBool::new(false)),
2890 let addr_dup = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1003};
2891 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
2892 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
2894 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
2895 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
2896 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
2897 peers[0].process_events();
2899 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
2900 let (act_three, _) =
2901 dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
2902 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
2904 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
2905 let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg);
2906 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
2910 fn test_disconnect_all_peer() {
2911 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2912 // then calls disconnect_all_peers
2913 let cfgs = create_peermgr_cfgs(2);
2914 let peers = create_network(2, &cfgs);
2915 establish_connection(&peers[0], &peers[1]);
2916 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2918 peers[0].disconnect_all_peers();
2919 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2923 fn test_timer_tick_occurred() {
2924 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2925 let cfgs = create_peermgr_cfgs(2);
2926 let peers = create_network(2, &cfgs);
2927 establish_connection(&peers[0], &peers[1]);
2928 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2930 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2931 peers[0].timer_tick_occurred();
2932 peers[0].process_events();
2933 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2935 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2936 peers[0].timer_tick_occurred();
2937 peers[0].process_events();
2938 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2942 fn test_do_attempt_write_data() {
2943 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2944 let cfgs = create_peermgr_cfgs(2);
2945 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2946 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2947 let peers = create_network(2, &cfgs);
2949 // By calling establish_connect, we trigger do_attempt_write_data between
2950 // the peers. Previously this function would mistakenly enter an infinite loop
2951 // when there were more channel messages available than could fit into a peer's
2952 // buffer. This issue would now be detected by this test (because we use custom
2953 // RoutingMessageHandlers that intentionally return more channel messages
2954 // than can fit into a peer's buffer).
2955 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2957 // Make each peer to read the messages that the other peer just wrote to them. Note that
2958 // due to the max-message-before-ping limits this may take a few iterations to complete.
2959 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2960 peers[1].process_events();
2961 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2962 assert!(!a_read_data.is_empty());
2964 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2965 peers[0].process_events();
2967 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2968 assert!(!b_read_data.is_empty());
2969 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2971 peers[0].process_events();
2972 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2975 // Check that each peer has received the expected number of channel updates and channel
2977 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2978 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2979 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2980 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2984 fn test_handshake_timeout() {
2985 // Tests that we time out a peer still waiting on handshake completion after a full timer
2987 let cfgs = create_peermgr_cfgs(2);
2988 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2989 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2990 let peers = create_network(2, &cfgs);
2992 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2993 let mut fd_a = FileDescriptor {
2994 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2995 disconnect: Arc::new(AtomicBool::new(false)),
2997 let mut fd_b = FileDescriptor {
2998 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2999 disconnect: Arc::new(AtomicBool::new(false)),
3001 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3002 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3004 // If we get a single timer tick before completion, that's fine
3005 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3006 peers[0].timer_tick_occurred();
3007 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3009 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3010 peers[0].process_events();
3011 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3012 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3013 peers[1].process_events();
3015 // ...but if we get a second timer tick, we should disconnect the peer
3016 peers[0].timer_tick_occurred();
3017 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3019 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3020 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3024 fn test_filter_addresses(){
3025 // Tests the filter_addresses function.
3028 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
3029 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3030 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
3031 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3032 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
3033 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3036 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
3037 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3038 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
3039 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3040 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
3041 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3044 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
3045 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3046 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
3047 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3048 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
3049 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3052 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
3053 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3054 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
3055 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3056 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
3057 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3060 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
3061 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3062 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
3063 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3064 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
3065 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3068 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
3069 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3070 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
3071 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3072 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
3073 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3076 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
3077 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3078 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
3079 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3080 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
3081 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3083 // For (192.88.99/24)
3084 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
3085 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3086 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
3087 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3088 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
3089 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3091 // For other IPv4 addresses
3092 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
3093 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3094 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
3095 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3096 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
3097 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3100 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3101 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3102 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3103 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3104 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3105 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3107 // For other IPv6 addresses
3108 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3109 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3110 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3111 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3112 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3113 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3116 assert_eq!(filter_addresses(None), None);
3120 #[cfg(feature = "std")]
3121 fn test_process_events_multithreaded() {
3122 use std::time::{Duration, Instant};
3123 // Test that `process_events` getting called on multiple threads doesn't generate too many
3125 // Each time `process_events` goes around the loop we call
3126 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3127 // Because the loop should go around once more after a call which fails to take the
3128 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3129 // should never observe there having been more than 2 loop iterations.
3130 // Further, because the last thread to exit will call `process_events` before returning, we
3131 // should always have at least one count at the end.
3132 let cfg = Arc::new(create_peermgr_cfgs(1));
3133 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3134 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3136 let exit_flag = Arc::new(AtomicBool::new(false));
3137 macro_rules! spawn_thread { () => { {
3138 let thread_cfg = Arc::clone(&cfg);
3139 let thread_peer = Arc::clone(&peer);
3140 let thread_exit = Arc::clone(&exit_flag);
3141 std::thread::spawn(move || {
3142 while !thread_exit.load(Ordering::Acquire) {
3143 thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3144 thread_peer.process_events();
3145 std::thread::sleep(Duration::from_micros(1));
3150 let thread_a = spawn_thread!();
3151 let thread_b = spawn_thread!();
3152 let thread_c = spawn_thread!();
3154 let start_time = Instant::now();
3155 while start_time.elapsed() < Duration::from_millis(100) {
3156 let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3158 std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3161 exit_flag.store(true, Ordering::Release);
3162 thread_a.join().unwrap();
3163 thread_b.join().unwrap();
3164 thread_c.join().unwrap();
3165 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);