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::{CustomOnionMessageContents, CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
32 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, NodeAlias};
33 use crate::util::atomic_counter::AtomicCounter;
34 use crate::util::logger::Logger;
36 use crate::prelude::*;
38 use alloc::collections::LinkedList;
39 use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock};
40 use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering};
41 use core::{cmp, hash, fmt, mem};
43 use core::convert::Infallible;
44 #[cfg(feature = "std")] use std::error;
46 use bitcoin::hashes::sha256::Hash as Sha256;
47 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
48 use bitcoin::hashes::{HashEngine, Hash};
50 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
52 /// [BOLT 1] specifies a custom message type range for use with experimental or application-specific
53 /// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the
54 /// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler.
56 /// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
57 /// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message
58 pub trait CustomMessageHandler: wire::CustomMessageReader {
59 /// Handles the given message sent from `sender_node_id`, possibly producing messages for
60 /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`]
62 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
64 /// Returns the list of pending messages that were generated by the handler, clearing the list
65 /// in the process. Each message is paired with the node id of the intended recipient. If no
66 /// connection to the node exists, then the message is simply not sent.
67 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
69 /// Gets the node feature flags which this handler itself supports. All available handlers are
70 /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
71 /// which are broadcasted in our [`NodeAnnouncement`] message.
73 /// [`NodeAnnouncement`]: crate::ln::msgs::NodeAnnouncement
74 fn provided_node_features(&self) -> NodeFeatures;
76 /// Gets the init feature flags which should be sent to the given peer. All available handlers
77 /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
78 /// which are sent in our [`Init`] message.
80 /// [`Init`]: crate::ln::msgs::Init
81 fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
84 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
85 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
86 pub struct IgnoringMessageHandler{}
87 impl MessageSendEventsProvider for IgnoringMessageHandler {
88 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
90 impl RoutingMessageHandler for IgnoringMessageHandler {
91 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
92 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
93 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
94 fn get_next_channel_announcement(&self, _starting_point: u64) ->
95 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
96 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
97 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
98 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
99 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
100 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
101 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
102 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
103 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
104 InitFeatures::empty()
106 fn processing_queue_high(&self) -> bool { false }
108 impl OnionMessageProvider for IgnoringMessageHandler {
109 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
111 impl OnionMessageHandler for IgnoringMessageHandler {
112 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
113 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
114 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
115 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
116 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
117 InitFeatures::empty()
120 impl CustomOnionMessageHandler for IgnoringMessageHandler {
121 type CustomMessage = Infallible;
122 fn handle_custom_message(&self, _msg: Infallible) {
123 // Since we always return `None` in the read the handle method should never be called.
126 fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
131 impl CustomOnionMessageContents for Infallible {
132 fn tlv_type(&self) -> u64 { unreachable!(); }
135 impl Deref for IgnoringMessageHandler {
136 type Target = IgnoringMessageHandler;
137 fn deref(&self) -> &Self { self }
140 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
141 // method that takes self for it.
142 impl wire::Type for Infallible {
143 fn type_id(&self) -> u16 {
147 impl Writeable for Infallible {
148 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
153 impl wire::CustomMessageReader for IgnoringMessageHandler {
154 type CustomMessage = Infallible;
155 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
160 impl CustomMessageHandler for IgnoringMessageHandler {
161 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
162 // Since we always return `None` in the read the handle method should never be called.
166 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
168 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
170 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
171 InitFeatures::empty()
175 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
176 /// You can provide one of these as the route_handler in a MessageHandler.
177 pub struct ErroringMessageHandler {
178 message_queue: Mutex<Vec<MessageSendEvent>>
180 impl ErroringMessageHandler {
181 /// Constructs a new ErroringMessageHandler
182 pub fn new() -> Self {
183 Self { message_queue: Mutex::new(Vec::new()) }
185 fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
186 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
187 action: msgs::ErrorAction::SendErrorMessage {
188 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
190 node_id: node_id.clone(),
194 impl MessageSendEventsProvider for ErroringMessageHandler {
195 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
196 let mut res = Vec::new();
197 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
201 impl ChannelMessageHandler for ErroringMessageHandler {
202 // Any messages which are related to a specific channel generate an error message to let the
203 // peer know we don't care about channels.
204 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
205 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
207 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
208 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
210 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
211 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
213 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
214 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
216 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
217 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
219 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
220 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
222 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
223 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
225 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
226 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
228 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
229 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
231 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
232 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
234 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
235 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
237 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
238 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
240 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
241 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
243 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
244 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
246 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
247 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
249 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
250 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
252 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
253 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
254 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
255 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
256 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
257 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
258 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
259 // Set a number of features which various nodes may require to talk to us. It's totally
260 // reasonable to indicate we "support" all kinds of channel features...we just reject all
262 let mut features = InitFeatures::empty();
263 features.set_data_loss_protect_optional();
264 features.set_upfront_shutdown_script_optional();
265 features.set_variable_length_onion_optional();
266 features.set_static_remote_key_optional();
267 features.set_payment_secret_optional();
268 features.set_basic_mpp_optional();
269 features.set_wumbo_optional();
270 features.set_shutdown_any_segwit_optional();
271 features.set_channel_type_optional();
272 features.set_scid_privacy_optional();
273 features.set_zero_conf_optional();
277 fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
278 // We don't enforce any chains upon peer connection for `ErroringMessageHandler` and leave it up
279 // to users of `ErroringMessageHandler` to make decisions on network compatiblility.
280 // There's not really any way to pull in specific networks here, and hardcoding can cause breakages.
284 fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
285 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
288 fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
289 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
292 fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
293 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
296 fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
297 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
300 fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
301 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
304 fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
305 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
308 fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &msgs::TxComplete) {
309 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
312 fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
313 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
316 fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
317 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
320 fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
321 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
324 fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &msgs::TxAbort) {
325 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
329 impl Deref for ErroringMessageHandler {
330 type Target = ErroringMessageHandler;
331 fn deref(&self) -> &Self { self }
334 /// Provides references to trait impls which handle different types of messages.
335 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref, CustomM: Deref> where
336 CM::Target: ChannelMessageHandler,
337 RM::Target: RoutingMessageHandler,
338 OM::Target: OnionMessageHandler,
339 CustomM::Target: CustomMessageHandler,
341 /// A message handler which handles messages specific to channels. Usually this is just a
342 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
344 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
345 pub chan_handler: CM,
346 /// A message handler which handles messages updating our knowledge of the network channel
347 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
349 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
350 pub route_handler: RM,
352 /// A message handler which handles onion messages. This should generally be an
353 /// [`OnionMessenger`], but can also be an [`IgnoringMessageHandler`].
355 /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
356 pub onion_message_handler: OM,
358 /// A message handler which handles custom messages. The only LDK-provided implementation is
359 /// [`IgnoringMessageHandler`].
360 pub custom_message_handler: CustomM,
363 /// Provides an object which can be used to send data to and which uniquely identifies a connection
364 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
365 /// implement Hash to meet the PeerManager API.
367 /// For efficiency, [`Clone`] should be relatively cheap for this type.
369 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
370 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
371 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
372 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
373 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
374 /// to simply use another value which is guaranteed to be globally unique instead.
375 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
376 /// Attempts to send some data from the given slice to the peer.
378 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
379 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
380 /// called and further write attempts may occur until that time.
382 /// If the returned size is smaller than `data.len()`, a
383 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
384 /// written. Additionally, until a `send_data` event completes fully, no further
385 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
386 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
389 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
390 /// (indicating that read events should be paused to prevent DoS in the send buffer),
391 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
392 /// `resume_read` of false carries no meaning, and should not cause any action.
393 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
394 /// Disconnect the socket pointed to by this SocketDescriptor.
396 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
397 /// call (doing so is a noop).
398 fn disconnect_socket(&mut self);
401 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
402 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
405 pub struct PeerHandleError { }
406 impl fmt::Debug for PeerHandleError {
407 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
408 formatter.write_str("Peer Sent Invalid Data")
411 impl fmt::Display for PeerHandleError {
412 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
413 formatter.write_str("Peer Sent Invalid Data")
417 #[cfg(feature = "std")]
418 impl error::Error for PeerHandleError {
419 fn description(&self) -> &str {
420 "Peer Sent Invalid Data"
424 enum InitSyncTracker{
426 ChannelsSyncing(u64),
427 NodesSyncing(NodeId),
430 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
431 /// forwarding gossip messages to peers altogether.
432 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
434 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
435 /// we have fewer than this many messages in the outbound buffer again.
436 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
437 /// refilled as we send bytes.
438 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
439 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
441 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
443 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
444 /// the socket receive buffer before receiving the ping.
446 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
447 /// including any network delays, outbound traffic, or the same for messages from other peers.
449 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
450 /// per connected peer to respond to a ping, as long as they send us at least one message during
451 /// each tick, ensuring we aren't actually just disconnected.
452 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
455 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
456 /// two connected peers, assuming most LDK-running systems have at least two cores.
457 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
459 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
460 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
461 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
462 /// process before the next ping.
464 /// Note that we continue responding to other messages even after we've sent this many messages, so
465 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
466 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
467 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
470 channel_encryptor: PeerChannelEncryptor,
471 /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
472 /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
473 their_node_id: Option<(PublicKey, NodeId)>,
474 /// The features provided in the peer's [`msgs::Init`] message.
476 /// This is set only after we've processed the [`msgs::Init`] message and called relevant
477 /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
478 /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
480 their_features: Option<InitFeatures>,
481 their_net_address: Option<NetAddress>,
483 pending_outbound_buffer: LinkedList<Vec<u8>>,
484 pending_outbound_buffer_first_msg_offset: usize,
485 /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
486 /// prioritize channel messages over them.
488 /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
489 gossip_broadcast_buffer: LinkedList<Vec<u8>>,
490 awaiting_write_event: bool,
492 pending_read_buffer: Vec<u8>,
493 pending_read_buffer_pos: usize,
494 pending_read_is_header: bool,
496 sync_status: InitSyncTracker,
498 msgs_sent_since_pong: usize,
499 awaiting_pong_timer_tick_intervals: i64,
500 received_message_since_timer_tick: bool,
501 sent_gossip_timestamp_filter: bool,
503 /// Indicates we've received a `channel_announcement` since the last time we had
504 /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
505 /// `channel_announcement` at all - we set this unconditionally but unset it every time we
506 /// check if we're gossip-processing-backlogged).
507 received_channel_announce_since_backlogged: bool,
509 inbound_connection: bool,
513 /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
514 /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
516 fn handshake_complete(&self) -> bool {
517 self.their_features.is_some()
520 /// Returns true if the channel announcements/updates for the given channel should be
521 /// forwarded to this peer.
522 /// If we are sending our routing table to this peer and we have not yet sent channel
523 /// announcements/updates for the given channel_id then we will send it when we get to that
524 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
525 /// sent the old versions, we should send the update, and so return true here.
526 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
527 if !self.handshake_complete() { return false; }
528 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
529 !self.sent_gossip_timestamp_filter {
532 match self.sync_status {
533 InitSyncTracker::NoSyncRequested => true,
534 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
535 InitSyncTracker::NodesSyncing(_) => true,
539 /// Similar to the above, but for node announcements indexed by node_id.
540 fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
541 if !self.handshake_complete() { return false; }
542 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
543 !self.sent_gossip_timestamp_filter {
546 match self.sync_status {
547 InitSyncTracker::NoSyncRequested => true,
548 InitSyncTracker::ChannelsSyncing(_) => false,
549 InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
553 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
554 /// buffer still has space and we don't need to pause reads to get some writes out.
555 fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
556 if !gossip_processing_backlogged {
557 self.received_channel_announce_since_backlogged = false;
559 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
560 (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
563 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
564 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
565 fn should_buffer_gossip_backfill(&self) -> bool {
566 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
567 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
568 && self.handshake_complete()
571 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
572 /// every time the peer's buffer may have been drained.
573 fn should_buffer_onion_message(&self) -> bool {
574 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
575 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
578 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
579 /// buffer. This is checked every time the peer's buffer may have been drained.
580 fn should_buffer_gossip_broadcast(&self) -> bool {
581 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
582 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
585 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
586 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
587 let total_outbound_buffered =
588 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
590 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
591 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
594 fn set_their_node_id(&mut self, node_id: PublicKey) {
595 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
599 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
600 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
601 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
602 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
603 /// issues such as overly long function definitions.
605 /// This is not exported to bindings users as `Arc`s don't make sense in bindings.
606 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, Arc<C>, Arc<L>>>, Arc<SimpleArcOnionMessenger<L>>, Arc<L>, IgnoringMessageHandler, Arc<KeysManager>>;
608 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
609 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
610 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
611 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
612 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
613 /// helps with issues such as long function definitions.
615 /// This is not exported to bindings users as general type aliases don't make sense in bindings.
616 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'l, 'm, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'm, M, T, F, L>, &'f P2PGossipSync<&'g NetworkGraph<&'f L>, &'h C, &'f L>, &'i SimpleRefOnionMessenger<'j, 'k, L>, &'f L, IgnoringMessageHandler, &'c KeysManager>;
619 /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or
620 /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather
621 /// than the full set of bounds on [`PeerManager`] itself.
622 #[allow(missing_docs)]
623 pub trait APeerManager {
624 type Descriptor: SocketDescriptor;
625 type CMT: ChannelMessageHandler + ?Sized;
626 type CM: Deref<Target=Self::CMT>;
627 type RMT: RoutingMessageHandler + ?Sized;
628 type RM: Deref<Target=Self::RMT>;
629 type OMT: OnionMessageHandler + ?Sized;
630 type OM: Deref<Target=Self::OMT>;
631 type LT: Logger + ?Sized;
632 type L: Deref<Target=Self::LT>;
633 type CMHT: CustomMessageHandler + ?Sized;
634 type CMH: Deref<Target=Self::CMHT>;
635 type NST: NodeSigner + ?Sized;
636 type NS: Deref<Target=Self::NST>;
637 /// Gets a reference to the underlying [`PeerManager`].
638 fn as_ref(&self) -> &PeerManager<Self::Descriptor, Self::CM, Self::RM, Self::OM, Self::L, Self::CMH, Self::NS>;
641 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref>
642 APeerManager for PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
643 CM::Target: ChannelMessageHandler,
644 RM::Target: RoutingMessageHandler,
645 OM::Target: OnionMessageHandler,
647 CMH::Target: CustomMessageHandler,
648 NS::Target: NodeSigner,
650 type Descriptor = Descriptor;
651 type CMT = <CM as Deref>::Target;
653 type RMT = <RM as Deref>::Target;
655 type OMT = <OM as Deref>::Target;
657 type LT = <L as Deref>::Target;
659 type CMHT = <CMH as Deref>::Target;
661 type NST = <NS as Deref>::Target;
663 fn as_ref(&self) -> &PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> { self }
666 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
667 /// socket events into messages which it passes on to its [`MessageHandler`].
669 /// Locks are taken internally, so you must never assume that reentrancy from a
670 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
672 /// Calls to [`read_event`] will decode relevant messages and pass them to the
673 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
674 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
675 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
676 /// calls only after previous ones have returned.
678 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
679 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
680 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
681 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
682 /// you're using lightning-net-tokio.
684 /// [`read_event`]: PeerManager::read_event
685 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
686 CM::Target: ChannelMessageHandler,
687 RM::Target: RoutingMessageHandler,
688 OM::Target: OnionMessageHandler,
690 CMH::Target: CustomMessageHandler,
691 NS::Target: NodeSigner {
692 message_handler: MessageHandler<CM, RM, OM, CMH>,
693 /// Connection state for each connected peer - we have an outer read-write lock which is taken
694 /// as read while we're doing processing for a peer and taken write when a peer is being added
697 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
698 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
699 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
700 /// the `MessageHandler`s for a given peer is already guaranteed.
701 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
702 /// Only add to this set when noise completes.
703 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
704 /// lock held. Entries may be added with only the `peers` read lock held (though the
705 /// `Descriptor` value must already exist in `peers`).
706 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
707 /// We can only have one thread processing events at once, but if a second call to
708 /// `process_events` happens while a first call is in progress, one of the two calls needs to
709 /// start from the top to ensure any new messages are also handled.
711 /// Because the event handler calls into user code which may block, we don't want to block a
712 /// second thread waiting for another thread to handle events which is then blocked on user
713 /// code, so we store an atomic counter here:
714 /// * 0 indicates no event processor is running
715 /// * 1 indicates an event processor is running
716 /// * > 1 indicates an event processor is running but needs to start again from the top once
717 /// it finishes as another thread tried to start processing events but returned early.
718 event_processing_state: AtomicI32,
720 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
721 /// value increases strictly since we don't assume access to a time source.
722 last_node_announcement_serial: AtomicU32,
724 ephemeral_key_midstate: Sha256Engine,
726 peer_counter: AtomicCounter,
728 gossip_processing_backlogged: AtomicBool,
729 gossip_processing_backlog_lifted: AtomicBool,
734 secp_ctx: Secp256k1<secp256k1::SignOnly>
737 enum MessageHandlingError {
738 PeerHandleError(PeerHandleError),
739 LightningError(LightningError),
742 impl From<PeerHandleError> for MessageHandlingError {
743 fn from(error: PeerHandleError) -> Self {
744 MessageHandlingError::PeerHandleError(error)
748 impl From<LightningError> for MessageHandlingError {
749 fn from(error: LightningError) -> Self {
750 MessageHandlingError::LightningError(error)
754 macro_rules! encode_msg {
756 let mut buffer = VecWriter(Vec::new());
757 wire::write($msg, &mut buffer).unwrap();
762 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
763 CM::Target: ChannelMessageHandler,
764 OM::Target: OnionMessageHandler,
766 NS::Target: NodeSigner {
767 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
768 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
771 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
772 /// cryptographically secure random bytes.
774 /// `current_time` is used as an always-increasing counter that survives across restarts and is
775 /// incremented irregularly internally. In general it is best to simply use the current UNIX
776 /// timestamp, however if it is not available a persistent counter that increases once per
777 /// minute should suffice.
779 /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
780 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 {
781 Self::new(MessageHandler {
782 chan_handler: channel_message_handler,
783 route_handler: IgnoringMessageHandler{},
784 onion_message_handler,
785 custom_message_handler: IgnoringMessageHandler{},
786 }, current_time, ephemeral_random_data, logger, node_signer)
790 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
791 RM::Target: RoutingMessageHandler,
793 NS::Target: NodeSigner {
794 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
795 /// handler or onion message handler is used and onion and channel messages will be ignored (or
796 /// generate error messages). Note that some other lightning implementations time-out connections
797 /// after some time if no channel is built with the peer.
799 /// `current_time` is used as an always-increasing counter that survives across restarts and is
800 /// incremented irregularly internally. In general it is best to simply use the current UNIX
801 /// timestamp, however if it is not available a persistent counter that increases once per
802 /// minute should suffice.
804 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
805 /// cryptographically secure random bytes.
807 /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
808 pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
809 Self::new(MessageHandler {
810 chan_handler: ErroringMessageHandler::new(),
811 route_handler: routing_message_handler,
812 onion_message_handler: IgnoringMessageHandler{},
813 custom_message_handler: IgnoringMessageHandler{},
814 }, current_time, ephemeral_random_data, logger, node_signer)
818 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
819 /// This works around `format!()` taking a reference to each argument, preventing
820 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
821 /// due to lifetime errors.
822 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
823 impl core::fmt::Display for OptionalFromDebugger<'_> {
824 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
825 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
829 /// A function used to filter out local or private addresses
830 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
831 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
832 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
834 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
835 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
836 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
837 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
838 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
839 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
840 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
841 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
842 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
843 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
844 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
845 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
846 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
847 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
848 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
849 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
850 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
851 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
852 // For remaining addresses
853 Some(NetAddress::IPv6{addr: _, port: _}) => None,
854 Some(..) => ip_address,
859 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
860 CM::Target: ChannelMessageHandler,
861 RM::Target: RoutingMessageHandler,
862 OM::Target: OnionMessageHandler,
864 CMH::Target: CustomMessageHandler,
865 NS::Target: NodeSigner
867 /// Constructs a new `PeerManager` with the given message handlers.
869 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
870 /// cryptographically secure random bytes.
872 /// `current_time` is used as an always-increasing counter that survives across restarts and is
873 /// incremented irregularly internally. In general it is best to simply use the current UNIX
874 /// timestamp, however if it is not available a persistent counter that increases once per
875 /// minute should suffice.
876 pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
877 let mut ephemeral_key_midstate = Sha256::engine();
878 ephemeral_key_midstate.input(ephemeral_random_data);
880 let mut secp_ctx = Secp256k1::signing_only();
881 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
882 secp_ctx.seeded_randomize(&ephemeral_hash);
886 peers: FairRwLock::new(HashMap::new()),
887 node_id_to_descriptor: Mutex::new(HashMap::new()),
888 event_processing_state: AtomicI32::new(0),
889 ephemeral_key_midstate,
890 peer_counter: AtomicCounter::new(),
891 gossip_processing_backlogged: AtomicBool::new(false),
892 gossip_processing_backlog_lifted: AtomicBool::new(false),
893 last_node_announcement_serial: AtomicU32::new(current_time),
900 /// Get a list of tuples mapping from node id to network addresses for peers which have
901 /// completed the initial handshake.
903 /// For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter
904 /// passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial
905 /// handshake has completed and we are sure the remote peer has the private key for the given
908 /// The returned `Option`s will only be `Some` if an address had been previously given via
909 /// [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`].
910 pub fn get_peer_node_ids(&self) -> Vec<(PublicKey, Option<NetAddress>)> {
911 let peers = self.peers.read().unwrap();
912 peers.values().filter_map(|peer_mutex| {
913 let p = peer_mutex.lock().unwrap();
914 if !p.handshake_complete() {
917 Some((p.their_node_id.unwrap().0, p.their_net_address.clone()))
921 fn get_ephemeral_key(&self) -> SecretKey {
922 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
923 let counter = self.peer_counter.get_increment();
924 ephemeral_hash.input(&counter.to_le_bytes());
925 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
928 fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
929 self.message_handler.chan_handler.provided_init_features(their_node_id)
930 | self.message_handler.route_handler.provided_init_features(their_node_id)
931 | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
932 | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
935 /// Indicates a new outbound connection has been established to a node with the given `node_id`
936 /// and an optional remote network address.
938 /// The remote network address adds the option to report a remote IP address back to a connecting
939 /// peer using the init message.
940 /// The user should pass the remote network address of the host they are connected to.
942 /// If an `Err` is returned here you must disconnect the connection immediately.
944 /// Returns a small number of bytes to send to the remote node (currently always 50).
946 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
947 /// [`socket_disconnected`].
949 /// [`socket_disconnected`]: PeerManager::socket_disconnected
950 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
951 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
952 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
953 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
955 let mut peers = self.peers.write().unwrap();
956 match peers.entry(descriptor) {
957 hash_map::Entry::Occupied(_) => {
958 debug_assert!(false, "PeerManager driver duplicated descriptors!");
959 Err(PeerHandleError {})
961 hash_map::Entry::Vacant(e) => {
962 e.insert(Mutex::new(Peer {
963 channel_encryptor: peer_encryptor,
965 their_features: None,
966 their_net_address: remote_network_address,
968 pending_outbound_buffer: LinkedList::new(),
969 pending_outbound_buffer_first_msg_offset: 0,
970 gossip_broadcast_buffer: LinkedList::new(),
971 awaiting_write_event: false,
974 pending_read_buffer_pos: 0,
975 pending_read_is_header: false,
977 sync_status: InitSyncTracker::NoSyncRequested,
979 msgs_sent_since_pong: 0,
980 awaiting_pong_timer_tick_intervals: 0,
981 received_message_since_timer_tick: false,
982 sent_gossip_timestamp_filter: false,
984 received_channel_announce_since_backlogged: false,
985 inbound_connection: false,
992 /// Indicates a new inbound connection has been established to a node with an optional remote
995 /// The remote network address adds the option to report a remote IP address back to a connecting
996 /// peer using the init message.
997 /// The user should pass the remote network address of the host they are connected to.
999 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
1000 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
1001 /// the connection immediately.
1003 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1004 /// [`socket_disconnected`].
1006 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1007 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
1008 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1009 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1011 let mut peers = self.peers.write().unwrap();
1012 match peers.entry(descriptor) {
1013 hash_map::Entry::Occupied(_) => {
1014 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1015 Err(PeerHandleError {})
1017 hash_map::Entry::Vacant(e) => {
1018 e.insert(Mutex::new(Peer {
1019 channel_encryptor: peer_encryptor,
1020 their_node_id: None,
1021 their_features: None,
1022 their_net_address: remote_network_address,
1024 pending_outbound_buffer: LinkedList::new(),
1025 pending_outbound_buffer_first_msg_offset: 0,
1026 gossip_broadcast_buffer: LinkedList::new(),
1027 awaiting_write_event: false,
1029 pending_read_buffer,
1030 pending_read_buffer_pos: 0,
1031 pending_read_is_header: false,
1033 sync_status: InitSyncTracker::NoSyncRequested,
1035 msgs_sent_since_pong: 0,
1036 awaiting_pong_timer_tick_intervals: 0,
1037 received_message_since_timer_tick: false,
1038 sent_gossip_timestamp_filter: false,
1040 received_channel_announce_since_backlogged: false,
1041 inbound_connection: true,
1048 fn peer_should_read(&self, peer: &mut Peer) -> bool {
1049 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1052 fn update_gossip_backlogged(&self) {
1053 let new_state = self.message_handler.route_handler.processing_queue_high();
1054 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1055 if prev_state && !new_state {
1056 self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1060 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1061 let mut have_written = false;
1062 while !peer.awaiting_write_event {
1063 if peer.should_buffer_onion_message() {
1064 if let Some((peer_node_id, _)) = peer.their_node_id {
1065 if let Some(next_onion_message) =
1066 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1067 self.enqueue_message(peer, &next_onion_message);
1071 if peer.should_buffer_gossip_broadcast() {
1072 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1073 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..]));
1076 if peer.should_buffer_gossip_backfill() {
1077 match peer.sync_status {
1078 InitSyncTracker::NoSyncRequested => {},
1079 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1080 if let Some((announce, update_a_option, update_b_option)) =
1081 self.message_handler.route_handler.get_next_channel_announcement(c)
1083 self.enqueue_message(peer, &announce);
1084 if let Some(update_a) = update_a_option {
1085 self.enqueue_message(peer, &update_a);
1087 if let Some(update_b) = update_b_option {
1088 self.enqueue_message(peer, &update_b);
1090 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1092 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1095 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1096 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1097 self.enqueue_message(peer, &msg);
1098 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1100 peer.sync_status = InitSyncTracker::NoSyncRequested;
1103 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1104 InitSyncTracker::NodesSyncing(sync_node_id) => {
1105 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1106 self.enqueue_message(peer, &msg);
1107 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1109 peer.sync_status = InitSyncTracker::NoSyncRequested;
1114 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1115 self.maybe_send_extra_ping(peer);
1118 let should_read = self.peer_should_read(peer);
1119 let next_buff = match peer.pending_outbound_buffer.front() {
1121 if force_one_write && !have_written {
1123 let data_sent = descriptor.send_data(&[], should_read);
1124 debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1132 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1133 let data_sent = descriptor.send_data(pending, should_read);
1134 have_written = true;
1135 peer.pending_outbound_buffer_first_msg_offset += data_sent;
1136 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1137 peer.pending_outbound_buffer_first_msg_offset = 0;
1138 peer.pending_outbound_buffer.pop_front();
1140 peer.awaiting_write_event = true;
1145 /// Indicates that there is room to write data to the given socket descriptor.
1147 /// May return an Err to indicate that the connection should be closed.
1149 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1150 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1151 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1152 /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1155 /// [`send_data`]: SocketDescriptor::send_data
1156 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1157 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1158 let peers = self.peers.read().unwrap();
1159 match peers.get(descriptor) {
1161 // This is most likely a simple race condition where the user found that the socket
1162 // was writeable, then we told the user to `disconnect_socket()`, then they called
1163 // this method. Return an error to make sure we get disconnected.
1164 return Err(PeerHandleError { });
1166 Some(peer_mutex) => {
1167 let mut peer = peer_mutex.lock().unwrap();
1168 peer.awaiting_write_event = false;
1169 self.do_attempt_write_data(descriptor, &mut peer, false);
1175 /// Indicates that data was read from the given socket descriptor.
1177 /// May return an Err to indicate that the connection should be closed.
1179 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1180 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1181 /// [`send_data`] calls to handle responses.
1183 /// If `Ok(true)` is returned, further read_events should not be triggered until a
1184 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1187 /// In order to avoid processing too many messages at once per peer, `data` should be on the
1190 /// [`send_data`]: SocketDescriptor::send_data
1191 /// [`process_events`]: PeerManager::process_events
1192 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1193 match self.do_read_event(peer_descriptor, data) {
1196 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1197 self.disconnect_event_internal(peer_descriptor);
1203 /// Append a message to a peer's pending outbound/write buffer
1204 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1205 if is_gossip_msg(message.type_id()) {
1206 log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1208 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1210 peer.msgs_sent_since_pong += 1;
1211 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1214 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1215 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: Vec<u8>) {
1216 peer.msgs_sent_since_pong += 1;
1217 peer.gossip_broadcast_buffer.push_back(encoded_message);
1220 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1221 let mut pause_read = false;
1222 let peers = self.peers.read().unwrap();
1223 let mut msgs_to_forward = Vec::new();
1224 let mut peer_node_id = None;
1225 match peers.get(peer_descriptor) {
1227 // This is most likely a simple race condition where the user read some bytes
1228 // from the socket, then we told the user to `disconnect_socket()`, then they
1229 // called this method. Return an error to make sure we get disconnected.
1230 return Err(PeerHandleError { });
1232 Some(peer_mutex) => {
1233 let mut read_pos = 0;
1234 while read_pos < data.len() {
1235 macro_rules! try_potential_handleerror {
1236 ($peer: expr, $thing: expr) => {
1241 msgs::ErrorAction::DisconnectPeer { .. } => {
1242 // We may have an `ErrorMessage` to send to the peer,
1243 // but writing to the socket while reading can lead to
1244 // re-entrant code and possibly unexpected behavior. The
1245 // message send is optimistic anyway, and in this case
1246 // we immediately disconnect the peer.
1247 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1248 return Err(PeerHandleError { });
1250 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1251 // We have a `WarningMessage` to send to the peer, but
1252 // writing to the socket while reading can lead to
1253 // re-entrant code and possibly unexpected behavior. The
1254 // message send is optimistic anyway, and in this case
1255 // we immediately disconnect the peer.
1256 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1257 return Err(PeerHandleError { });
1259 msgs::ErrorAction::IgnoreAndLog(level) => {
1260 log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1263 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1264 msgs::ErrorAction::IgnoreError => {
1265 log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1268 msgs::ErrorAction::SendErrorMessage { msg } => {
1269 log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1270 self.enqueue_message($peer, &msg);
1273 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1274 log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1275 self.enqueue_message($peer, &msg);
1284 let mut peer_lock = peer_mutex.lock().unwrap();
1285 let peer = &mut *peer_lock;
1286 let mut msg_to_handle = None;
1287 if peer_node_id.is_none() {
1288 peer_node_id = peer.their_node_id.clone();
1291 assert!(peer.pending_read_buffer.len() > 0);
1292 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1295 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1296 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]);
1297 read_pos += data_to_copy;
1298 peer.pending_read_buffer_pos += data_to_copy;
1301 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1302 peer.pending_read_buffer_pos = 0;
1304 macro_rules! insert_node_id {
1306 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1307 hash_map::Entry::Occupied(e) => {
1308 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1309 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1310 // Check that the peers map is consistent with the
1311 // node_id_to_descriptor map, as this has been broken
1313 debug_assert!(peers.get(e.get()).is_some());
1314 return Err(PeerHandleError { })
1316 hash_map::Entry::Vacant(entry) => {
1317 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1318 entry.insert(peer_descriptor.clone())
1324 let next_step = peer.channel_encryptor.get_noise_step();
1326 NextNoiseStep::ActOne => {
1327 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1328 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1329 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1330 peer.pending_outbound_buffer.push_back(act_two);
1331 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1333 NextNoiseStep::ActTwo => {
1334 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1335 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1336 &self.node_signer));
1337 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1338 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1339 peer.pending_read_is_header = true;
1341 peer.set_their_node_id(their_node_id);
1343 let features = self.init_features(&their_node_id);
1344 let networks = self.message_handler.chan_handler.get_genesis_hashes();
1345 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1346 self.enqueue_message(peer, &resp);
1347 peer.awaiting_pong_timer_tick_intervals = 0;
1349 NextNoiseStep::ActThree => {
1350 let their_node_id = try_potential_handleerror!(peer,
1351 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1352 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1353 peer.pending_read_is_header = true;
1354 peer.set_their_node_id(their_node_id);
1356 let features = self.init_features(&their_node_id);
1357 let networks = self.message_handler.chan_handler.get_genesis_hashes();
1358 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1359 self.enqueue_message(peer, &resp);
1360 peer.awaiting_pong_timer_tick_intervals = 0;
1362 NextNoiseStep::NoiseComplete => {
1363 if peer.pending_read_is_header {
1364 let msg_len = try_potential_handleerror!(peer,
1365 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1366 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1367 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1368 if msg_len < 2 { // Need at least the message type tag
1369 return Err(PeerHandleError { });
1371 peer.pending_read_is_header = false;
1373 let msg_data = try_potential_handleerror!(peer,
1374 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1375 assert!(msg_data.len() >= 2);
1377 // Reset read buffer
1378 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1379 peer.pending_read_buffer.resize(18, 0);
1380 peer.pending_read_is_header = true;
1382 let mut reader = io::Cursor::new(&msg_data[..]);
1383 let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1384 let message = match message_result {
1388 // Note that to avoid re-entrancy we never call
1389 // `do_attempt_write_data` from here, causing
1390 // the messages enqueued here to not actually
1391 // be sent before the peer is disconnected.
1392 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1393 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1396 (msgs::DecodeError::UnsupportedCompression, _) => {
1397 log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1398 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1401 (_, Some(ty)) if is_gossip_msg(ty) => {
1402 log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1403 self.enqueue_message(peer, &msgs::WarningMessage {
1404 channel_id: [0; 32],
1405 data: format!("Unreadable/bogus gossip message of type {}", ty),
1409 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1410 log_debug!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1411 return Err(PeerHandleError { });
1413 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1414 (msgs::DecodeError::InvalidValue, _) => {
1415 log_debug!(self.logger, "Got an invalid value while deserializing message");
1416 return Err(PeerHandleError { });
1418 (msgs::DecodeError::ShortRead, _) => {
1419 log_debug!(self.logger, "Deserialization failed due to shortness of message");
1420 return Err(PeerHandleError { });
1422 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1423 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1428 msg_to_handle = Some(message);
1433 pause_read = !self.peer_should_read(peer);
1435 if let Some(message) = msg_to_handle {
1436 match self.handle_message(&peer_mutex, peer_lock, message) {
1437 Err(handling_error) => match handling_error {
1438 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1439 MessageHandlingError::LightningError(e) => {
1440 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1444 msgs_to_forward.push(msg);
1453 for msg in msgs_to_forward.drain(..) {
1454 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1460 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1461 /// Returns the message back if it needs to be broadcasted to all other peers.
1464 peer_mutex: &Mutex<Peer>,
1465 mut peer_lock: MutexGuard<Peer>,
1466 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1467 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1468 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;
1469 peer_lock.received_message_since_timer_tick = true;
1471 // Need an Init as first message
1472 if let wire::Message::Init(msg) = message {
1473 // Check if we have any compatible chains if the `networks` field is specified.
1474 if let Some(networks) = &msg.networks {
1475 if let Some(our_chains) = self.message_handler.chan_handler.get_genesis_hashes() {
1476 let mut have_compatible_chains = false;
1477 'our_chains: for our_chain in our_chains.iter() {
1478 for their_chain in networks {
1479 if our_chain == their_chain {
1480 have_compatible_chains = true;
1485 if !have_compatible_chains {
1486 log_debug!(self.logger, "Peer does not support any of our supported chains");
1487 return Err(PeerHandleError { }.into());
1492 let our_features = self.init_features(&their_node_id);
1493 if msg.features.requires_unknown_bits_from(&our_features) {
1494 log_debug!(self.logger, "Peer requires features unknown to us");
1495 return Err(PeerHandleError { }.into());
1498 if our_features.requires_unknown_bits_from(&msg.features) {
1499 log_debug!(self.logger, "We require features unknown to our peer");
1500 return Err(PeerHandleError { }.into());
1503 if peer_lock.their_features.is_some() {
1504 return Err(PeerHandleError { }.into());
1507 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1509 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1510 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1511 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1514 if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1515 log_debug!(self.logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1516 return Err(PeerHandleError { }.into());
1518 if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1519 log_debug!(self.logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1520 return Err(PeerHandleError { }.into());
1522 if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1523 log_debug!(self.logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1524 return Err(PeerHandleError { }.into());
1527 peer_lock.their_features = Some(msg.features);
1529 } else if peer_lock.their_features.is_none() {
1530 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1531 return Err(PeerHandleError { }.into());
1534 if let wire::Message::GossipTimestampFilter(_msg) = message {
1535 // When supporting gossip messages, start inital gossip sync only after we receive
1536 // a GossipTimestampFilter
1537 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1538 !peer_lock.sent_gossip_timestamp_filter {
1539 peer_lock.sent_gossip_timestamp_filter = true;
1540 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1545 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1546 peer_lock.received_channel_announce_since_backlogged = true;
1549 mem::drop(peer_lock);
1551 if is_gossip_msg(message.type_id()) {
1552 log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1554 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1557 let mut should_forward = None;
1560 // Setup and Control messages:
1561 wire::Message::Init(_) => {
1564 wire::Message::GossipTimestampFilter(_) => {
1567 wire::Message::Error(msg) => {
1568 let mut data_is_printable = true;
1569 for b in msg.data.bytes() {
1570 if b < 32 || b > 126 {
1571 data_is_printable = false;
1576 if data_is_printable {
1577 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1579 log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1581 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1582 if msg.channel_id == [0; 32] {
1583 return Err(PeerHandleError { }.into());
1586 wire::Message::Warning(msg) => {
1587 let mut data_is_printable = true;
1588 for b in msg.data.bytes() {
1589 if b < 32 || b > 126 {
1590 data_is_printable = false;
1595 if data_is_printable {
1596 log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1598 log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1602 wire::Message::Ping(msg) => {
1603 if msg.ponglen < 65532 {
1604 let resp = msgs::Pong { byteslen: msg.ponglen };
1605 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1608 wire::Message::Pong(_msg) => {
1609 let mut peer_lock = peer_mutex.lock().unwrap();
1610 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1611 peer_lock.msgs_sent_since_pong = 0;
1614 // Channel messages:
1615 wire::Message::OpenChannel(msg) => {
1616 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1618 wire::Message::OpenChannelV2(msg) => {
1619 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1621 wire::Message::AcceptChannel(msg) => {
1622 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1624 wire::Message::AcceptChannelV2(msg) => {
1625 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1628 wire::Message::FundingCreated(msg) => {
1629 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1631 wire::Message::FundingSigned(msg) => {
1632 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1634 wire::Message::ChannelReady(msg) => {
1635 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1638 // Interactive transaction construction messages:
1639 wire::Message::TxAddInput(msg) => {
1640 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1642 wire::Message::TxAddOutput(msg) => {
1643 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1645 wire::Message::TxRemoveInput(msg) => {
1646 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1648 wire::Message::TxRemoveOutput(msg) => {
1649 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1651 wire::Message::TxComplete(msg) => {
1652 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1654 wire::Message::TxSignatures(msg) => {
1655 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1657 wire::Message::TxInitRbf(msg) => {
1658 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1660 wire::Message::TxAckRbf(msg) => {
1661 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1663 wire::Message::TxAbort(msg) => {
1664 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1667 wire::Message::Shutdown(msg) => {
1668 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1670 wire::Message::ClosingSigned(msg) => {
1671 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1674 // Commitment messages:
1675 wire::Message::UpdateAddHTLC(msg) => {
1676 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1678 wire::Message::UpdateFulfillHTLC(msg) => {
1679 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1681 wire::Message::UpdateFailHTLC(msg) => {
1682 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1684 wire::Message::UpdateFailMalformedHTLC(msg) => {
1685 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1688 wire::Message::CommitmentSigned(msg) => {
1689 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1691 wire::Message::RevokeAndACK(msg) => {
1692 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1694 wire::Message::UpdateFee(msg) => {
1695 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1697 wire::Message::ChannelReestablish(msg) => {
1698 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1701 // Routing messages:
1702 wire::Message::AnnouncementSignatures(msg) => {
1703 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1705 wire::Message::ChannelAnnouncement(msg) => {
1706 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1707 .map_err(|e| -> MessageHandlingError { e.into() })? {
1708 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1710 self.update_gossip_backlogged();
1712 wire::Message::NodeAnnouncement(msg) => {
1713 if self.message_handler.route_handler.handle_node_announcement(&msg)
1714 .map_err(|e| -> MessageHandlingError { e.into() })? {
1715 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1717 self.update_gossip_backlogged();
1719 wire::Message::ChannelUpdate(msg) => {
1720 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1721 if self.message_handler.route_handler.handle_channel_update(&msg)
1722 .map_err(|e| -> MessageHandlingError { e.into() })? {
1723 should_forward = Some(wire::Message::ChannelUpdate(msg));
1725 self.update_gossip_backlogged();
1727 wire::Message::QueryShortChannelIds(msg) => {
1728 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1730 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1731 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1733 wire::Message::QueryChannelRange(msg) => {
1734 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1736 wire::Message::ReplyChannelRange(msg) => {
1737 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1741 wire::Message::OnionMessage(msg) => {
1742 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1745 // Unknown messages:
1746 wire::Message::Unknown(type_id) if message.is_even() => {
1747 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1748 return Err(PeerHandleError { }.into());
1750 wire::Message::Unknown(type_id) => {
1751 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1753 wire::Message::Custom(custom) => {
1754 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1760 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>) {
1762 wire::Message::ChannelAnnouncement(ref msg) => {
1763 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1764 let encoded_msg = encode_msg!(msg);
1766 for (_, peer_mutex) in peers.iter() {
1767 let mut peer = peer_mutex.lock().unwrap();
1768 if !peer.handshake_complete() ||
1769 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1772 debug_assert!(peer.their_node_id.is_some());
1773 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1774 if peer.buffer_full_drop_gossip_broadcast() {
1775 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1778 if let Some((_, their_node_id)) = peer.their_node_id {
1779 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1783 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1786 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1789 wire::Message::NodeAnnouncement(ref msg) => {
1790 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1791 let encoded_msg = encode_msg!(msg);
1793 for (_, peer_mutex) in peers.iter() {
1794 let mut peer = peer_mutex.lock().unwrap();
1795 if !peer.handshake_complete() ||
1796 !peer.should_forward_node_announcement(msg.contents.node_id) {
1799 debug_assert!(peer.their_node_id.is_some());
1800 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1801 if peer.buffer_full_drop_gossip_broadcast() {
1802 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1805 if let Some((_, their_node_id)) = peer.their_node_id {
1806 if their_node_id == msg.contents.node_id {
1810 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1813 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1816 wire::Message::ChannelUpdate(ref msg) => {
1817 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1818 let encoded_msg = encode_msg!(msg);
1820 for (_, peer_mutex) in peers.iter() {
1821 let mut peer = peer_mutex.lock().unwrap();
1822 if !peer.handshake_complete() ||
1823 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1826 debug_assert!(peer.their_node_id.is_some());
1827 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1828 if peer.buffer_full_drop_gossip_broadcast() {
1829 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1832 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1835 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1838 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1842 /// Checks for any events generated by our handlers and processes them. Includes sending most
1843 /// response messages as well as messages generated by calls to handler functions directly (eg
1844 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1846 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1849 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1850 /// or one of the other clients provided in our language bindings.
1852 /// Note that if there are any other calls to this function waiting on lock(s) this may return
1853 /// without doing any work. All available events that need handling will be handled before the
1854 /// other calls return.
1856 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1857 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1858 /// [`send_data`]: SocketDescriptor::send_data
1859 pub fn process_events(&self) {
1860 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
1861 // If we're not the first event processor to get here, just return early, the increment
1862 // we just did will be treated as "go around again" at the end.
1867 self.update_gossip_backlogged();
1868 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
1870 let mut peers_to_disconnect = HashMap::new();
1871 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1872 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1875 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1876 // buffer by doing things like announcing channels on another node. We should be willing to
1877 // drop optional-ish messages when send buffers get full!
1879 let peers_lock = self.peers.read().unwrap();
1880 let peers = &*peers_lock;
1881 macro_rules! get_peer_for_forwarding {
1882 ($node_id: expr) => {
1884 if peers_to_disconnect.get($node_id).is_some() {
1885 // If we've "disconnected" this peer, do not send to it.
1888 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1889 match descriptor_opt {
1890 Some(descriptor) => match peers.get(&descriptor) {
1891 Some(peer_mutex) => {
1892 let peer_lock = peer_mutex.lock().unwrap();
1893 if !peer_lock.handshake_complete() {
1899 debug_assert!(false, "Inconsistent peers set state!");
1910 for event in events_generated.drain(..) {
1912 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1913 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1914 log_pubkey!(node_id),
1915 log_bytes!(msg.temporary_channel_id));
1916 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1918 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
1919 log_debug!(self.logger, "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
1920 log_pubkey!(node_id),
1921 log_bytes!(msg.temporary_channel_id));
1922 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1924 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1925 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1926 log_pubkey!(node_id),
1927 log_bytes!(msg.temporary_channel_id));
1928 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1930 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
1931 log_debug!(self.logger, "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}",
1932 log_pubkey!(node_id),
1933 log_bytes!(msg.temporary_channel_id));
1934 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1936 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1937 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1938 log_pubkey!(node_id),
1939 log_bytes!(msg.temporary_channel_id),
1940 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1941 // TODO: If the peer is gone we should generate a DiscardFunding event
1942 // indicating to the wallet that they should just throw away this funding transaction
1943 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1945 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1946 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1947 log_pubkey!(node_id),
1948 log_bytes!(msg.channel_id));
1949 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1951 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1952 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1953 log_pubkey!(node_id),
1954 log_bytes!(msg.channel_id));
1955 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1957 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
1958 log_debug!(self.logger, "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
1959 log_pubkey!(node_id),
1960 log_bytes!(msg.channel_id));
1961 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1963 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
1964 log_debug!(self.logger, "Handling SendTxAddOutput event in peer_handler for node {} for channel {}",
1965 log_pubkey!(node_id),
1966 log_bytes!(msg.channel_id));
1967 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1969 MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => {
1970 log_debug!(self.logger, "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
1971 log_pubkey!(node_id),
1972 log_bytes!(msg.channel_id));
1973 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1975 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
1976 log_debug!(self.logger, "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
1977 log_pubkey!(node_id),
1978 log_bytes!(msg.channel_id));
1979 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1981 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
1982 log_debug!(self.logger, "Handling SendTxComplete event in peer_handler for node {} for channel {}",
1983 log_pubkey!(node_id),
1984 log_bytes!(msg.channel_id));
1985 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1987 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
1988 log_debug!(self.logger, "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
1989 log_pubkey!(node_id),
1990 log_bytes!(msg.channel_id));
1991 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1993 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
1994 log_debug!(self.logger, "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
1995 log_pubkey!(node_id),
1996 log_bytes!(msg.channel_id));
1997 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1999 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2000 log_debug!(self.logger, "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2001 log_pubkey!(node_id),
2002 log_bytes!(msg.channel_id));
2003 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2005 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2006 log_debug!(self.logger, "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2007 log_pubkey!(node_id),
2008 log_bytes!(msg.channel_id));
2009 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2011 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2012 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2013 log_pubkey!(node_id),
2014 log_bytes!(msg.channel_id));
2015 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2017 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 } } => {
2018 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
2019 log_pubkey!(node_id),
2020 update_add_htlcs.len(),
2021 update_fulfill_htlcs.len(),
2022 update_fail_htlcs.len(),
2023 log_bytes!(commitment_signed.channel_id));
2024 let mut peer = get_peer_for_forwarding!(node_id);
2025 for msg in update_add_htlcs {
2026 self.enqueue_message(&mut *peer, msg);
2028 for msg in update_fulfill_htlcs {
2029 self.enqueue_message(&mut *peer, msg);
2031 for msg in update_fail_htlcs {
2032 self.enqueue_message(&mut *peer, msg);
2034 for msg in update_fail_malformed_htlcs {
2035 self.enqueue_message(&mut *peer, msg);
2037 if let &Some(ref msg) = update_fee {
2038 self.enqueue_message(&mut *peer, msg);
2040 self.enqueue_message(&mut *peer, commitment_signed);
2042 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2043 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2044 log_pubkey!(node_id),
2045 log_bytes!(msg.channel_id));
2046 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2048 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2049 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2050 log_pubkey!(node_id),
2051 log_bytes!(msg.channel_id));
2052 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2054 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2055 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
2056 log_pubkey!(node_id),
2057 log_bytes!(msg.channel_id));
2058 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2060 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2061 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2062 log_pubkey!(node_id),
2063 log_bytes!(msg.channel_id));
2064 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2066 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2067 log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2068 log_pubkey!(node_id),
2069 msg.contents.short_channel_id);
2070 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2071 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2073 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2074 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2075 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2076 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2077 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2080 if let Some(msg) = update_msg {
2081 match self.message_handler.route_handler.handle_channel_update(&msg) {
2082 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2083 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2088 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2089 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2090 match self.message_handler.route_handler.handle_channel_update(&msg) {
2091 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2092 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2096 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2097 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2098 match self.message_handler.route_handler.handle_node_announcement(&msg) {
2099 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2100 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2104 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2105 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2106 log_pubkey!(node_id), msg.contents.short_channel_id);
2107 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2109 MessageSendEvent::HandleError { node_id, action } => {
2111 msgs::ErrorAction::DisconnectPeer { msg } => {
2112 if let Some(msg) = msg.as_ref() {
2113 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2114 log_pubkey!(node_id), msg.data);
2116 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2117 log_pubkey!(node_id));
2119 // We do not have the peers write lock, so we just store that we're
2120 // about to disconenct the peer and do it after we finish
2121 // processing most messages.
2122 let msg = msg.map(|msg| wire::Message::<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2123 peers_to_disconnect.insert(node_id, msg);
2125 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2126 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2127 log_pubkey!(node_id), msg.data);
2128 // We do not have the peers write lock, so we just store that we're
2129 // about to disconenct the peer and do it after we finish
2130 // processing most messages.
2131 peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2133 msgs::ErrorAction::IgnoreAndLog(level) => {
2134 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2136 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2137 msgs::ErrorAction::IgnoreError => {
2138 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2140 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2141 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2142 log_pubkey!(node_id),
2144 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2146 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2147 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2148 log_pubkey!(node_id),
2150 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2154 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2155 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2157 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2158 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2160 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2161 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
2162 log_pubkey!(node_id),
2163 msg.short_channel_ids.len(),
2165 msg.number_of_blocks,
2167 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2169 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2170 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2175 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2176 if peers_to_disconnect.get(&node_id).is_some() { continue; }
2177 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2180 for (descriptor, peer_mutex) in peers.iter() {
2181 let mut peer = peer_mutex.lock().unwrap();
2182 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2183 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2186 if !peers_to_disconnect.is_empty() {
2187 let mut peers_lock = self.peers.write().unwrap();
2188 let peers = &mut *peers_lock;
2189 for (node_id, msg) in peers_to_disconnect.drain() {
2190 // Note that since we are holding the peers *write* lock we can
2191 // remove from node_id_to_descriptor immediately (as no other
2192 // thread can be holding the peer lock if we have the global write
2195 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2196 if let Some(mut descriptor) = descriptor_opt {
2197 if let Some(peer_mutex) = peers.remove(&descriptor) {
2198 let mut peer = peer_mutex.lock().unwrap();
2199 if let Some(msg) = msg {
2200 self.enqueue_message(&mut *peer, &msg);
2201 // This isn't guaranteed to work, but if there is enough free
2202 // room in the send buffer, put the error message there...
2203 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2205 self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2206 } else { debug_assert!(false, "Missing connection for peer"); }
2211 if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2212 // If another thread incremented the state while we were running we should go
2213 // around again, but only once.
2214 self.event_processing_state.store(1, Ordering::Release);
2221 /// Indicates that the given socket descriptor's connection is now closed.
2222 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2223 self.disconnect_event_internal(descriptor);
2226 fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2227 if !peer.handshake_complete() {
2228 log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2229 descriptor.disconnect_socket();
2233 debug_assert!(peer.their_node_id.is_some());
2234 if let Some((node_id, _)) = peer.their_node_id {
2235 log_trace!(self.logger, "Disconnecting peer with id {} due to {}", node_id, reason);
2236 self.message_handler.chan_handler.peer_disconnected(&node_id);
2237 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2239 descriptor.disconnect_socket();
2242 fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2243 let mut peers = self.peers.write().unwrap();
2244 let peer_option = peers.remove(descriptor);
2247 // This is most likely a simple race condition where the user found that the socket
2248 // was disconnected, then we told the user to `disconnect_socket()`, then they
2249 // called this method. Either way we're disconnected, return.
2251 Some(peer_lock) => {
2252 let peer = peer_lock.lock().unwrap();
2253 if let Some((node_id, _)) = peer.their_node_id {
2254 log_trace!(self.logger, "Handling disconnection of peer {}", log_pubkey!(node_id));
2255 let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2256 debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2257 if !peer.handshake_complete() { return; }
2258 self.message_handler.chan_handler.peer_disconnected(&node_id);
2259 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2265 /// Disconnect a peer given its node id.
2267 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2268 /// peer. Thus, be very careful about reentrancy issues.
2270 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2271 pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2272 let mut peers_lock = self.peers.write().unwrap();
2273 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2274 let peer_opt = peers_lock.remove(&descriptor);
2275 if let Some(peer_mutex) = peer_opt {
2276 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2277 } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2281 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2282 /// an indication that TCP sockets have stalled even if we weren't around to time them out
2283 /// using regular ping/pongs.
2284 pub fn disconnect_all_peers(&self) {
2285 let mut peers_lock = self.peers.write().unwrap();
2286 self.node_id_to_descriptor.lock().unwrap().clear();
2287 let peers = &mut *peers_lock;
2288 for (descriptor, peer_mutex) in peers.drain() {
2289 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2293 /// This is called when we're blocked on sending additional gossip messages until we receive a
2294 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2295 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2296 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2297 if peer.awaiting_pong_timer_tick_intervals == 0 {
2298 peer.awaiting_pong_timer_tick_intervals = -1;
2299 let ping = msgs::Ping {
2303 self.enqueue_message(peer, &ping);
2307 /// Send pings to each peer and disconnect those which did not respond to the last round of
2310 /// This may be called on any timescale you want, however, roughly once every ten seconds is
2311 /// preferred. The call rate determines both how often we send a ping to our peers and how much
2312 /// time they have to respond before we disconnect them.
2314 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2317 /// [`send_data`]: SocketDescriptor::send_data
2318 pub fn timer_tick_occurred(&self) {
2319 let mut descriptors_needing_disconnect = Vec::new();
2321 let peers_lock = self.peers.read().unwrap();
2323 self.update_gossip_backlogged();
2324 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2326 for (descriptor, peer_mutex) in peers_lock.iter() {
2327 let mut peer = peer_mutex.lock().unwrap();
2328 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2330 if !peer.handshake_complete() {
2331 // The peer needs to complete its handshake before we can exchange messages. We
2332 // give peers one timer tick to complete handshake, reusing
2333 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2334 // for handshake completion.
2335 if peer.awaiting_pong_timer_tick_intervals != 0 {
2336 descriptors_needing_disconnect.push(descriptor.clone());
2338 peer.awaiting_pong_timer_tick_intervals = 1;
2342 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2343 debug_assert!(peer.their_node_id.is_some());
2345 loop { // Used as a `goto` to skip writing a Ping message.
2346 if peer.awaiting_pong_timer_tick_intervals == -1 {
2347 // Magic value set in `maybe_send_extra_ping`.
2348 peer.awaiting_pong_timer_tick_intervals = 1;
2349 peer.received_message_since_timer_tick = false;
2353 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2354 || peer.awaiting_pong_timer_tick_intervals as u64 >
2355 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2357 descriptors_needing_disconnect.push(descriptor.clone());
2360 peer.received_message_since_timer_tick = false;
2362 if peer.awaiting_pong_timer_tick_intervals > 0 {
2363 peer.awaiting_pong_timer_tick_intervals += 1;
2367 peer.awaiting_pong_timer_tick_intervals = 1;
2368 let ping = msgs::Ping {
2372 self.enqueue_message(&mut *peer, &ping);
2375 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2379 if !descriptors_needing_disconnect.is_empty() {
2381 let mut peers_lock = self.peers.write().unwrap();
2382 for descriptor in descriptors_needing_disconnect {
2383 if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2384 let peer = peer_mutex.lock().unwrap();
2385 if let Some((node_id, _)) = peer.their_node_id {
2386 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2388 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2396 // Messages of up to 64KB should never end up more than half full with addresses, as that would
2397 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2398 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2400 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
2403 // ...by failing to compile if the number of addresses that would be half of a message is
2404 // smaller than 100:
2405 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2407 /// Generates a signed node_announcement from the given arguments, sending it to all connected
2408 /// peers. Note that peers will likely ignore this message unless we have at least one public
2409 /// channel which has at least six confirmations on-chain.
2411 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2412 /// node to humans. They carry no in-protocol meaning.
2414 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2415 /// accepts incoming connections. These will be included in the node_announcement, publicly
2416 /// tying these addresses together and to this node. If you wish to preserve user privacy,
2417 /// addresses should likely contain only Tor Onion addresses.
2419 /// Panics if `addresses` is absurdly large (more than 100).
2421 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2422 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
2423 if addresses.len() > 100 {
2424 panic!("More than half the message size was taken up by public addresses!");
2427 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2428 // addresses be sorted for future compatibility.
2429 addresses.sort_by_key(|addr| addr.get_id());
2431 let features = self.message_handler.chan_handler.provided_node_features()
2432 | self.message_handler.route_handler.provided_node_features()
2433 | self.message_handler.onion_message_handler.provided_node_features()
2434 | self.message_handler.custom_message_handler.provided_node_features();
2435 let announcement = msgs::UnsignedNodeAnnouncement {
2437 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2438 node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2440 alias: NodeAlias(alias),
2442 excess_address_data: Vec::new(),
2443 excess_data: Vec::new(),
2445 let node_announce_sig = match self.node_signer.sign_gossip_message(
2446 msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2450 log_error!(self.logger, "Failed to generate signature for node_announcement");
2455 let msg = msgs::NodeAnnouncement {
2456 signature: node_announce_sig,
2457 contents: announcement
2460 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2461 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2462 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2466 fn is_gossip_msg(type_id: u16) -> bool {
2468 msgs::ChannelAnnouncement::TYPE |
2469 msgs::ChannelUpdate::TYPE |
2470 msgs::NodeAnnouncement::TYPE |
2471 msgs::QueryChannelRange::TYPE |
2472 msgs::ReplyChannelRange::TYPE |
2473 msgs::QueryShortChannelIds::TYPE |
2474 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2481 use crate::sign::{NodeSigner, Recipient};
2484 use crate::ln::features::{InitFeatures, NodeFeatures};
2485 use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2486 use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2487 use crate::ln::{msgs, wire};
2488 use crate::ln::msgs::{LightningError, NetAddress};
2489 use crate::util::test_utils;
2491 use bitcoin::Network;
2492 use bitcoin::blockdata::constants::ChainHash;
2493 use bitcoin::secp256k1::{PublicKey, SecretKey};
2495 use crate::prelude::*;
2496 use crate::sync::{Arc, Mutex};
2497 use core::convert::Infallible;
2498 use core::sync::atomic::{AtomicBool, Ordering};
2501 struct FileDescriptor {
2503 outbound_data: Arc<Mutex<Vec<u8>>>,
2504 disconnect: Arc<AtomicBool>,
2506 impl PartialEq for FileDescriptor {
2507 fn eq(&self, other: &Self) -> bool {
2511 impl Eq for FileDescriptor { }
2512 impl core::hash::Hash for FileDescriptor {
2513 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2514 self.fd.hash(hasher)
2518 impl SocketDescriptor for FileDescriptor {
2519 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2520 self.outbound_data.lock().unwrap().extend_from_slice(data);
2524 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2527 struct PeerManagerCfg {
2528 chan_handler: test_utils::TestChannelMessageHandler,
2529 routing_handler: test_utils::TestRoutingMessageHandler,
2530 custom_handler: TestCustomMessageHandler,
2531 logger: test_utils::TestLogger,
2532 node_signer: test_utils::TestNodeSigner,
2535 struct TestCustomMessageHandler {
2536 features: InitFeatures,
2539 impl wire::CustomMessageReader for TestCustomMessageHandler {
2540 type CustomMessage = Infallible;
2541 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2546 impl CustomMessageHandler for TestCustomMessageHandler {
2547 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2551 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2553 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2555 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2556 self.features.clone()
2560 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2561 let mut cfgs = Vec::new();
2562 for i in 0..peer_count {
2563 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2565 let mut feature_bits = vec![0u8; 33];
2566 feature_bits[32] = 0b00000001;
2567 InitFeatures::from_le_bytes(feature_bits)
2571 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2572 logger: test_utils::TestLogger::new(),
2573 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2574 custom_handler: TestCustomMessageHandler { features },
2575 node_signer: test_utils::TestNodeSigner::new(node_secret),
2583 fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2584 let mut cfgs = Vec::new();
2585 for i in 0..peer_count {
2586 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2588 let mut feature_bits = vec![0u8; 33 + i + 1];
2589 feature_bits[33 + i] = 0b00000001;
2590 InitFeatures::from_le_bytes(feature_bits)
2594 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2595 logger: test_utils::TestLogger::new(),
2596 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2597 custom_handler: TestCustomMessageHandler { features },
2598 node_signer: test_utils::TestNodeSigner::new(node_secret),
2606 fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2607 let mut cfgs = Vec::new();
2608 for i in 0..peer_count {
2609 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2610 let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2611 let network = ChainHash::from(&[i as u8; 32][..]);
2614 chan_handler: test_utils::TestChannelMessageHandler::new(network),
2615 logger: test_utils::TestLogger::new(),
2616 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2617 custom_handler: TestCustomMessageHandler { features },
2618 node_signer: test_utils::TestNodeSigner::new(node_secret),
2626 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>> {
2627 let mut peers = Vec::new();
2628 for i in 0..peer_count {
2629 let ephemeral_bytes = [i as u8; 32];
2630 let msg_handler = MessageHandler {
2631 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2632 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2634 let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2641 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) {
2642 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2643 let mut fd_a = FileDescriptor {
2644 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2645 disconnect: Arc::new(AtomicBool::new(false)),
2647 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2648 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2649 let mut fd_b = FileDescriptor {
2650 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2651 disconnect: Arc::new(AtomicBool::new(false)),
2653 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2654 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2655 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2656 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2657 peer_a.process_events();
2659 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2660 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2662 peer_b.process_events();
2663 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2664 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2666 peer_a.process_events();
2667 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2668 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2670 assert!(peer_a.get_peer_node_ids().contains(&(id_b, Some(addr_b))));
2671 assert!(peer_b.get_peer_node_ids().contains(&(id_a, Some(addr_a))));
2673 (fd_a.clone(), fd_b.clone())
2677 #[cfg(feature = "std")]
2678 fn fuzz_threaded_connections() {
2679 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2680 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2681 // with our internal map consistency, and is a generally good smoke test of disconnection.
2682 let cfgs = Arc::new(create_peermgr_cfgs(2));
2683 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2684 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2686 let start_time = std::time::Instant::now();
2687 macro_rules! spawn_thread { ($id: expr) => { {
2688 let peers = Arc::clone(&peers);
2689 let cfgs = Arc::clone(&cfgs);
2690 std::thread::spawn(move || {
2692 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2693 let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2694 let mut fd_a = FileDescriptor {
2695 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2696 disconnect: Arc::new(AtomicBool::new(false)),
2698 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2699 let mut fd_b = FileDescriptor {
2700 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2701 disconnect: Arc::new(AtomicBool::new(false)),
2703 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2704 let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2705 peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2706 if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2708 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2709 peers[0].process_events();
2710 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2711 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2712 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2714 peers[1].process_events();
2715 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2716 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2717 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2719 cfgs[0].chan_handler.pending_events.lock().unwrap()
2720 .push(crate::events::MessageSendEvent::SendShutdown {
2721 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2722 msg: msgs::Shutdown {
2723 channel_id: [0; 32],
2724 scriptpubkey: bitcoin::Script::new(),
2727 cfgs[1].chan_handler.pending_events.lock().unwrap()
2728 .push(crate::events::MessageSendEvent::SendShutdown {
2729 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2730 msg: msgs::Shutdown {
2731 channel_id: [0; 32],
2732 scriptpubkey: bitcoin::Script::new(),
2737 peers[0].timer_tick_occurred();
2738 peers[1].timer_tick_occurred();
2742 peers[0].socket_disconnected(&fd_a);
2743 peers[1].socket_disconnected(&fd_b);
2745 std::thread::sleep(std::time::Duration::from_micros(1));
2749 let thrd_a = spawn_thread!(1);
2750 let thrd_b = spawn_thread!(2);
2752 thrd_a.join().unwrap();
2753 thrd_b.join().unwrap();
2757 fn test_feature_incompatible_peers() {
2758 let cfgs = create_peermgr_cfgs(2);
2759 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2761 let peers = create_network(2, &cfgs);
2762 let incompatible_peers = create_network(2, &incompatible_cfgs);
2763 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2764 for (peer_a, peer_b) in peer_pairs.iter() {
2765 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2766 let mut fd_a = FileDescriptor {
2767 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2768 disconnect: Arc::new(AtomicBool::new(false)),
2770 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2771 let mut fd_b = FileDescriptor {
2772 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2773 disconnect: Arc::new(AtomicBool::new(false)),
2775 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2776 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2777 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2778 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2779 peer_a.process_events();
2781 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2782 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2784 peer_b.process_events();
2785 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2787 // Should fail because of unknown required features
2788 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2793 fn test_chain_incompatible_peers() {
2794 let cfgs = create_peermgr_cfgs(2);
2795 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
2797 let peers = create_network(2, &cfgs);
2798 let incompatible_peers = create_network(2, &incompatible_cfgs);
2799 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2800 for (peer_a, peer_b) in peer_pairs.iter() {
2801 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2802 let mut fd_a = FileDescriptor {
2803 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2804 disconnect: Arc::new(AtomicBool::new(false)),
2806 let addr_a = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1000};
2807 let mut fd_b = FileDescriptor {
2808 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2809 disconnect: Arc::new(AtomicBool::new(false)),
2811 let addr_b = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1001};
2812 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2813 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2814 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2815 peer_a.process_events();
2817 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2818 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2820 peer_b.process_events();
2821 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2823 // Should fail because of incompatible chains
2824 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2829 fn test_disconnect_peer() {
2830 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2831 // push a DisconnectPeer event to remove the node flagged by id
2832 let cfgs = create_peermgr_cfgs(2);
2833 let peers = create_network(2, &cfgs);
2834 establish_connection(&peers[0], &peers[1]);
2835 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2837 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2838 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2840 action: msgs::ErrorAction::DisconnectPeer { msg: None },
2843 peers[0].process_events();
2844 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2848 fn test_send_simple_msg() {
2849 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2850 // push a message from one peer to another.
2851 let cfgs = create_peermgr_cfgs(2);
2852 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2853 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2854 let mut peers = create_network(2, &cfgs);
2855 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2856 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2858 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2860 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2861 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2862 node_id: their_id, msg: msg.clone()
2864 peers[0].message_handler.chan_handler = &a_chan_handler;
2866 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2867 peers[1].message_handler.chan_handler = &b_chan_handler;
2869 peers[0].process_events();
2871 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2872 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2876 fn test_non_init_first_msg() {
2877 // Simple test of the first message received over a connection being something other than
2878 // Init. This results in an immediate disconnection, which previously included a spurious
2879 // peer_disconnected event handed to event handlers (which would panic in
2880 // `TestChannelMessageHandler` here).
2881 let cfgs = create_peermgr_cfgs(2);
2882 let peers = create_network(2, &cfgs);
2884 let mut fd_dup = FileDescriptor {
2885 fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2886 disconnect: Arc::new(AtomicBool::new(false)),
2888 let addr_dup = NetAddress::IPv4{addr: [127, 0, 0, 1], port: 1003};
2889 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
2890 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
2892 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
2893 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
2894 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
2895 peers[0].process_events();
2897 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
2898 let (act_three, _) =
2899 dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
2900 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
2902 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
2903 let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg);
2904 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
2908 fn test_disconnect_all_peer() {
2909 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2910 // then calls disconnect_all_peers
2911 let cfgs = create_peermgr_cfgs(2);
2912 let peers = create_network(2, &cfgs);
2913 establish_connection(&peers[0], &peers[1]);
2914 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2916 peers[0].disconnect_all_peers();
2917 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2921 fn test_timer_tick_occurred() {
2922 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2923 let cfgs = create_peermgr_cfgs(2);
2924 let peers = create_network(2, &cfgs);
2925 establish_connection(&peers[0], &peers[1]);
2926 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2928 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2929 peers[0].timer_tick_occurred();
2930 peers[0].process_events();
2931 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2933 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2934 peers[0].timer_tick_occurred();
2935 peers[0].process_events();
2936 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2940 fn test_do_attempt_write_data() {
2941 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2942 let cfgs = create_peermgr_cfgs(2);
2943 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2944 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2945 let peers = create_network(2, &cfgs);
2947 // By calling establish_connect, we trigger do_attempt_write_data between
2948 // the peers. Previously this function would mistakenly enter an infinite loop
2949 // when there were more channel messages available than could fit into a peer's
2950 // buffer. This issue would now be detected by this test (because we use custom
2951 // RoutingMessageHandlers that intentionally return more channel messages
2952 // than can fit into a peer's buffer).
2953 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2955 // Make each peer to read the messages that the other peer just wrote to them. Note that
2956 // due to the max-message-before-ping limits this may take a few iterations to complete.
2957 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2958 peers[1].process_events();
2959 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2960 assert!(!a_read_data.is_empty());
2962 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2963 peers[0].process_events();
2965 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2966 assert!(!b_read_data.is_empty());
2967 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2969 peers[0].process_events();
2970 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2973 // Check that each peer has received the expected number of channel updates and channel
2975 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2976 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2977 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2978 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2982 fn test_handshake_timeout() {
2983 // Tests that we time out a peer still waiting on handshake completion after a full timer
2985 let cfgs = create_peermgr_cfgs(2);
2986 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2987 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2988 let peers = create_network(2, &cfgs);
2990 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2991 let mut fd_a = FileDescriptor {
2992 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2993 disconnect: Arc::new(AtomicBool::new(false)),
2995 let mut fd_b = FileDescriptor {
2996 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2997 disconnect: Arc::new(AtomicBool::new(false)),
2999 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3000 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3002 // If we get a single timer tick before completion, that's fine
3003 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3004 peers[0].timer_tick_occurred();
3005 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3007 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3008 peers[0].process_events();
3009 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3010 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3011 peers[1].process_events();
3013 // ...but if we get a second timer tick, we should disconnect the peer
3014 peers[0].timer_tick_occurred();
3015 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3017 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3018 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3022 fn test_filter_addresses(){
3023 // Tests the filter_addresses function.
3026 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
3027 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3028 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
3029 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3030 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
3031 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3034 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
3035 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3036 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
3037 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3038 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
3039 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3042 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
3043 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3044 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
3045 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3046 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
3047 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3050 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
3051 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3052 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
3053 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3054 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
3055 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3058 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
3059 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3060 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
3061 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3062 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
3063 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3066 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
3067 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3068 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
3069 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3070 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
3071 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3074 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
3075 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3076 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
3077 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3078 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
3079 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3081 // For (192.88.99/24)
3082 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
3083 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3084 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
3085 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3086 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
3087 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3089 // For other IPv4 addresses
3090 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
3091 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3092 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
3093 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3094 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
3095 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3098 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3099 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3100 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 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: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3103 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3105 // For other IPv6 addresses
3106 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3107 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3108 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3109 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3110 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3111 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3114 assert_eq!(filter_addresses(None), None);
3118 #[cfg(feature = "std")]
3119 fn test_process_events_multithreaded() {
3120 use std::time::{Duration, Instant};
3121 // Test that `process_events` getting called on multiple threads doesn't generate too many
3123 // Each time `process_events` goes around the loop we call
3124 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3125 // Because the loop should go around once more after a call which fails to take the
3126 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3127 // should never observe there having been more than 2 loop iterations.
3128 // Further, because the last thread to exit will call `process_events` before returning, we
3129 // should always have at least one count at the end.
3130 let cfg = Arc::new(create_peermgr_cfgs(1));
3131 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3132 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3134 let exit_flag = Arc::new(AtomicBool::new(false));
3135 macro_rules! spawn_thread { () => { {
3136 let thread_cfg = Arc::clone(&cfg);
3137 let thread_peer = Arc::clone(&peer);
3138 let thread_exit = Arc::clone(&exit_flag);
3139 std::thread::spawn(move || {
3140 while !thread_exit.load(Ordering::Acquire) {
3141 thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3142 thread_peer.process_events();
3143 std::thread::sleep(Duration::from_micros(1));
3148 let thread_a = spawn_thread!();
3149 let thread_b = spawn_thread!();
3150 let thread_c = spawn_thread!();
3152 let start_time = Instant::now();
3153 while start_time.elapsed() < Duration::from_millis(100) {
3154 let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3156 std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3159 exit_flag.store(true, Ordering::Release);
3160 thread_a.join().unwrap();
3161 thread_b.join().unwrap();
3162 thread_c.join().unwrap();
3163 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);