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};
23 use crate::ln::ChannelId;
24 use crate::ln::features::{InitFeatures, NodeFeatures};
26 use crate::ln::msgs::{ChannelMessageHandler, LightningError, SocketAddress, OnionMessageHandler, RoutingMessageHandler};
27 #[cfg(not(c_bindings))]
28 use crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
29 use crate::util::ser::{VecWriter, Writeable, Writer};
30 use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
32 use crate::ln::wire::{Encode, Type};
33 #[cfg(not(c_bindings))]
34 use crate::onion_message::{SimpleArcOnionMessenger, SimpleRefOnionMessenger};
35 use crate::onion_message::{CustomOnionMessageHandler, OffersMessage, OffersMessageHandler, OnionMessageContents, PendingOnionMessage};
36 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, NodeAlias};
37 use crate::util::atomic_counter::AtomicCounter;
38 use crate::util::logger::Logger;
39 use crate::util::string::PrintableString;
41 use crate::prelude::*;
43 use alloc::collections::LinkedList;
44 use crate::sync::{Arc, Mutex, MutexGuard, FairRwLock};
45 use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering};
46 use core::{cmp, hash, fmt, mem};
48 use core::convert::Infallible;
49 #[cfg(feature = "std")] use std::error;
51 use bitcoin::hashes::sha256::Hash as Sha256;
52 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
53 use bitcoin::hashes::{HashEngine, Hash};
55 /// A handler provided to [`PeerManager`] for reading and handling custom messages.
57 /// [BOLT 1] specifies a custom message type range for use with experimental or application-specific
58 /// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the
59 /// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler.
61 /// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md
62 /// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message
63 pub trait CustomMessageHandler: wire::CustomMessageReader {
64 /// Handles the given message sent from `sender_node_id`, possibly producing messages for
65 /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`]
67 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
69 /// Returns the list of pending messages that were generated by the handler, clearing the list
70 /// in the process. Each message is paired with the node id of the intended recipient. If no
71 /// connection to the node exists, then the message is simply not sent.
72 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
74 /// Gets the node feature flags which this handler itself supports. All available handlers are
75 /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`]
76 /// which are broadcasted in our [`NodeAnnouncement`] message.
78 /// [`NodeAnnouncement`]: crate::ln::msgs::NodeAnnouncement
79 fn provided_node_features(&self) -> NodeFeatures;
81 /// Gets the init feature flags which should be sent to the given peer. All available handlers
82 /// are queried similarly and their feature flags are OR'd together to form the [`InitFeatures`]
83 /// which are sent in our [`Init`] message.
85 /// [`Init`]: crate::ln::msgs::Init
86 fn provided_init_features(&self, their_node_id: &PublicKey) -> InitFeatures;
89 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
90 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
91 pub struct IgnoringMessageHandler{}
92 impl MessageSendEventsProvider for IgnoringMessageHandler {
93 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
95 impl RoutingMessageHandler for IgnoringMessageHandler {
96 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
97 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
98 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
99 fn get_next_channel_announcement(&self, _starting_point: u64) ->
100 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
101 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> { None }
102 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
103 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
104 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
105 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
106 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
107 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
108 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
109 InitFeatures::empty()
111 fn processing_queue_high(&self) -> bool { false }
113 impl OnionMessageHandler for IgnoringMessageHandler {
114 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
115 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
116 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
117 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
118 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
119 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
120 InitFeatures::empty()
123 impl OffersMessageHandler for IgnoringMessageHandler {
124 fn handle_message(&self, _msg: OffersMessage) -> Option<OffersMessage> { None }
126 impl CustomOnionMessageHandler for IgnoringMessageHandler {
127 type CustomMessage = Infallible;
128 fn handle_custom_message(&self, _msg: Infallible) -> Option<Infallible> {
129 // Since we always return `None` in the read the handle method should never be called.
132 fn read_custom_message<R: io::Read>(&self, _msg_type: u64, _buffer: &mut R) -> Result<Option<Infallible>, msgs::DecodeError> where Self: Sized {
135 fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Infallible>> {
140 impl OnionMessageContents for Infallible {
141 fn tlv_type(&self) -> u64 { unreachable!(); }
144 impl Deref for IgnoringMessageHandler {
145 type Target = IgnoringMessageHandler;
146 fn deref(&self) -> &Self { self }
149 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
150 // method that takes self for it.
151 impl wire::Type for Infallible {
152 fn type_id(&self) -> u16 {
156 impl Writeable for Infallible {
157 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
162 impl wire::CustomMessageReader for IgnoringMessageHandler {
163 type CustomMessage = Infallible;
164 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
169 impl CustomMessageHandler for IgnoringMessageHandler {
170 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
171 // Since we always return `None` in the read the handle method should never be called.
175 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
177 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
179 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
180 InitFeatures::empty()
184 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
185 /// You can provide one of these as the route_handler in a MessageHandler.
186 pub struct ErroringMessageHandler {
187 message_queue: Mutex<Vec<MessageSendEvent>>
189 impl ErroringMessageHandler {
190 /// Constructs a new ErroringMessageHandler
191 pub fn new() -> Self {
192 Self { message_queue: Mutex::new(Vec::new()) }
194 fn push_error(&self, node_id: &PublicKey, channel_id: ChannelId) {
195 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
196 action: msgs::ErrorAction::SendErrorMessage {
197 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
199 node_id: node_id.clone(),
203 impl MessageSendEventsProvider for ErroringMessageHandler {
204 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
205 let mut res = Vec::new();
206 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
210 impl ChannelMessageHandler for ErroringMessageHandler {
211 // Any messages which are related to a specific channel generate an error message to let the
212 // peer know we don't care about channels.
213 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
214 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
216 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
217 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
219 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
220 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
222 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
223 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
225 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
226 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
228 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) {
229 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
231 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
232 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
234 fn handle_stfu(&self, their_node_id: &PublicKey, msg: &msgs::Stfu) {
235 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
237 fn handle_splice(&self, their_node_id: &PublicKey, msg: &msgs::Splice) {
238 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
240 fn handle_splice_ack(&self, their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
241 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
243 fn handle_splice_locked(&self, their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
244 ErroringMessageHandler::push_error(&self, their_node_id, msg.channel_id);
246 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
247 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
249 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
250 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
252 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
253 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
255 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
256 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
258 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
259 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
261 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
262 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
264 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
265 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
267 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
268 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
270 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
271 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
273 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
274 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
275 fn peer_disconnected(&self, _their_node_id: &PublicKey) {}
276 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
277 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
278 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
279 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
280 // Set a number of features which various nodes may require to talk to us. It's totally
281 // reasonable to indicate we "support" all kinds of channel features...we just reject all
283 let mut features = InitFeatures::empty();
284 features.set_data_loss_protect_optional();
285 features.set_upfront_shutdown_script_optional();
286 features.set_variable_length_onion_optional();
287 features.set_static_remote_key_optional();
288 features.set_payment_secret_optional();
289 features.set_basic_mpp_optional();
290 features.set_wumbo_optional();
291 features.set_shutdown_any_segwit_optional();
292 features.set_channel_type_optional();
293 features.set_scid_privacy_optional();
294 features.set_zero_conf_optional();
298 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
299 // We don't enforce any chains upon peer connection for `ErroringMessageHandler` and leave it up
300 // to users of `ErroringMessageHandler` to make decisions on network compatiblility.
301 // There's not really any way to pull in specific networks here, and hardcoding can cause breakages.
305 fn handle_open_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
306 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
309 fn handle_accept_channel_v2(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
310 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
313 fn handle_tx_add_input(&self, their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
314 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
317 fn handle_tx_add_output(&self, their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
318 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
321 fn handle_tx_remove_input(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
322 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
325 fn handle_tx_remove_output(&self, their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
326 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
329 fn handle_tx_complete(&self, their_node_id: &PublicKey, msg: &msgs::TxComplete) {
330 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
333 fn handle_tx_signatures(&self, their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
334 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
337 fn handle_tx_init_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
338 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
341 fn handle_tx_ack_rbf(&self, their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
342 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
345 fn handle_tx_abort(&self, their_node_id: &PublicKey, msg: &msgs::TxAbort) {
346 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
350 impl Deref for ErroringMessageHandler {
351 type Target = ErroringMessageHandler;
352 fn deref(&self) -> &Self { self }
355 /// Provides references to trait impls which handle different types of messages.
356 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref, CustomM: Deref> where
357 CM::Target: ChannelMessageHandler,
358 RM::Target: RoutingMessageHandler,
359 OM::Target: OnionMessageHandler,
360 CustomM::Target: CustomMessageHandler,
362 /// A message handler which handles messages specific to channels. Usually this is just a
363 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
365 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
366 pub chan_handler: CM,
367 /// A message handler which handles messages updating our knowledge of the network channel
368 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
370 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
371 pub route_handler: RM,
373 /// A message handler which handles onion messages. This should generally be an
374 /// [`OnionMessenger`], but can also be an [`IgnoringMessageHandler`].
376 /// [`OnionMessenger`]: crate::onion_message::OnionMessenger
377 pub onion_message_handler: OM,
379 /// A message handler which handles custom messages. The only LDK-provided implementation is
380 /// [`IgnoringMessageHandler`].
381 pub custom_message_handler: CustomM,
384 /// Provides an object which can be used to send data to and which uniquely identifies a connection
385 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
386 /// implement Hash to meet the PeerManager API.
388 /// For efficiency, [`Clone`] should be relatively cheap for this type.
390 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
391 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
392 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
393 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
394 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
395 /// to simply use another value which is guaranteed to be globally unique instead.
396 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
397 /// Attempts to send some data from the given slice to the peer.
399 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
400 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
401 /// called and further write attempts may occur until that time.
403 /// If the returned size is smaller than `data.len()`, a
404 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
405 /// written. Additionally, until a `send_data` event completes fully, no further
406 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
407 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
410 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
411 /// (indicating that read events should be paused to prevent DoS in the send buffer),
412 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
413 /// `resume_read` of false carries no meaning, and should not cause any action.
414 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
415 /// Disconnect the socket pointed to by this SocketDescriptor.
417 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
418 /// call (doing so is a noop).
419 fn disconnect_socket(&mut self);
422 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
423 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
426 pub struct PeerHandleError { }
427 impl fmt::Debug for PeerHandleError {
428 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
429 formatter.write_str("Peer Sent Invalid Data")
432 impl fmt::Display for PeerHandleError {
433 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
434 formatter.write_str("Peer Sent Invalid Data")
438 #[cfg(feature = "std")]
439 impl error::Error for PeerHandleError {
440 fn description(&self) -> &str {
441 "Peer Sent Invalid Data"
445 enum InitSyncTracker{
447 ChannelsSyncing(u64),
448 NodesSyncing(NodeId),
451 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
452 /// forwarding gossip messages to peers altogether.
453 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
455 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
456 /// we have fewer than this many messages in the outbound buffer again.
457 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
458 /// refilled as we send bytes.
459 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
460 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
462 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
464 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
465 /// the socket receive buffer before receiving the ping.
467 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
468 /// including any network delays, outbound traffic, or the same for messages from other peers.
470 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
471 /// per connected peer to respond to a ping, as long as they send us at least one message during
472 /// each tick, ensuring we aren't actually just disconnected.
473 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
476 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
477 /// two connected peers, assuming most LDK-running systems have at least two cores.
478 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
480 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
481 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
482 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
483 /// process before the next ping.
485 /// Note that we continue responding to other messages even after we've sent this many messages, so
486 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
487 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
488 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
491 channel_encryptor: PeerChannelEncryptor,
492 /// We cache a `NodeId` here to avoid serializing peers' keys every time we forward gossip
493 /// messages in `PeerManager`. Use `Peer::set_their_node_id` to modify this field.
494 their_node_id: Option<(PublicKey, NodeId)>,
495 /// The features provided in the peer's [`msgs::Init`] message.
497 /// This is set only after we've processed the [`msgs::Init`] message and called relevant
498 /// `peer_connected` handler methods. Thus, this field is set *iff* we've finished our
499 /// handshake and can talk to this peer normally (though use [`Peer::handshake_complete`] to
501 their_features: Option<InitFeatures>,
502 their_socket_address: Option<SocketAddress>,
504 pending_outbound_buffer: LinkedList<Vec<u8>>,
505 pending_outbound_buffer_first_msg_offset: usize,
506 /// Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily
507 /// prioritize channel messages over them.
509 /// Note that these messages are *not* encrypted/MAC'd, and are only serialized.
510 gossip_broadcast_buffer: LinkedList<Vec<u8>>,
511 awaiting_write_event: bool,
513 pending_read_buffer: Vec<u8>,
514 pending_read_buffer_pos: usize,
515 pending_read_is_header: bool,
517 sync_status: InitSyncTracker,
519 msgs_sent_since_pong: usize,
520 awaiting_pong_timer_tick_intervals: i64,
521 received_message_since_timer_tick: bool,
522 sent_gossip_timestamp_filter: bool,
524 /// Indicates we've received a `channel_announcement` since the last time we had
525 /// [`PeerManager::gossip_processing_backlogged`] set (or, really, that we've received a
526 /// `channel_announcement` at all - we set this unconditionally but unset it every time we
527 /// check if we're gossip-processing-backlogged).
528 received_channel_announce_since_backlogged: bool,
530 inbound_connection: bool,
534 /// True after we've processed the [`msgs::Init`] message and called relevant `peer_connected`
535 /// handler methods. Thus, this implies we've finished our handshake and can talk to this peer
537 fn handshake_complete(&self) -> bool {
538 self.their_features.is_some()
541 /// Returns true if the channel announcements/updates for the given channel should be
542 /// forwarded to this peer.
543 /// If we are sending our routing table to this peer and we have not yet sent channel
544 /// announcements/updates for the given channel_id then we will send it when we get to that
545 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
546 /// sent the old versions, we should send the update, and so return true here.
547 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
548 if !self.handshake_complete() { return false; }
549 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
550 !self.sent_gossip_timestamp_filter {
553 match self.sync_status {
554 InitSyncTracker::NoSyncRequested => true,
555 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
556 InitSyncTracker::NodesSyncing(_) => true,
560 /// Similar to the above, but for node announcements indexed by node_id.
561 fn should_forward_node_announcement(&self, node_id: NodeId) -> bool {
562 if !self.handshake_complete() { return false; }
563 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
564 !self.sent_gossip_timestamp_filter {
567 match self.sync_status {
568 InitSyncTracker::NoSyncRequested => true,
569 InitSyncTracker::ChannelsSyncing(_) => false,
570 InitSyncTracker::NodesSyncing(sync_node_id) => sync_node_id.as_slice() < node_id.as_slice(),
574 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
575 /// buffer still has space and we don't need to pause reads to get some writes out.
576 fn should_read(&mut self, gossip_processing_backlogged: bool) -> bool {
577 if !gossip_processing_backlogged {
578 self.received_channel_announce_since_backlogged = false;
580 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE &&
581 (!gossip_processing_backlogged || !self.received_channel_announce_since_backlogged)
584 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
585 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
586 fn should_buffer_gossip_backfill(&self) -> bool {
587 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
588 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
589 && self.handshake_complete()
592 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
593 /// every time the peer's buffer may have been drained.
594 fn should_buffer_onion_message(&self) -> bool {
595 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
596 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
599 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
600 /// buffer. This is checked every time the peer's buffer may have been drained.
601 fn should_buffer_gossip_broadcast(&self) -> bool {
602 self.pending_outbound_buffer.is_empty() && self.handshake_complete()
603 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
606 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
607 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
608 let total_outbound_buffered =
609 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
611 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
612 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
615 fn set_their_node_id(&mut self, node_id: PublicKey) {
616 self.their_node_id = Some((node_id, NodeId::from_pubkey(&node_id)));
620 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
621 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
622 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
623 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
624 /// issues such as overly long function definitions.
626 /// This is not exported to bindings users as type aliases aren't supported in most languages.
627 #[cfg(not(c_bindings))]
628 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<
630 Arc<SimpleArcChannelManager<M, T, F, L>>,
631 Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, C, Arc<L>>>,
632 Arc<SimpleArcOnionMessenger<M, T, F, L>>,
634 IgnoringMessageHandler,
638 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
639 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
640 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
641 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
642 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
643 /// helps with issues such as long function definitions.
645 /// This is not exported to bindings users as type aliases aren't supported in most languages.
646 #[cfg(not(c_bindings))]
647 pub type SimpleRefPeerManager<
648 'a, 'b, 'c, 'd, 'e, 'f, 'logger, 'h, 'i, 'j, 'graph, 'k, SD, M, T, F, C, L
651 &'j SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, M, T, F, L>,
652 &'f P2PGossipSync<&'graph NetworkGraph<&'logger L>, C, &'logger L>,
653 &'h SimpleRefOnionMessenger<'a, 'b, 'c, 'd, 'e, 'graph, 'logger, 'i, 'j, 'k, M, T, F, L>,
655 IgnoringMessageHandler,
660 /// A generic trait which is implemented for all [`PeerManager`]s. This makes bounding functions or
661 /// structs on any [`PeerManager`] much simpler as only this trait is needed as a bound, rather
662 /// than the full set of bounds on [`PeerManager`] itself.
664 /// This is not exported to bindings users as general cover traits aren't useful in other
666 #[allow(missing_docs)]
667 pub trait APeerManager {
668 type Descriptor: SocketDescriptor;
669 type CMT: ChannelMessageHandler + ?Sized;
670 type CM: Deref<Target=Self::CMT>;
671 type RMT: RoutingMessageHandler + ?Sized;
672 type RM: Deref<Target=Self::RMT>;
673 type OMT: OnionMessageHandler + ?Sized;
674 type OM: Deref<Target=Self::OMT>;
675 type LT: Logger + ?Sized;
676 type L: Deref<Target=Self::LT>;
677 type CMHT: CustomMessageHandler + ?Sized;
678 type CMH: Deref<Target=Self::CMHT>;
679 type NST: NodeSigner + ?Sized;
680 type NS: Deref<Target=Self::NST>;
681 /// Gets a reference to the underlying [`PeerManager`].
682 fn as_ref(&self) -> &PeerManager<Self::Descriptor, Self::CM, Self::RM, Self::OM, Self::L, Self::CMH, Self::NS>;
685 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref>
686 APeerManager for PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
687 CM::Target: ChannelMessageHandler,
688 RM::Target: RoutingMessageHandler,
689 OM::Target: OnionMessageHandler,
691 CMH::Target: CustomMessageHandler,
692 NS::Target: NodeSigner,
694 type Descriptor = Descriptor;
695 type CMT = <CM as Deref>::Target;
697 type RMT = <RM as Deref>::Target;
699 type OMT = <OM as Deref>::Target;
701 type LT = <L as Deref>::Target;
703 type CMHT = <CMH as Deref>::Target;
705 type NST = <NS as Deref>::Target;
707 fn as_ref(&self) -> &PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> { self }
710 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
711 /// socket events into messages which it passes on to its [`MessageHandler`].
713 /// Locks are taken internally, so you must never assume that reentrancy from a
714 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
716 /// Calls to [`read_event`] will decode relevant messages and pass them to the
717 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
718 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
719 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
720 /// calls only after previous ones have returned.
722 /// Rather than using a plain [`PeerManager`], it is preferable to use either a [`SimpleArcPeerManager`]
723 /// a [`SimpleRefPeerManager`], for conciseness. See their documentation for more details, but
724 /// essentially you should default to using a [`SimpleRefPeerManager`], and use a
725 /// [`SimpleArcPeerManager`] when you require a `PeerManager` with a static lifetime, such as when
726 /// you're using lightning-net-tokio.
728 /// [`read_event`]: PeerManager::read_event
729 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> where
730 CM::Target: ChannelMessageHandler,
731 RM::Target: RoutingMessageHandler,
732 OM::Target: OnionMessageHandler,
734 CMH::Target: CustomMessageHandler,
735 NS::Target: NodeSigner {
736 message_handler: MessageHandler<CM, RM, OM, CMH>,
737 /// Connection state for each connected peer - we have an outer read-write lock which is taken
738 /// as read while we're doing processing for a peer and taken write when a peer is being added
741 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
742 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
743 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
744 /// the `MessageHandler`s for a given peer is already guaranteed.
745 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
746 /// Only add to this set when noise completes.
747 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
748 /// lock held. Entries may be added with only the `peers` read lock held (though the
749 /// `Descriptor` value must already exist in `peers`).
750 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
751 /// We can only have one thread processing events at once, but if a second call to
752 /// `process_events` happens while a first call is in progress, one of the two calls needs to
753 /// start from the top to ensure any new messages are also handled.
755 /// Because the event handler calls into user code which may block, we don't want to block a
756 /// second thread waiting for another thread to handle events which is then blocked on user
757 /// code, so we store an atomic counter here:
758 /// * 0 indicates no event processor is running
759 /// * 1 indicates an event processor is running
760 /// * > 1 indicates an event processor is running but needs to start again from the top once
761 /// it finishes as another thread tried to start processing events but returned early.
762 event_processing_state: AtomicI32,
764 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
765 /// value increases strictly since we don't assume access to a time source.
766 last_node_announcement_serial: AtomicU32,
768 ephemeral_key_midstate: Sha256Engine,
770 peer_counter: AtomicCounter,
772 gossip_processing_backlogged: AtomicBool,
773 gossip_processing_backlog_lifted: AtomicBool,
778 secp_ctx: Secp256k1<secp256k1::SignOnly>
781 enum MessageHandlingError {
782 PeerHandleError(PeerHandleError),
783 LightningError(LightningError),
786 impl From<PeerHandleError> for MessageHandlingError {
787 fn from(error: PeerHandleError) -> Self {
788 MessageHandlingError::PeerHandleError(error)
792 impl From<LightningError> for MessageHandlingError {
793 fn from(error: LightningError) -> Self {
794 MessageHandlingError::LightningError(error)
798 macro_rules! encode_msg {
800 let mut buffer = VecWriter(Vec::new());
801 wire::write($msg, &mut buffer).unwrap();
806 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler, NS> where
807 CM::Target: ChannelMessageHandler,
808 OM::Target: OnionMessageHandler,
810 NS::Target: NodeSigner {
811 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
812 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
815 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
816 /// cryptographically secure random bytes.
818 /// `current_time` is used as an always-increasing counter that survives across restarts and is
819 /// incremented irregularly internally. In general it is best to simply use the current UNIX
820 /// timestamp, however if it is not available a persistent counter that increases once per
821 /// minute should suffice.
823 /// This is not exported to bindings users as we can't export a PeerManager with a dummy route handler
824 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 {
825 Self::new(MessageHandler {
826 chan_handler: channel_message_handler,
827 route_handler: IgnoringMessageHandler{},
828 onion_message_handler,
829 custom_message_handler: IgnoringMessageHandler{},
830 }, current_time, ephemeral_random_data, logger, node_signer)
834 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref, NS: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler, NS> where
835 RM::Target: RoutingMessageHandler,
837 NS::Target: NodeSigner {
838 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
839 /// handler or onion message handler is used and onion and channel messages will be ignored (or
840 /// generate error messages). Note that some other lightning implementations time-out connections
841 /// after some time if no channel is built with the peer.
843 /// `current_time` is used as an always-increasing counter that survives across restarts and is
844 /// incremented irregularly internally. In general it is best to simply use the current UNIX
845 /// timestamp, however if it is not available a persistent counter that increases once per
846 /// minute should suffice.
848 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
849 /// cryptographically secure random bytes.
851 /// This is not exported to bindings users as we can't export a PeerManager with a dummy channel handler
852 pub fn new_routing_only(routing_message_handler: RM, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
853 Self::new(MessageHandler {
854 chan_handler: ErroringMessageHandler::new(),
855 route_handler: routing_message_handler,
856 onion_message_handler: IgnoringMessageHandler{},
857 custom_message_handler: IgnoringMessageHandler{},
858 }, current_time, ephemeral_random_data, logger, node_signer)
862 /// A simple wrapper that optionally prints ` from <pubkey>` for an optional pubkey.
863 /// This works around `format!()` taking a reference to each argument, preventing
864 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
865 /// due to lifetime errors.
866 struct OptionalFromDebugger<'a>(&'a Option<(PublicKey, NodeId)>);
867 impl core::fmt::Display for OptionalFromDebugger<'_> {
868 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
869 if let Some((node_id, _)) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
873 /// A function used to filter out local or private addresses
874 /// <https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml>
875 /// <https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml>
876 fn filter_addresses(ip_address: Option<SocketAddress>) -> Option<SocketAddress> {
878 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
879 Some(SocketAddress::TcpIpV4{addr: [10, _, _, _], port: _}) => None,
880 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
881 Some(SocketAddress::TcpIpV4{addr: [0, _, _, _], port: _}) => None,
882 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
883 Some(SocketAddress::TcpIpV4{addr: [100, 64..=127, _, _], port: _}) => None,
884 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
885 Some(SocketAddress::TcpIpV4{addr: [127, _, _, _], port: _}) => None,
886 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
887 Some(SocketAddress::TcpIpV4{addr: [169, 254, _, _], port: _}) => None,
888 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
889 Some(SocketAddress::TcpIpV4{addr: [172, 16..=31, _, _], port: _}) => None,
890 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
891 Some(SocketAddress::TcpIpV4{addr: [192, 168, _, _], port: _}) => None,
892 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
893 Some(SocketAddress::TcpIpV4{addr: [192, 88, 99, _], port: _}) => None,
894 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
895 Some(SocketAddress::TcpIpV6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
896 // For remaining addresses
897 Some(SocketAddress::TcpIpV6{addr: _, port: _}) => None,
898 Some(..) => ip_address,
903 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref, NS: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH, NS> where
904 CM::Target: ChannelMessageHandler,
905 RM::Target: RoutingMessageHandler,
906 OM::Target: OnionMessageHandler,
908 CMH::Target: CustomMessageHandler,
909 NS::Target: NodeSigner
911 /// Constructs a new `PeerManager` with the given message handlers.
913 /// `ephemeral_random_data` is used to derive per-connection ephemeral keys and must be
914 /// cryptographically secure random bytes.
916 /// `current_time` is used as an always-increasing counter that survives across restarts and is
917 /// incremented irregularly internally. In general it is best to simply use the current UNIX
918 /// timestamp, however if it is not available a persistent counter that increases once per
919 /// minute should suffice.
920 pub fn new(message_handler: MessageHandler<CM, RM, OM, CMH>, current_time: u32, ephemeral_random_data: &[u8; 32], logger: L, node_signer: NS) -> Self {
921 let mut ephemeral_key_midstate = Sha256::engine();
922 ephemeral_key_midstate.input(ephemeral_random_data);
924 let mut secp_ctx = Secp256k1::signing_only();
925 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
926 secp_ctx.seeded_randomize(&ephemeral_hash);
930 peers: FairRwLock::new(HashMap::new()),
931 node_id_to_descriptor: Mutex::new(HashMap::new()),
932 event_processing_state: AtomicI32::new(0),
933 ephemeral_key_midstate,
934 peer_counter: AtomicCounter::new(),
935 gossip_processing_backlogged: AtomicBool::new(false),
936 gossip_processing_backlog_lifted: AtomicBool::new(false),
937 last_node_announcement_serial: AtomicU32::new(current_time),
944 /// Get a list of tuples mapping from node id to network addresses for peers which have
945 /// completed the initial handshake.
947 /// For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter
948 /// passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial
949 /// handshake has completed and we are sure the remote peer has the private key for the given
952 /// The returned `Option`s will only be `Some` if an address had been previously given via
953 /// [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`].
954 pub fn get_peer_node_ids(&self) -> Vec<(PublicKey, Option<SocketAddress>)> {
955 let peers = self.peers.read().unwrap();
956 peers.values().filter_map(|peer_mutex| {
957 let p = peer_mutex.lock().unwrap();
958 if !p.handshake_complete() {
961 Some((p.their_node_id.unwrap().0, p.their_socket_address.clone()))
965 fn get_ephemeral_key(&self) -> SecretKey {
966 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
967 let counter = self.peer_counter.get_increment();
968 ephemeral_hash.input(&counter.to_le_bytes());
969 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
972 fn init_features(&self, their_node_id: &PublicKey) -> InitFeatures {
973 self.message_handler.chan_handler.provided_init_features(their_node_id)
974 | self.message_handler.route_handler.provided_init_features(their_node_id)
975 | self.message_handler.onion_message_handler.provided_init_features(their_node_id)
976 | self.message_handler.custom_message_handler.provided_init_features(their_node_id)
979 /// Indicates a new outbound connection has been established to a node with the given `node_id`
980 /// and an optional remote network address.
982 /// The remote network address adds the option to report a remote IP address back to a connecting
983 /// peer using the init message.
984 /// The user should pass the remote network address of the host they are connected to.
986 /// If an `Err` is returned here you must disconnect the connection immediately.
988 /// Returns a small number of bytes to send to the remote node (currently always 50).
990 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
991 /// [`socket_disconnected`].
993 /// [`socket_disconnected`]: PeerManager::socket_disconnected
994 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<Vec<u8>, PeerHandleError> {
995 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
996 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
997 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
999 let mut peers = self.peers.write().unwrap();
1000 match peers.entry(descriptor) {
1001 hash_map::Entry::Occupied(_) => {
1002 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1003 Err(PeerHandleError {})
1005 hash_map::Entry::Vacant(e) => {
1006 e.insert(Mutex::new(Peer {
1007 channel_encryptor: peer_encryptor,
1008 their_node_id: None,
1009 their_features: None,
1010 their_socket_address: remote_network_address,
1012 pending_outbound_buffer: LinkedList::new(),
1013 pending_outbound_buffer_first_msg_offset: 0,
1014 gossip_broadcast_buffer: LinkedList::new(),
1015 awaiting_write_event: false,
1017 pending_read_buffer,
1018 pending_read_buffer_pos: 0,
1019 pending_read_is_header: false,
1021 sync_status: InitSyncTracker::NoSyncRequested,
1023 msgs_sent_since_pong: 0,
1024 awaiting_pong_timer_tick_intervals: 0,
1025 received_message_since_timer_tick: false,
1026 sent_gossip_timestamp_filter: false,
1028 received_channel_announce_since_backlogged: false,
1029 inbound_connection: false,
1036 /// Indicates a new inbound connection has been established to a node with an optional remote
1037 /// network address.
1039 /// The remote network address adds the option to report a remote IP address back to a connecting
1040 /// peer using the init message.
1041 /// The user should pass the remote network address of the host they are connected to.
1043 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
1044 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
1045 /// the connection immediately.
1047 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
1048 /// [`socket_disconnected`].
1050 /// [`socket_disconnected`]: PeerManager::socket_disconnected
1051 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<SocketAddress>) -> Result<(), PeerHandleError> {
1052 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.node_signer);
1053 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
1055 let mut peers = self.peers.write().unwrap();
1056 match peers.entry(descriptor) {
1057 hash_map::Entry::Occupied(_) => {
1058 debug_assert!(false, "PeerManager driver duplicated descriptors!");
1059 Err(PeerHandleError {})
1061 hash_map::Entry::Vacant(e) => {
1062 e.insert(Mutex::new(Peer {
1063 channel_encryptor: peer_encryptor,
1064 their_node_id: None,
1065 their_features: None,
1066 their_socket_address: remote_network_address,
1068 pending_outbound_buffer: LinkedList::new(),
1069 pending_outbound_buffer_first_msg_offset: 0,
1070 gossip_broadcast_buffer: LinkedList::new(),
1071 awaiting_write_event: false,
1073 pending_read_buffer,
1074 pending_read_buffer_pos: 0,
1075 pending_read_is_header: false,
1077 sync_status: InitSyncTracker::NoSyncRequested,
1079 msgs_sent_since_pong: 0,
1080 awaiting_pong_timer_tick_intervals: 0,
1081 received_message_since_timer_tick: false,
1082 sent_gossip_timestamp_filter: false,
1084 received_channel_announce_since_backlogged: false,
1085 inbound_connection: true,
1092 fn peer_should_read(&self, peer: &mut Peer) -> bool {
1093 peer.should_read(self.gossip_processing_backlogged.load(Ordering::Relaxed))
1096 fn update_gossip_backlogged(&self) {
1097 let new_state = self.message_handler.route_handler.processing_queue_high();
1098 let prev_state = self.gossip_processing_backlogged.swap(new_state, Ordering::Relaxed);
1099 if prev_state && !new_state {
1100 self.gossip_processing_backlog_lifted.store(true, Ordering::Relaxed);
1104 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer, force_one_write: bool) {
1105 let mut have_written = false;
1106 while !peer.awaiting_write_event {
1107 if peer.should_buffer_onion_message() {
1108 if let Some((peer_node_id, _)) = peer.their_node_id {
1109 if let Some(next_onion_message) =
1110 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
1111 self.enqueue_message(peer, &next_onion_message);
1115 if peer.should_buffer_gossip_broadcast() {
1116 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
1117 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_buffer(&msg[..]));
1120 if peer.should_buffer_gossip_backfill() {
1121 match peer.sync_status {
1122 InitSyncTracker::NoSyncRequested => {},
1123 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
1124 if let Some((announce, update_a_option, update_b_option)) =
1125 self.message_handler.route_handler.get_next_channel_announcement(c)
1127 self.enqueue_message(peer, &announce);
1128 if let Some(update_a) = update_a_option {
1129 self.enqueue_message(peer, &update_a);
1131 if let Some(update_b) = update_b_option {
1132 self.enqueue_message(peer, &update_b);
1134 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
1136 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
1139 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
1140 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
1141 self.enqueue_message(peer, &msg);
1142 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1144 peer.sync_status = InitSyncTracker::NoSyncRequested;
1147 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
1148 InitSyncTracker::NodesSyncing(sync_node_id) => {
1149 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&sync_node_id)) {
1150 self.enqueue_message(peer, &msg);
1151 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
1153 peer.sync_status = InitSyncTracker::NoSyncRequested;
1158 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
1159 self.maybe_send_extra_ping(peer);
1162 let should_read = self.peer_should_read(peer);
1163 let next_buff = match peer.pending_outbound_buffer.front() {
1165 if force_one_write && !have_written {
1167 let data_sent = descriptor.send_data(&[], should_read);
1168 debug_assert_eq!(data_sent, 0, "Can't write more than no data");
1176 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
1177 let data_sent = descriptor.send_data(pending, should_read);
1178 have_written = true;
1179 peer.pending_outbound_buffer_first_msg_offset += data_sent;
1180 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
1181 peer.pending_outbound_buffer_first_msg_offset = 0;
1182 peer.pending_outbound_buffer.pop_front();
1184 peer.awaiting_write_event = true;
1189 /// Indicates that there is room to write data to the given socket descriptor.
1191 /// May return an Err to indicate that the connection should be closed.
1193 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
1194 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
1195 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
1196 /// ready to call [`write_buffer_space_avail`] again if a write call generated here isn't
1199 /// [`send_data`]: SocketDescriptor::send_data
1200 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
1201 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
1202 let peers = self.peers.read().unwrap();
1203 match peers.get(descriptor) {
1205 // This is most likely a simple race condition where the user found that the socket
1206 // was writeable, then we told the user to `disconnect_socket()`, then they called
1207 // this method. Return an error to make sure we get disconnected.
1208 return Err(PeerHandleError { });
1210 Some(peer_mutex) => {
1211 let mut peer = peer_mutex.lock().unwrap();
1212 peer.awaiting_write_event = false;
1213 self.do_attempt_write_data(descriptor, &mut peer, false);
1219 /// Indicates that data was read from the given socket descriptor.
1221 /// May return an Err to indicate that the connection should be closed.
1223 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
1224 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
1225 /// [`send_data`] calls to handle responses.
1227 /// If `Ok(true)` is returned, further read_events should not be triggered until a
1228 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
1231 /// In order to avoid processing too many messages at once per peer, `data` should be on the
1234 /// [`send_data`]: SocketDescriptor::send_data
1235 /// [`process_events`]: PeerManager::process_events
1236 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1237 match self.do_read_event(peer_descriptor, data) {
1240 log_trace!(self.logger, "Disconnecting peer due to a protocol error (usually a duplicate connection).");
1241 self.disconnect_event_internal(peer_descriptor);
1247 /// Append a message to a peer's pending outbound/write buffer
1248 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
1249 if is_gossip_msg(message.type_id()) {
1250 log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0));
1252 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap().0))
1254 peer.msgs_sent_since_pong += 1;
1255 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(message));
1258 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
1259 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: Vec<u8>) {
1260 peer.msgs_sent_since_pong += 1;
1261 peer.gossip_broadcast_buffer.push_back(encoded_message);
1264 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
1265 let mut pause_read = false;
1266 let peers = self.peers.read().unwrap();
1267 let mut msgs_to_forward = Vec::new();
1268 let mut peer_node_id = None;
1269 match peers.get(peer_descriptor) {
1271 // This is most likely a simple race condition where the user read some bytes
1272 // from the socket, then we told the user to `disconnect_socket()`, then they
1273 // called this method. Return an error to make sure we get disconnected.
1274 return Err(PeerHandleError { });
1276 Some(peer_mutex) => {
1277 let mut read_pos = 0;
1278 while read_pos < data.len() {
1279 macro_rules! try_potential_handleerror {
1280 ($peer: expr, $thing: expr) => {
1285 msgs::ErrorAction::DisconnectPeer { .. } => {
1286 // We may have an `ErrorMessage` to send to the peer,
1287 // but writing to the socket while reading can lead to
1288 // re-entrant code and possibly unexpected behavior. The
1289 // message send is optimistic anyway, and in this case
1290 // we immediately disconnect the peer.
1291 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1292 return Err(PeerHandleError { });
1294 msgs::ErrorAction::DisconnectPeerWithWarning { .. } => {
1295 // We have a `WarningMessage` to send to the peer, but
1296 // writing to the socket while reading can lead to
1297 // re-entrant code and possibly unexpected behavior. The
1298 // message send is optimistic anyway, and in this case
1299 // we immediately disconnect the peer.
1300 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1301 return Err(PeerHandleError { });
1303 msgs::ErrorAction::IgnoreAndLog(level) => {
1304 log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1307 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
1308 msgs::ErrorAction::IgnoreError => {
1309 log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
1312 msgs::ErrorAction::SendErrorMessage { msg } => {
1313 log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1314 self.enqueue_message($peer, &msg);
1317 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
1318 log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1319 self.enqueue_message($peer, &msg);
1328 let mut peer_lock = peer_mutex.lock().unwrap();
1329 let peer = &mut *peer_lock;
1330 let mut msg_to_handle = None;
1331 if peer_node_id.is_none() {
1332 peer_node_id = peer.their_node_id.clone();
1335 assert!(peer.pending_read_buffer.len() > 0);
1336 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1339 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1340 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]);
1341 read_pos += data_to_copy;
1342 peer.pending_read_buffer_pos += data_to_copy;
1345 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1346 peer.pending_read_buffer_pos = 0;
1348 macro_rules! insert_node_id {
1350 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap().0) {
1351 hash_map::Entry::Occupied(e) => {
1352 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap().0));
1353 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1354 // Check that the peers map is consistent with the
1355 // node_id_to_descriptor map, as this has been broken
1357 debug_assert!(peers.get(e.get()).is_some());
1358 return Err(PeerHandleError { })
1360 hash_map::Entry::Vacant(entry) => {
1361 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap().0));
1362 entry.insert(peer_descriptor.clone())
1368 let next_step = peer.channel_encryptor.get_noise_step();
1370 NextNoiseStep::ActOne => {
1371 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1372 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1373 &self.node_signer, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1374 peer.pending_outbound_buffer.push_back(act_two);
1375 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1377 NextNoiseStep::ActTwo => {
1378 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1379 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1380 &self.node_signer));
1381 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1382 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1383 peer.pending_read_is_header = true;
1385 peer.set_their_node_id(their_node_id);
1387 let features = self.init_features(&their_node_id);
1388 let networks = self.message_handler.chan_handler.get_chain_hashes();
1389 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1390 self.enqueue_message(peer, &resp);
1391 peer.awaiting_pong_timer_tick_intervals = 0;
1393 NextNoiseStep::ActThree => {
1394 let their_node_id = try_potential_handleerror!(peer,
1395 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1396 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1397 peer.pending_read_is_header = true;
1398 peer.set_their_node_id(their_node_id);
1400 let features = self.init_features(&their_node_id);
1401 let networks = self.message_handler.chan_handler.get_chain_hashes();
1402 let resp = msgs::Init { features, networks, remote_network_address: filter_addresses(peer.their_socket_address.clone()) };
1403 self.enqueue_message(peer, &resp);
1404 peer.awaiting_pong_timer_tick_intervals = 0;
1406 NextNoiseStep::NoiseComplete => {
1407 if peer.pending_read_is_header {
1408 let msg_len = try_potential_handleerror!(peer,
1409 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1410 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1411 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1412 if msg_len < 2 { // Need at least the message type tag
1413 return Err(PeerHandleError { });
1415 peer.pending_read_is_header = false;
1417 let msg_data = try_potential_handleerror!(peer,
1418 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1419 assert!(msg_data.len() >= 2);
1421 // Reset read buffer
1422 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1423 peer.pending_read_buffer.resize(18, 0);
1424 peer.pending_read_is_header = true;
1426 let mut reader = io::Cursor::new(&msg_data[..]);
1427 let message_result = wire::read(&mut reader, &*self.message_handler.custom_message_handler);
1428 let message = match message_result {
1432 // Note that to avoid re-entrancy we never call
1433 // `do_attempt_write_data` from here, causing
1434 // the messages enqueued here to not actually
1435 // be sent before the peer is disconnected.
1436 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1437 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1440 (msgs::DecodeError::UnsupportedCompression, _) => {
1441 log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1442 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: ChannelId::new_zero(), data: "Unsupported message compression: zlib".to_owned() });
1445 (_, Some(ty)) if is_gossip_msg(ty) => {
1446 log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1447 self.enqueue_message(peer, &msgs::WarningMessage {
1448 channel_id: ChannelId::new_zero(),
1449 data: format!("Unreadable/bogus gossip message of type {}", ty),
1453 (msgs::DecodeError::UnknownRequiredFeature, _) => {
1454 log_debug!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1455 return Err(PeerHandleError { });
1457 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { }),
1458 (msgs::DecodeError::InvalidValue, _) => {
1459 log_debug!(self.logger, "Got an invalid value while deserializing message");
1460 return Err(PeerHandleError { });
1462 (msgs::DecodeError::ShortRead, _) => {
1463 log_debug!(self.logger, "Deserialization failed due to shortness of message");
1464 return Err(PeerHandleError { });
1466 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { }),
1467 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { }),
1472 msg_to_handle = Some(message);
1477 pause_read = !self.peer_should_read(peer);
1479 if let Some(message) = msg_to_handle {
1480 match self.handle_message(&peer_mutex, peer_lock, message) {
1481 Err(handling_error) => match handling_error {
1482 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1483 MessageHandlingError::LightningError(e) => {
1484 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1488 msgs_to_forward.push(msg);
1497 for msg in msgs_to_forward.drain(..) {
1498 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref().map(|(pk, _)| pk));
1504 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1505 /// Returns the message back if it needs to be broadcasted to all other peers.
1508 peer_mutex: &Mutex<Peer>,
1509 mut peer_lock: MutexGuard<Peer>,
1510 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1511 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1512 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;
1513 peer_lock.received_message_since_timer_tick = true;
1515 // Need an Init as first message
1516 if let wire::Message::Init(msg) = message {
1517 // Check if we have any compatible chains if the `networks` field is specified.
1518 if let Some(networks) = &msg.networks {
1519 if let Some(our_chains) = self.message_handler.chan_handler.get_chain_hashes() {
1520 let mut have_compatible_chains = false;
1521 'our_chains: for our_chain in our_chains.iter() {
1522 for their_chain in networks {
1523 if our_chain == their_chain {
1524 have_compatible_chains = true;
1529 if !have_compatible_chains {
1530 log_debug!(self.logger, "Peer does not support any of our supported chains");
1531 return Err(PeerHandleError { }.into());
1536 let our_features = self.init_features(&their_node_id);
1537 if msg.features.requires_unknown_bits_from(&our_features) {
1538 log_debug!(self.logger, "Peer requires features unknown to us");
1539 return Err(PeerHandleError { }.into());
1542 if our_features.requires_unknown_bits_from(&msg.features) {
1543 log_debug!(self.logger, "We require features unknown to our peer");
1544 return Err(PeerHandleError { }.into());
1547 if peer_lock.their_features.is_some() {
1548 return Err(PeerHandleError { }.into());
1551 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1553 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1554 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1555 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1558 if let Err(()) = self.message_handler.route_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1559 log_debug!(self.logger, "Route Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1560 return Err(PeerHandleError { }.into());
1562 if let Err(()) = self.message_handler.chan_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1563 log_debug!(self.logger, "Channel Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1564 return Err(PeerHandleError { }.into());
1566 if let Err(()) = self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg, peer_lock.inbound_connection) {
1567 log_debug!(self.logger, "Onion Message Handler decided we couldn't communicate with peer {}", log_pubkey!(their_node_id));
1568 return Err(PeerHandleError { }.into());
1571 peer_lock.their_features = Some(msg.features);
1573 } else if peer_lock.their_features.is_none() {
1574 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1575 return Err(PeerHandleError { }.into());
1578 if let wire::Message::GossipTimestampFilter(_msg) = message {
1579 // When supporting gossip messages, start inital gossip sync only after we receive
1580 // a GossipTimestampFilter
1581 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1582 !peer_lock.sent_gossip_timestamp_filter {
1583 peer_lock.sent_gossip_timestamp_filter = true;
1584 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1589 if let wire::Message::ChannelAnnouncement(ref _msg) = message {
1590 peer_lock.received_channel_announce_since_backlogged = true;
1593 mem::drop(peer_lock);
1595 if is_gossip_msg(message.type_id()) {
1596 log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1598 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1601 let mut should_forward = None;
1604 // Setup and Control messages:
1605 wire::Message::Init(_) => {
1608 wire::Message::GossipTimestampFilter(_) => {
1611 wire::Message::Error(msg) => {
1612 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1613 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1614 if msg.channel_id.is_zero() {
1615 return Err(PeerHandleError { }.into());
1618 wire::Message::Warning(msg) => {
1619 log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), PrintableString(&msg.data));
1622 wire::Message::Ping(msg) => {
1623 if msg.ponglen < 65532 {
1624 let resp = msgs::Pong { byteslen: msg.ponglen };
1625 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1628 wire::Message::Pong(_msg) => {
1629 let mut peer_lock = peer_mutex.lock().unwrap();
1630 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1631 peer_lock.msgs_sent_since_pong = 0;
1634 // Channel messages:
1635 wire::Message::OpenChannel(msg) => {
1636 self.message_handler.chan_handler.handle_open_channel(&their_node_id, &msg);
1638 wire::Message::OpenChannelV2(msg) => {
1639 self.message_handler.chan_handler.handle_open_channel_v2(&their_node_id, &msg);
1641 wire::Message::AcceptChannel(msg) => {
1642 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, &msg);
1644 wire::Message::AcceptChannelV2(msg) => {
1645 self.message_handler.chan_handler.handle_accept_channel_v2(&their_node_id, &msg);
1648 wire::Message::FundingCreated(msg) => {
1649 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1651 wire::Message::FundingSigned(msg) => {
1652 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1654 wire::Message::ChannelReady(msg) => {
1655 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1658 // Quiescence messages:
1659 wire::Message::Stfu(msg) => {
1660 self.message_handler.chan_handler.handle_stfu(&their_node_id, &msg);
1663 // Splicing messages:
1664 wire::Message::Splice(msg) => {
1665 self.message_handler.chan_handler.handle_splice(&their_node_id, &msg);
1667 wire::Message::SpliceAck(msg) => {
1668 self.message_handler.chan_handler.handle_splice_ack(&their_node_id, &msg);
1670 wire::Message::SpliceLocked(msg) => {
1671 self.message_handler.chan_handler.handle_splice_locked(&their_node_id, &msg);
1674 // Interactive transaction construction messages:
1675 wire::Message::TxAddInput(msg) => {
1676 self.message_handler.chan_handler.handle_tx_add_input(&their_node_id, &msg);
1678 wire::Message::TxAddOutput(msg) => {
1679 self.message_handler.chan_handler.handle_tx_add_output(&their_node_id, &msg);
1681 wire::Message::TxRemoveInput(msg) => {
1682 self.message_handler.chan_handler.handle_tx_remove_input(&their_node_id, &msg);
1684 wire::Message::TxRemoveOutput(msg) => {
1685 self.message_handler.chan_handler.handle_tx_remove_output(&their_node_id, &msg);
1687 wire::Message::TxComplete(msg) => {
1688 self.message_handler.chan_handler.handle_tx_complete(&their_node_id, &msg);
1690 wire::Message::TxSignatures(msg) => {
1691 self.message_handler.chan_handler.handle_tx_signatures(&their_node_id, &msg);
1693 wire::Message::TxInitRbf(msg) => {
1694 self.message_handler.chan_handler.handle_tx_init_rbf(&their_node_id, &msg);
1696 wire::Message::TxAckRbf(msg) => {
1697 self.message_handler.chan_handler.handle_tx_ack_rbf(&their_node_id, &msg);
1699 wire::Message::TxAbort(msg) => {
1700 self.message_handler.chan_handler.handle_tx_abort(&their_node_id, &msg);
1703 wire::Message::Shutdown(msg) => {
1704 self.message_handler.chan_handler.handle_shutdown(&their_node_id, &msg);
1706 wire::Message::ClosingSigned(msg) => {
1707 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1710 // Commitment messages:
1711 wire::Message::UpdateAddHTLC(msg) => {
1712 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1714 wire::Message::UpdateFulfillHTLC(msg) => {
1715 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1717 wire::Message::UpdateFailHTLC(msg) => {
1718 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1720 wire::Message::UpdateFailMalformedHTLC(msg) => {
1721 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1724 wire::Message::CommitmentSigned(msg) => {
1725 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1727 wire::Message::RevokeAndACK(msg) => {
1728 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1730 wire::Message::UpdateFee(msg) => {
1731 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1733 wire::Message::ChannelReestablish(msg) => {
1734 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1737 // Routing messages:
1738 wire::Message::AnnouncementSignatures(msg) => {
1739 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1741 wire::Message::ChannelAnnouncement(msg) => {
1742 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1743 .map_err(|e| -> MessageHandlingError { e.into() })? {
1744 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1746 self.update_gossip_backlogged();
1748 wire::Message::NodeAnnouncement(msg) => {
1749 if self.message_handler.route_handler.handle_node_announcement(&msg)
1750 .map_err(|e| -> MessageHandlingError { e.into() })? {
1751 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1753 self.update_gossip_backlogged();
1755 wire::Message::ChannelUpdate(msg) => {
1756 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1757 if self.message_handler.route_handler.handle_channel_update(&msg)
1758 .map_err(|e| -> MessageHandlingError { e.into() })? {
1759 should_forward = Some(wire::Message::ChannelUpdate(msg));
1761 self.update_gossip_backlogged();
1763 wire::Message::QueryShortChannelIds(msg) => {
1764 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1766 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1767 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1769 wire::Message::QueryChannelRange(msg) => {
1770 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1772 wire::Message::ReplyChannelRange(msg) => {
1773 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1777 wire::Message::OnionMessage(msg) => {
1778 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1781 // Unknown messages:
1782 wire::Message::Unknown(type_id) if message.is_even() => {
1783 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1784 return Err(PeerHandleError { }.into());
1786 wire::Message::Unknown(type_id) => {
1787 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1789 wire::Message::Custom(custom) => {
1790 self.message_handler.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1796 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>) {
1798 wire::Message::ChannelAnnouncement(ref msg) => {
1799 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1800 let encoded_msg = encode_msg!(msg);
1802 for (_, peer_mutex) in peers.iter() {
1803 let mut peer = peer_mutex.lock().unwrap();
1804 if !peer.handshake_complete() ||
1805 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1808 debug_assert!(peer.their_node_id.is_some());
1809 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1810 if peer.buffer_full_drop_gossip_broadcast() {
1811 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1814 if let Some((_, their_node_id)) = peer.their_node_id {
1815 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
1819 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1822 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1825 wire::Message::NodeAnnouncement(ref msg) => {
1826 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1827 let encoded_msg = encode_msg!(msg);
1829 for (_, peer_mutex) in peers.iter() {
1830 let mut peer = peer_mutex.lock().unwrap();
1831 if !peer.handshake_complete() ||
1832 !peer.should_forward_node_announcement(msg.contents.node_id) {
1835 debug_assert!(peer.their_node_id.is_some());
1836 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1837 if peer.buffer_full_drop_gossip_broadcast() {
1838 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1841 if let Some((_, their_node_id)) = peer.their_node_id {
1842 if their_node_id == msg.contents.node_id {
1846 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1849 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1852 wire::Message::ChannelUpdate(ref msg) => {
1853 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1854 let encoded_msg = encode_msg!(msg);
1856 for (_, peer_mutex) in peers.iter() {
1857 let mut peer = peer_mutex.lock().unwrap();
1858 if !peer.handshake_complete() ||
1859 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1862 debug_assert!(peer.their_node_id.is_some());
1863 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
1864 if peer.buffer_full_drop_gossip_broadcast() {
1865 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1868 if except_node.is_some() && peer.their_node_id.as_ref().map(|(pk, _)| pk) == except_node {
1871 self.enqueue_encoded_gossip_broadcast(&mut *peer, encoded_msg.clone());
1874 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1878 /// Checks for any events generated by our handlers and processes them. Includes sending most
1879 /// response messages as well as messages generated by calls to handler functions directly (eg
1880 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1882 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1885 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1886 /// or one of the other clients provided in our language bindings.
1888 /// Note that if there are any other calls to this function waiting on lock(s) this may return
1889 /// without doing any work. All available events that need handling will be handled before the
1890 /// other calls return.
1892 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1893 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1894 /// [`send_data`]: SocketDescriptor::send_data
1895 pub fn process_events(&self) {
1896 if self.event_processing_state.fetch_add(1, Ordering::AcqRel) > 0 {
1897 // If we're not the first event processor to get here, just return early, the increment
1898 // we just did will be treated as "go around again" at the end.
1903 self.update_gossip_backlogged();
1904 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
1906 let mut peers_to_disconnect = HashMap::new();
1909 let peers_lock = self.peers.read().unwrap();
1911 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1912 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1914 let peers = &*peers_lock;
1915 macro_rules! get_peer_for_forwarding {
1916 ($node_id: expr) => {
1918 if peers_to_disconnect.get($node_id).is_some() {
1919 // If we've "disconnected" this peer, do not send to it.
1922 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1923 match descriptor_opt {
1924 Some(descriptor) => match peers.get(&descriptor) {
1925 Some(peer_mutex) => {
1926 let peer_lock = peer_mutex.lock().unwrap();
1927 if !peer_lock.handshake_complete() {
1933 debug_assert!(false, "Inconsistent peers set state!");
1944 for event in events_generated.drain(..) {
1946 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1947 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1948 log_pubkey!(node_id),
1949 &msg.temporary_channel_id);
1950 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1952 MessageSendEvent::SendAcceptChannelV2 { ref node_id, ref msg } => {
1953 log_debug!(self.logger, "Handling SendAcceptChannelV2 event in peer_handler for node {} for channel {}",
1954 log_pubkey!(node_id),
1955 &msg.temporary_channel_id);
1956 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1958 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1959 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1960 log_pubkey!(node_id),
1961 &msg.temporary_channel_id);
1962 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1964 MessageSendEvent::SendOpenChannelV2 { ref node_id, ref msg } => {
1965 log_debug!(self.logger, "Handling SendOpenChannelV2 event in peer_handler for node {} for channel {}",
1966 log_pubkey!(node_id),
1967 &msg.temporary_channel_id);
1968 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1970 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1971 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1972 log_pubkey!(node_id),
1973 &msg.temporary_channel_id,
1974 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1975 // TODO: If the peer is gone we should generate a DiscardFunding event
1976 // indicating to the wallet that they should just throw away this funding transaction
1977 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1979 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1980 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1981 log_pubkey!(node_id),
1983 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1985 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1986 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1987 log_pubkey!(node_id),
1989 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1991 MessageSendEvent::SendStfu { ref node_id, ref msg} => {
1992 log_debug!(self.logger, "Handling SendStfu event in peer_handler for node {} for channel {}",
1993 log_pubkey!(node_id),
1995 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1997 MessageSendEvent::SendSplice { ref node_id, ref msg} => {
1998 log_debug!(self.logger, "Handling SendSplice event in peer_handler for node {} for channel {}",
1999 log_pubkey!(node_id),
2001 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2003 MessageSendEvent::SendSpliceAck { ref node_id, ref msg} => {
2004 log_debug!(self.logger, "Handling SendSpliceAck event in peer_handler for node {} for channel {}",
2005 log_pubkey!(node_id),
2007 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2009 MessageSendEvent::SendSpliceLocked { ref node_id, ref msg} => {
2010 log_debug!(self.logger, "Handling SendSpliceLocked event in peer_handler for node {} for channel {}",
2011 log_pubkey!(node_id),
2013 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2015 MessageSendEvent::SendTxAddInput { ref node_id, ref msg } => {
2016 log_debug!(self.logger, "Handling SendTxAddInput event in peer_handler for node {} for channel {}",
2017 log_pubkey!(node_id),
2019 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2021 MessageSendEvent::SendTxAddOutput { ref node_id, ref msg } => {
2022 log_debug!(self.logger, "Handling SendTxAddOutput event in peer_handler for node {} for channel {}",
2023 log_pubkey!(node_id),
2025 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2027 MessageSendEvent::SendTxRemoveInput { ref node_id, ref msg } => {
2028 log_debug!(self.logger, "Handling SendTxRemoveInput event in peer_handler for node {} for channel {}",
2029 log_pubkey!(node_id),
2031 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2033 MessageSendEvent::SendTxRemoveOutput { ref node_id, ref msg } => {
2034 log_debug!(self.logger, "Handling SendTxRemoveOutput event in peer_handler for node {} for channel {}",
2035 log_pubkey!(node_id),
2037 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2039 MessageSendEvent::SendTxComplete { ref node_id, ref msg } => {
2040 log_debug!(self.logger, "Handling SendTxComplete event in peer_handler for node {} for channel {}",
2041 log_pubkey!(node_id),
2043 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2045 MessageSendEvent::SendTxSignatures { ref node_id, ref msg } => {
2046 log_debug!(self.logger, "Handling SendTxSignatures event in peer_handler for node {} for channel {}",
2047 log_pubkey!(node_id),
2049 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2051 MessageSendEvent::SendTxInitRbf { ref node_id, ref msg } => {
2052 log_debug!(self.logger, "Handling SendTxInitRbf event in peer_handler for node {} for channel {}",
2053 log_pubkey!(node_id),
2055 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2057 MessageSendEvent::SendTxAckRbf { ref node_id, ref msg } => {
2058 log_debug!(self.logger, "Handling SendTxAckRbf event in peer_handler for node {} for channel {}",
2059 log_pubkey!(node_id),
2061 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2063 MessageSendEvent::SendTxAbort { ref node_id, ref msg } => {
2064 log_debug!(self.logger, "Handling SendTxAbort event in peer_handler for node {} for channel {}",
2065 log_pubkey!(node_id),
2067 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2069 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
2070 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
2071 log_pubkey!(node_id),
2073 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2075 MessageSendEvent::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 } } => {
2076 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
2077 log_pubkey!(node_id),
2078 update_add_htlcs.len(),
2079 update_fulfill_htlcs.len(),
2080 update_fail_htlcs.len(),
2081 &commitment_signed.channel_id);
2082 let mut peer = get_peer_for_forwarding!(node_id);
2083 for msg in update_add_htlcs {
2084 self.enqueue_message(&mut *peer, msg);
2086 for msg in update_fulfill_htlcs {
2087 self.enqueue_message(&mut *peer, msg);
2089 for msg in update_fail_htlcs {
2090 self.enqueue_message(&mut *peer, msg);
2092 for msg in update_fail_malformed_htlcs {
2093 self.enqueue_message(&mut *peer, msg);
2095 if let &Some(ref msg) = update_fee {
2096 self.enqueue_message(&mut *peer, msg);
2098 self.enqueue_message(&mut *peer, commitment_signed);
2100 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2101 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
2102 log_pubkey!(node_id),
2104 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2106 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
2107 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
2108 log_pubkey!(node_id),
2110 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2112 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
2113 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
2114 log_pubkey!(node_id),
2116 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2118 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
2119 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
2120 log_pubkey!(node_id),
2122 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2124 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
2125 log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
2126 log_pubkey!(node_id),
2127 msg.contents.short_channel_id);
2128 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2129 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
2131 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
2132 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
2133 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
2134 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2135 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
2138 if let Some(msg) = update_msg {
2139 match self.message_handler.route_handler.handle_channel_update(&msg) {
2140 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2141 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2146 MessageSendEvent::BroadcastChannelUpdate { msg } => {
2147 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for contents {:?}", msg.contents);
2148 match self.message_handler.route_handler.handle_channel_update(&msg) {
2149 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2150 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
2154 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
2155 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler for node {}", msg.contents.node_id);
2156 match self.message_handler.route_handler.handle_node_announcement(&msg) {
2157 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
2158 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
2162 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
2163 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
2164 log_pubkey!(node_id), msg.contents.short_channel_id);
2165 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2167 MessageSendEvent::HandleError { node_id, action } => {
2169 msgs::ErrorAction::DisconnectPeer { msg } => {
2170 if let Some(msg) = msg.as_ref() {
2171 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2172 log_pubkey!(node_id), msg.data);
2174 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {}",
2175 log_pubkey!(node_id));
2177 // We do not have the peers write lock, so we just store that we're
2178 // about to disconenct the peer and do it after we finish
2179 // processing most messages.
2180 let msg = msg.map(|msg| wire::Message::<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
2181 peers_to_disconnect.insert(node_id, msg);
2183 msgs::ErrorAction::DisconnectPeerWithWarning { msg } => {
2184 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
2185 log_pubkey!(node_id), msg.data);
2186 // We do not have the peers write lock, so we just store that we're
2187 // about to disconenct the peer and do it after we finish
2188 // processing most messages.
2189 peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
2191 msgs::ErrorAction::IgnoreAndLog(level) => {
2192 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2194 msgs::ErrorAction::IgnoreDuplicateGossip => {},
2195 msgs::ErrorAction::IgnoreError => {
2196 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
2198 msgs::ErrorAction::SendErrorMessage { ref msg } => {
2199 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
2200 log_pubkey!(node_id),
2202 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2204 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
2205 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
2206 log_pubkey!(node_id),
2208 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), msg);
2212 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
2213 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2215 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
2216 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2218 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
2219 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
2220 log_pubkey!(node_id),
2221 msg.short_channel_ids.len(),
2223 msg.number_of_blocks,
2225 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2227 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
2228 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
2233 for (node_id, msg) in self.message_handler.custom_message_handler.get_and_clear_pending_msg() {
2234 if peers_to_disconnect.get(&node_id).is_some() { continue; }
2235 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
2238 for (descriptor, peer_mutex) in peers.iter() {
2239 let mut peer = peer_mutex.lock().unwrap();
2240 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2241 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer, flush_read_disabled);
2244 if !peers_to_disconnect.is_empty() {
2245 let mut peers_lock = self.peers.write().unwrap();
2246 let peers = &mut *peers_lock;
2247 for (node_id, msg) in peers_to_disconnect.drain() {
2248 // Note that since we are holding the peers *write* lock we can
2249 // remove from node_id_to_descriptor immediately (as no other
2250 // thread can be holding the peer lock if we have the global write
2253 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2254 if let Some(mut descriptor) = descriptor_opt {
2255 if let Some(peer_mutex) = peers.remove(&descriptor) {
2256 let mut peer = peer_mutex.lock().unwrap();
2257 if let Some(msg) = msg {
2258 self.enqueue_message(&mut *peer, &msg);
2259 // This isn't guaranteed to work, but if there is enough free
2260 // room in the send buffer, put the error message there...
2261 self.do_attempt_write_data(&mut descriptor, &mut *peer, false);
2263 self.do_disconnect(descriptor, &*peer, "DisconnectPeer HandleError");
2264 } else { debug_assert!(false, "Missing connection for peer"); }
2269 if self.event_processing_state.fetch_sub(1, Ordering::AcqRel) != 1 {
2270 // If another thread incremented the state while we were running we should go
2271 // around again, but only once.
2272 self.event_processing_state.store(1, Ordering::Release);
2279 /// Indicates that the given socket descriptor's connection is now closed.
2280 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
2281 self.disconnect_event_internal(descriptor);
2284 fn do_disconnect(&self, mut descriptor: Descriptor, peer: &Peer, reason: &'static str) {
2285 if !peer.handshake_complete() {
2286 log_trace!(self.logger, "Disconnecting peer which hasn't completed handshake due to {}", reason);
2287 descriptor.disconnect_socket();
2291 debug_assert!(peer.their_node_id.is_some());
2292 if let Some((node_id, _)) = peer.their_node_id {
2293 log_trace!(self.logger, "Disconnecting peer with id {} due to {}", node_id, reason);
2294 self.message_handler.chan_handler.peer_disconnected(&node_id);
2295 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2297 descriptor.disconnect_socket();
2300 fn disconnect_event_internal(&self, descriptor: &Descriptor) {
2301 let mut peers = self.peers.write().unwrap();
2302 let peer_option = peers.remove(descriptor);
2305 // This is most likely a simple race condition where the user found that the socket
2306 // was disconnected, then we told the user to `disconnect_socket()`, then they
2307 // called this method. Either way we're disconnected, return.
2309 Some(peer_lock) => {
2310 let peer = peer_lock.lock().unwrap();
2311 if let Some((node_id, _)) = peer.their_node_id {
2312 log_trace!(self.logger, "Handling disconnection of peer {}", log_pubkey!(node_id));
2313 let removed = self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2314 debug_assert!(removed.is_some(), "descriptor maps should be consistent");
2315 if !peer.handshake_complete() { return; }
2316 self.message_handler.chan_handler.peer_disconnected(&node_id);
2317 self.message_handler.onion_message_handler.peer_disconnected(&node_id);
2323 /// Disconnect a peer given its node id.
2325 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
2326 /// peer. Thus, be very careful about reentrancy issues.
2328 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
2329 pub fn disconnect_by_node_id(&self, node_id: PublicKey) {
2330 let mut peers_lock = self.peers.write().unwrap();
2331 if let Some(descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
2332 let peer_opt = peers_lock.remove(&descriptor);
2333 if let Some(peer_mutex) = peer_opt {
2334 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request");
2335 } else { debug_assert!(false, "node_id_to_descriptor thought we had a peer"); }
2339 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
2340 /// an indication that TCP sockets have stalled even if we weren't around to time them out
2341 /// using regular ping/pongs.
2342 pub fn disconnect_all_peers(&self) {
2343 let mut peers_lock = self.peers.write().unwrap();
2344 self.node_id_to_descriptor.lock().unwrap().clear();
2345 let peers = &mut *peers_lock;
2346 for (descriptor, peer_mutex) in peers.drain() {
2347 self.do_disconnect(descriptor, &*peer_mutex.lock().unwrap(), "client request to disconnect all peers");
2351 /// This is called when we're blocked on sending additional gossip messages until we receive a
2352 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
2353 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
2354 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
2355 if peer.awaiting_pong_timer_tick_intervals == 0 {
2356 peer.awaiting_pong_timer_tick_intervals = -1;
2357 let ping = msgs::Ping {
2361 self.enqueue_message(peer, &ping);
2365 /// Send pings to each peer and disconnect those which did not respond to the last round of
2368 /// This may be called on any timescale you want, however, roughly once every ten seconds is
2369 /// preferred. The call rate determines both how often we send a ping to our peers and how much
2370 /// time they have to respond before we disconnect them.
2372 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
2375 /// [`send_data`]: SocketDescriptor::send_data
2376 pub fn timer_tick_occurred(&self) {
2377 let mut descriptors_needing_disconnect = Vec::new();
2379 let peers_lock = self.peers.read().unwrap();
2381 self.update_gossip_backlogged();
2382 let flush_read_disabled = self.gossip_processing_backlog_lifted.swap(false, Ordering::Relaxed);
2384 for (descriptor, peer_mutex) in peers_lock.iter() {
2385 let mut peer = peer_mutex.lock().unwrap();
2386 if flush_read_disabled { peer.received_channel_announce_since_backlogged = false; }
2388 if !peer.handshake_complete() {
2389 // The peer needs to complete its handshake before we can exchange messages. We
2390 // give peers one timer tick to complete handshake, reusing
2391 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
2392 // for handshake completion.
2393 if peer.awaiting_pong_timer_tick_intervals != 0 {
2394 descriptors_needing_disconnect.push(descriptor.clone());
2396 peer.awaiting_pong_timer_tick_intervals = 1;
2400 debug_assert!(peer.channel_encryptor.is_ready_for_encryption());
2401 debug_assert!(peer.their_node_id.is_some());
2403 loop { // Used as a `goto` to skip writing a Ping message.
2404 if peer.awaiting_pong_timer_tick_intervals == -1 {
2405 // Magic value set in `maybe_send_extra_ping`.
2406 peer.awaiting_pong_timer_tick_intervals = 1;
2407 peer.received_message_since_timer_tick = false;
2411 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
2412 || peer.awaiting_pong_timer_tick_intervals as u64 >
2413 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
2415 descriptors_needing_disconnect.push(descriptor.clone());
2418 peer.received_message_since_timer_tick = false;
2420 if peer.awaiting_pong_timer_tick_intervals > 0 {
2421 peer.awaiting_pong_timer_tick_intervals += 1;
2425 peer.awaiting_pong_timer_tick_intervals = 1;
2426 let ping = msgs::Ping {
2430 self.enqueue_message(&mut *peer, &ping);
2433 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer, flush_read_disabled);
2437 if !descriptors_needing_disconnect.is_empty() {
2439 let mut peers_lock = self.peers.write().unwrap();
2440 for descriptor in descriptors_needing_disconnect {
2441 if let Some(peer_mutex) = peers_lock.remove(&descriptor) {
2442 let peer = peer_mutex.lock().unwrap();
2443 if let Some((node_id, _)) = peer.their_node_id {
2444 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
2446 self.do_disconnect(descriptor, &*peer, "ping/handshake timeout");
2454 // Messages of up to 64KB should never end up more than half full with addresses, as that would
2455 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
2456 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
2458 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (SocketAddress::MAX_LEN as u32 + 1) / 2;
2461 // ...by failing to compile if the number of addresses that would be half of a message is
2462 // smaller than 100:
2463 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
2465 /// Generates a signed node_announcement from the given arguments, sending it to all connected
2466 /// peers. Note that peers will likely ignore this message unless we have at least one public
2467 /// channel which has at least six confirmations on-chain.
2469 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
2470 /// node to humans. They carry no in-protocol meaning.
2472 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
2473 /// accepts incoming connections. These will be included in the node_announcement, publicly
2474 /// tying these addresses together and to this node. If you wish to preserve user privacy,
2475 /// addresses should likely contain only Tor Onion addresses.
2477 /// Panics if `addresses` is absurdly large (more than 100).
2479 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
2480 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<SocketAddress>) {
2481 if addresses.len() > 100 {
2482 panic!("More than half the message size was taken up by public addresses!");
2485 // While all existing nodes handle unsorted addresses just fine, the spec requires that
2486 // addresses be sorted for future compatibility.
2487 addresses.sort_by_key(|addr| addr.get_id());
2489 let features = self.message_handler.chan_handler.provided_node_features()
2490 | self.message_handler.route_handler.provided_node_features()
2491 | self.message_handler.onion_message_handler.provided_node_features()
2492 | self.message_handler.custom_message_handler.provided_node_features();
2493 let announcement = msgs::UnsignedNodeAnnouncement {
2495 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel),
2496 node_id: NodeId::from_pubkey(&self.node_signer.get_node_id(Recipient::Node).unwrap()),
2498 alias: NodeAlias(alias),
2500 excess_address_data: Vec::new(),
2501 excess_data: Vec::new(),
2503 let node_announce_sig = match self.node_signer.sign_gossip_message(
2504 msgs::UnsignedGossipMessage::NodeAnnouncement(&announcement)
2508 log_error!(self.logger, "Failed to generate signature for node_announcement");
2513 let msg = msgs::NodeAnnouncement {
2514 signature: node_announce_sig,
2515 contents: announcement
2518 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
2519 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
2520 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
2524 fn is_gossip_msg(type_id: u16) -> bool {
2526 msgs::ChannelAnnouncement::TYPE |
2527 msgs::ChannelUpdate::TYPE |
2528 msgs::NodeAnnouncement::TYPE |
2529 msgs::QueryChannelRange::TYPE |
2530 msgs::ReplyChannelRange::TYPE |
2531 msgs::QueryShortChannelIds::TYPE |
2532 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2539 use crate::sign::{NodeSigner, Recipient};
2542 use crate::ln::ChannelId;
2543 use crate::ln::features::{InitFeatures, NodeFeatures};
2544 use crate::ln::peer_channel_encryptor::PeerChannelEncryptor;
2545 use crate::ln::peer_handler::{CustomMessageHandler, PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2546 use crate::ln::{msgs, wire};
2547 use crate::ln::msgs::{LightningError, SocketAddress};
2548 use crate::util::test_utils;
2550 use bitcoin::Network;
2551 use bitcoin::blockdata::constants::ChainHash;
2552 use bitcoin::secp256k1::{PublicKey, SecretKey};
2554 use crate::prelude::*;
2555 use crate::sync::{Arc, Mutex};
2556 use core::convert::Infallible;
2557 use core::sync::atomic::{AtomicBool, Ordering};
2560 struct FileDescriptor {
2562 outbound_data: Arc<Mutex<Vec<u8>>>,
2563 disconnect: Arc<AtomicBool>,
2565 impl PartialEq for FileDescriptor {
2566 fn eq(&self, other: &Self) -> bool {
2570 impl Eq for FileDescriptor { }
2571 impl core::hash::Hash for FileDescriptor {
2572 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2573 self.fd.hash(hasher)
2577 impl SocketDescriptor for FileDescriptor {
2578 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2579 self.outbound_data.lock().unwrap().extend_from_slice(data);
2583 fn disconnect_socket(&mut self) { self.disconnect.store(true, Ordering::Release); }
2586 struct PeerManagerCfg {
2587 chan_handler: test_utils::TestChannelMessageHandler,
2588 routing_handler: test_utils::TestRoutingMessageHandler,
2589 custom_handler: TestCustomMessageHandler,
2590 logger: test_utils::TestLogger,
2591 node_signer: test_utils::TestNodeSigner,
2594 struct TestCustomMessageHandler {
2595 features: InitFeatures,
2598 impl wire::CustomMessageReader for TestCustomMessageHandler {
2599 type CustomMessage = Infallible;
2600 fn read<R: io::Read>(&self, _: u16, _: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
2605 impl CustomMessageHandler for TestCustomMessageHandler {
2606 fn handle_custom_message(&self, _: Infallible, _: &PublicKey) -> Result<(), LightningError> {
2610 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
2612 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
2614 fn provided_init_features(&self, _: &PublicKey) -> InitFeatures {
2615 self.features.clone()
2619 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2620 let mut cfgs = Vec::new();
2621 for i in 0..peer_count {
2622 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2624 let mut feature_bits = vec![0u8; 33];
2625 feature_bits[32] = 0b00000001;
2626 InitFeatures::from_le_bytes(feature_bits)
2630 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2631 logger: test_utils::TestLogger::new(),
2632 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2633 custom_handler: TestCustomMessageHandler { features },
2634 node_signer: test_utils::TestNodeSigner::new(node_secret),
2642 fn create_feature_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2643 let mut cfgs = Vec::new();
2644 for i in 0..peer_count {
2645 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2647 let mut feature_bits = vec![0u8; 33 + i + 1];
2648 feature_bits[33 + i] = 0b00000001;
2649 InitFeatures::from_le_bytes(feature_bits)
2653 chan_handler: test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet)),
2654 logger: test_utils::TestLogger::new(),
2655 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2656 custom_handler: TestCustomMessageHandler { features },
2657 node_signer: test_utils::TestNodeSigner::new(node_secret),
2665 fn create_chain_incompatible_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2666 let mut cfgs = Vec::new();
2667 for i in 0..peer_count {
2668 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2669 let features = InitFeatures::from_le_bytes(vec![0u8; 33]);
2670 let network = ChainHash::from(&[i as u8; 32][..]);
2673 chan_handler: test_utils::TestChannelMessageHandler::new(network),
2674 logger: test_utils::TestLogger::new(),
2675 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2676 custom_handler: TestCustomMessageHandler { features },
2677 node_signer: test_utils::TestNodeSigner::new(node_secret),
2685 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>> {
2686 let mut peers = Vec::new();
2687 for i in 0..peer_count {
2688 let ephemeral_bytes = [i as u8; 32];
2689 let msg_handler = MessageHandler {
2690 chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler,
2691 onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: &cfgs[i].custom_handler
2693 let peer = PeerManager::new(msg_handler, 0, &ephemeral_bytes, &cfgs[i].logger, &cfgs[i].node_signer);
2700 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) {
2701 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2702 let mut fd_a = FileDescriptor {
2703 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2704 disconnect: Arc::new(AtomicBool::new(false)),
2706 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2707 let id_b = peer_b.node_signer.get_node_id(Recipient::Node).unwrap();
2708 let mut fd_b = FileDescriptor {
2709 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2710 disconnect: Arc::new(AtomicBool::new(false)),
2712 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2713 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2714 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2715 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2716 peer_a.process_events();
2718 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2719 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2721 peer_b.process_events();
2722 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2723 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2725 peer_a.process_events();
2726 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2727 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2729 assert!(peer_a.get_peer_node_ids().contains(&(id_b, Some(addr_b))));
2730 assert!(peer_b.get_peer_node_ids().contains(&(id_a, Some(addr_a))));
2732 (fd_a.clone(), fd_b.clone())
2736 #[cfg(feature = "std")]
2737 fn fuzz_threaded_connections() {
2738 // Spawn two threads which repeatedly connect two peers together, leading to "got second
2739 // connection with peer" disconnections and rapid reconnect. This previously found an issue
2740 // with our internal map consistency, and is a generally good smoke test of disconnection.
2741 let cfgs = Arc::new(create_peermgr_cfgs(2));
2742 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
2743 let peers = Arc::new(create_network(2, unsafe { &*(&*cfgs as *const _) as &'static _ }));
2745 let start_time = std::time::Instant::now();
2746 macro_rules! spawn_thread { ($id: expr) => { {
2747 let peers = Arc::clone(&peers);
2748 let cfgs = Arc::clone(&cfgs);
2749 std::thread::spawn(move || {
2751 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2752 let id_a = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
2753 let mut fd_a = FileDescriptor {
2754 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2755 disconnect: Arc::new(AtomicBool::new(false)),
2757 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2758 let mut fd_b = FileDescriptor {
2759 fd: $id + ctr * 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2760 disconnect: Arc::new(AtomicBool::new(false)),
2762 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2763 let initial_data = peers[1].new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2764 peers[0].new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2765 if peers[0].read_event(&mut fd_a, &initial_data).is_err() { break; }
2767 while start_time.elapsed() < std::time::Duration::from_secs(1) {
2768 peers[0].process_events();
2769 if fd_a.disconnect.load(Ordering::Acquire) { break; }
2770 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2771 if peers[1].read_event(&mut fd_b, &a_data).is_err() { break; }
2773 peers[1].process_events();
2774 if fd_b.disconnect.load(Ordering::Acquire) { break; }
2775 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2776 if peers[0].read_event(&mut fd_a, &b_data).is_err() { break; }
2778 cfgs[0].chan_handler.pending_events.lock().unwrap()
2779 .push(crate::events::MessageSendEvent::SendShutdown {
2780 node_id: peers[1].node_signer.get_node_id(Recipient::Node).unwrap(),
2781 msg: msgs::Shutdown {
2782 channel_id: ChannelId::new_zero(),
2783 scriptpubkey: bitcoin::Script::new(),
2786 cfgs[1].chan_handler.pending_events.lock().unwrap()
2787 .push(crate::events::MessageSendEvent::SendShutdown {
2788 node_id: peers[0].node_signer.get_node_id(Recipient::Node).unwrap(),
2789 msg: msgs::Shutdown {
2790 channel_id: ChannelId::new_zero(),
2791 scriptpubkey: bitcoin::Script::new(),
2796 peers[0].timer_tick_occurred();
2797 peers[1].timer_tick_occurred();
2801 peers[0].socket_disconnected(&fd_a);
2802 peers[1].socket_disconnected(&fd_b);
2804 std::thread::sleep(std::time::Duration::from_micros(1));
2808 let thrd_a = spawn_thread!(1);
2809 let thrd_b = spawn_thread!(2);
2811 thrd_a.join().unwrap();
2812 thrd_b.join().unwrap();
2816 fn test_feature_incompatible_peers() {
2817 let cfgs = create_peermgr_cfgs(2);
2818 let incompatible_cfgs = create_feature_incompatible_peermgr_cfgs(2);
2820 let peers = create_network(2, &cfgs);
2821 let incompatible_peers = create_network(2, &incompatible_cfgs);
2822 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2823 for (peer_a, peer_b) in peer_pairs.iter() {
2824 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2825 let mut fd_a = FileDescriptor {
2826 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2827 disconnect: Arc::new(AtomicBool::new(false)),
2829 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2830 let mut fd_b = FileDescriptor {
2831 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2832 disconnect: Arc::new(AtomicBool::new(false)),
2834 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2835 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2836 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2837 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2838 peer_a.process_events();
2840 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2841 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2843 peer_b.process_events();
2844 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2846 // Should fail because of unknown required features
2847 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2852 fn test_chain_incompatible_peers() {
2853 let cfgs = create_peermgr_cfgs(2);
2854 let incompatible_cfgs = create_chain_incompatible_peermgr_cfgs(2);
2856 let peers = create_network(2, &cfgs);
2857 let incompatible_peers = create_network(2, &incompatible_cfgs);
2858 let peer_pairs = [(&peers[0], &incompatible_peers[0]), (&incompatible_peers[1], &peers[1])];
2859 for (peer_a, peer_b) in peer_pairs.iter() {
2860 let id_a = peer_a.node_signer.get_node_id(Recipient::Node).unwrap();
2861 let mut fd_a = FileDescriptor {
2862 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2863 disconnect: Arc::new(AtomicBool::new(false)),
2865 let addr_a = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1000};
2866 let mut fd_b = FileDescriptor {
2867 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
2868 disconnect: Arc::new(AtomicBool::new(false)),
2870 let addr_b = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1001};
2871 let initial_data = peer_b.new_outbound_connection(id_a, fd_b.clone(), Some(addr_a.clone())).unwrap();
2872 peer_a.new_inbound_connection(fd_a.clone(), Some(addr_b.clone())).unwrap();
2873 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2874 peer_a.process_events();
2876 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2877 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2879 peer_b.process_events();
2880 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2882 // Should fail because of incompatible chains
2883 assert!(peer_a.read_event(&mut fd_a, &b_data).is_err());
2888 fn test_disconnect_peer() {
2889 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2890 // push a DisconnectPeer event to remove the node flagged by id
2891 let cfgs = create_peermgr_cfgs(2);
2892 let peers = create_network(2, &cfgs);
2893 establish_connection(&peers[0], &peers[1]);
2894 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2896 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2897 cfgs[0].chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2899 action: msgs::ErrorAction::DisconnectPeer { msg: None },
2902 peers[0].process_events();
2903 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2907 fn test_send_simple_msg() {
2908 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2909 // push a message from one peer to another.
2910 let cfgs = create_peermgr_cfgs(2);
2911 let a_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2912 let b_chan_handler = test_utils::TestChannelMessageHandler::new(ChainHash::using_genesis_block(Network::Testnet));
2913 let mut peers = create_network(2, &cfgs);
2914 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2915 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2917 let their_id = peers[1].node_signer.get_node_id(Recipient::Node).unwrap();
2919 let msg = msgs::Shutdown { channel_id: ChannelId::from_bytes([42; 32]), scriptpubkey: bitcoin::Script::new() };
2920 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2921 node_id: their_id, msg: msg.clone()
2923 peers[0].message_handler.chan_handler = &a_chan_handler;
2925 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2926 peers[1].message_handler.chan_handler = &b_chan_handler;
2928 peers[0].process_events();
2930 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2931 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2935 fn test_non_init_first_msg() {
2936 // Simple test of the first message received over a connection being something other than
2937 // Init. This results in an immediate disconnection, which previously included a spurious
2938 // peer_disconnected event handed to event handlers (which would panic in
2939 // `TestChannelMessageHandler` here).
2940 let cfgs = create_peermgr_cfgs(2);
2941 let peers = create_network(2, &cfgs);
2943 let mut fd_dup = FileDescriptor {
2944 fd: 3, outbound_data: Arc::new(Mutex::new(Vec::new())),
2945 disconnect: Arc::new(AtomicBool::new(false)),
2947 let addr_dup = SocketAddress::TcpIpV4{addr: [127, 0, 0, 1], port: 1003};
2948 let id_a = cfgs[0].node_signer.get_node_id(Recipient::Node).unwrap();
2949 peers[0].new_inbound_connection(fd_dup.clone(), Some(addr_dup.clone())).unwrap();
2951 let mut dup_encryptor = PeerChannelEncryptor::new_outbound(id_a, SecretKey::from_slice(&[42; 32]).unwrap());
2952 let initial_data = dup_encryptor.get_act_one(&peers[1].secp_ctx);
2953 assert_eq!(peers[0].read_event(&mut fd_dup, &initial_data).unwrap(), false);
2954 peers[0].process_events();
2956 let a_data = fd_dup.outbound_data.lock().unwrap().split_off(0);
2957 let (act_three, _) =
2958 dup_encryptor.process_act_two(&a_data[..], &&cfgs[1].node_signer).unwrap();
2959 assert_eq!(peers[0].read_event(&mut fd_dup, &act_three).unwrap(), false);
2961 let not_init_msg = msgs::Ping { ponglen: 4, byteslen: 0 };
2962 let msg_bytes = dup_encryptor.encrypt_message(¬_init_msg);
2963 assert!(peers[0].read_event(&mut fd_dup, &msg_bytes).is_err());
2967 fn test_disconnect_all_peer() {
2968 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2969 // then calls disconnect_all_peers
2970 let cfgs = create_peermgr_cfgs(2);
2971 let peers = create_network(2, &cfgs);
2972 establish_connection(&peers[0], &peers[1]);
2973 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2975 peers[0].disconnect_all_peers();
2976 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2980 fn test_timer_tick_occurred() {
2981 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2982 let cfgs = create_peermgr_cfgs(2);
2983 let peers = create_network(2, &cfgs);
2984 establish_connection(&peers[0], &peers[1]);
2985 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2987 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2988 peers[0].timer_tick_occurred();
2989 peers[0].process_events();
2990 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2992 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2993 peers[0].timer_tick_occurred();
2994 peers[0].process_events();
2995 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2999 fn test_do_attempt_write_data() {
3000 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
3001 let cfgs = create_peermgr_cfgs(2);
3002 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3003 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3004 let peers = create_network(2, &cfgs);
3006 // By calling establish_connect, we trigger do_attempt_write_data between
3007 // the peers. Previously this function would mistakenly enter an infinite loop
3008 // when there were more channel messages available than could fit into a peer's
3009 // buffer. This issue would now be detected by this test (because we use custom
3010 // RoutingMessageHandlers that intentionally return more channel messages
3011 // than can fit into a peer's buffer).
3012 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
3014 // Make each peer to read the messages that the other peer just wrote to them. Note that
3015 // due to the max-message-before-ping limits this may take a few iterations to complete.
3016 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
3017 peers[1].process_events();
3018 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3019 assert!(!a_read_data.is_empty());
3021 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
3022 peers[0].process_events();
3024 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3025 assert!(!b_read_data.is_empty());
3026 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
3028 peers[0].process_events();
3029 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
3032 // Check that each peer has received the expected number of channel updates and channel
3034 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3035 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3036 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
3037 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
3041 fn test_handshake_timeout() {
3042 // Tests that we time out a peer still waiting on handshake completion after a full timer
3044 let cfgs = create_peermgr_cfgs(2);
3045 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
3046 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
3047 let peers = create_network(2, &cfgs);
3049 let a_id = peers[0].node_signer.get_node_id(Recipient::Node).unwrap();
3050 let mut fd_a = FileDescriptor {
3051 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3052 disconnect: Arc::new(AtomicBool::new(false)),
3054 let mut fd_b = FileDescriptor {
3055 fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())),
3056 disconnect: Arc::new(AtomicBool::new(false)),
3058 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
3059 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
3061 // If we get a single timer tick before completion, that's fine
3062 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3063 peers[0].timer_tick_occurred();
3064 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
3066 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
3067 peers[0].process_events();
3068 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
3069 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
3070 peers[1].process_events();
3072 // ...but if we get a second timer tick, we should disconnect the peer
3073 peers[0].timer_tick_occurred();
3074 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
3076 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
3077 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
3081 fn test_filter_addresses(){
3082 // Tests the filter_addresses function.
3085 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 0, 0], port: 1000};
3086 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3087 let ip_address = SocketAddress::TcpIpV4{addr: [10, 0, 255, 201], port: 1000};
3088 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3089 let ip_address = SocketAddress::TcpIpV4{addr: [10, 255, 255, 255], port: 1000};
3090 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3093 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 0, 0], port: 1000};
3094 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3095 let ip_address = SocketAddress::TcpIpV4{addr: [0, 0, 255, 187], port: 1000};
3096 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3097 let ip_address = SocketAddress::TcpIpV4{addr: [0, 255, 255, 255], port: 1000};
3098 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3101 let ip_address = SocketAddress::TcpIpV4{addr: [100, 64, 0, 0], port: 1000};
3102 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3103 let ip_address = SocketAddress::TcpIpV4{addr: [100, 78, 255, 0], port: 1000};
3104 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3105 let ip_address = SocketAddress::TcpIpV4{addr: [100, 127, 255, 255], port: 1000};
3106 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3109 let ip_address = SocketAddress::TcpIpV4{addr: [127, 0, 0, 0], port: 1000};
3110 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3111 let ip_address = SocketAddress::TcpIpV4{addr: [127, 65, 73, 0], port: 1000};
3112 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3113 let ip_address = SocketAddress::TcpIpV4{addr: [127, 255, 255, 255], port: 1000};
3114 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3117 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 0, 0], port: 1000};
3118 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3119 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 221, 101], port: 1000};
3120 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3121 let ip_address = SocketAddress::TcpIpV4{addr: [169, 254, 255, 255], port: 1000};
3122 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3125 let ip_address = SocketAddress::TcpIpV4{addr: [172, 16, 0, 0], port: 1000};
3126 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3127 let ip_address = SocketAddress::TcpIpV4{addr: [172, 27, 101, 23], port: 1000};
3128 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3129 let ip_address = SocketAddress::TcpIpV4{addr: [172, 31, 255, 255], port: 1000};
3130 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3133 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 0, 0], port: 1000};
3134 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3135 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 205, 159], port: 1000};
3136 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3137 let ip_address = SocketAddress::TcpIpV4{addr: [192, 168, 255, 255], port: 1000};
3138 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3140 // For (192.88.99/24)
3141 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 0], port: 1000};
3142 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3143 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 140], port: 1000};
3144 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3145 let ip_address = SocketAddress::TcpIpV4{addr: [192, 88, 99, 255], port: 1000};
3146 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3148 // For other IPv4 addresses
3149 let ip_address = SocketAddress::TcpIpV4{addr: [188, 255, 99, 0], port: 1000};
3150 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3151 let ip_address = SocketAddress::TcpIpV4{addr: [123, 8, 129, 14], port: 1000};
3152 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3153 let ip_address = SocketAddress::TcpIpV4{addr: [2, 88, 9, 255], port: 1000};
3154 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3157 let ip_address = SocketAddress::TcpIpV6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
3158 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3159 let ip_address = SocketAddress::TcpIpV6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
3160 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3161 let ip_address = SocketAddress::TcpIpV6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
3162 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
3164 // For other IPv6 addresses
3165 let ip_address = SocketAddress::TcpIpV6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
3166 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3167 let ip_address = SocketAddress::TcpIpV6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
3168 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3169 let ip_address = SocketAddress::TcpIpV6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
3170 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
3173 assert_eq!(filter_addresses(None), None);
3177 #[cfg(feature = "std")]
3178 fn test_process_events_multithreaded() {
3179 use std::time::{Duration, Instant};
3180 // Test that `process_events` getting called on multiple threads doesn't generate too many
3182 // Each time `process_events` goes around the loop we call
3183 // `get_and_clear_pending_msg_events`, which we count using the `TestMessageHandler`.
3184 // Because the loop should go around once more after a call which fails to take the
3185 // single-threaded lock, if we write zero to the counter before calling `process_events` we
3186 // should never observe there having been more than 2 loop iterations.
3187 // Further, because the last thread to exit will call `process_events` before returning, we
3188 // should always have at least one count at the end.
3189 let cfg = Arc::new(create_peermgr_cfgs(1));
3190 // Until we have std::thread::scoped we have to unsafe { turn off the borrow checker }.
3191 let peer = Arc::new(create_network(1, unsafe { &*(&*cfg as *const _) as &'static _ }).pop().unwrap());
3193 let exit_flag = Arc::new(AtomicBool::new(false));
3194 macro_rules! spawn_thread { () => { {
3195 let thread_cfg = Arc::clone(&cfg);
3196 let thread_peer = Arc::clone(&peer);
3197 let thread_exit = Arc::clone(&exit_flag);
3198 std::thread::spawn(move || {
3199 while !thread_exit.load(Ordering::Acquire) {
3200 thread_cfg[0].chan_handler.message_fetch_counter.store(0, Ordering::Release);
3201 thread_peer.process_events();
3202 std::thread::sleep(Duration::from_micros(1));
3207 let thread_a = spawn_thread!();
3208 let thread_b = spawn_thread!();
3209 let thread_c = spawn_thread!();
3211 let start_time = Instant::now();
3212 while start_time.elapsed() < Duration::from_millis(100) {
3213 let val = cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire);
3215 std::thread::yield_now(); // Winblowz seemingly doesn't ever interrupt threads?!
3218 exit_flag.store(true, Ordering::Release);
3219 thread_a.join().unwrap();
3220 thread_b.join().unwrap();
3221 thread_c.join().unwrap();
3222 assert!(cfg[0].chan_handler.message_fetch_counter.load(Ordering::Acquire) >= 1);