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::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
20 use ln::features::{InitFeatures, NodeFeatures};
22 use ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
23 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24 use util::ser::{VecWriter, Writeable, Writer};
25 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
28 use routing::gossip::{NetworkGraph, P2PGossipSync};
29 use util::atomic_counter::AtomicCounter;
30 use util::crypto::sign;
31 use util::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
32 use util::logger::Logger;
36 use alloc::collections::LinkedList;
37 use sync::{Arc, Mutex, MutexGuard, FairRwLock};
38 use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
39 use core::{cmp, hash, fmt, mem};
41 use core::convert::Infallible;
42 #[cfg(feature = "std")] use std::error;
44 use bitcoin::hashes::sha256::Hash as Sha256;
45 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
46 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
47 use bitcoin::hashes::{HashEngine, Hash};
49 /// Handler for BOLT1-compliant messages.
50 pub trait CustomMessageHandler: wire::CustomMessageReader {
51 /// Called with the message type that was received and the buffer to be read.
52 /// Can return a `MessageHandlingError` if the message could not be handled.
53 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
55 /// Gets the list of pending messages which were generated by the custom message
56 /// handler, clearing the list in the process. The first tuple element must
57 /// correspond to the intended recipients node ids. If no connection to one of the
58 /// specified node does not exist, the message is simply not sent to it.
59 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
62 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
63 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
64 pub struct IgnoringMessageHandler{}
65 impl MessageSendEventsProvider for IgnoringMessageHandler {
66 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
68 impl RoutingMessageHandler for IgnoringMessageHandler {
69 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
70 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
71 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
72 fn get_next_channel_announcement(&self, _starting_point: u64) ->
73 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
74 fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> { None }
75 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
76 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
77 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
78 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
79 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
80 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
81 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
85 impl OnionMessageProvider for IgnoringMessageHandler {
86 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
88 impl OnionMessageHandler for IgnoringMessageHandler {
89 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
90 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
91 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
93 impl Deref for IgnoringMessageHandler {
94 type Target = IgnoringMessageHandler;
95 fn deref(&self) -> &Self { self }
98 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
99 // method that takes self for it.
100 impl wire::Type for Infallible {
101 fn type_id(&self) -> u16 {
105 impl Writeable for Infallible {
106 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
111 impl wire::CustomMessageReader for IgnoringMessageHandler {
112 type CustomMessage = Infallible;
113 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
118 impl CustomMessageHandler for IgnoringMessageHandler {
119 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
120 // Since we always return `None` in the read the handle method should never be called.
124 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
127 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
128 /// You can provide one of these as the route_handler in a MessageHandler.
129 pub struct ErroringMessageHandler {
130 message_queue: Mutex<Vec<MessageSendEvent>>
132 impl ErroringMessageHandler {
133 /// Constructs a new ErroringMessageHandler
134 pub fn new() -> Self {
135 Self { message_queue: Mutex::new(Vec::new()) }
137 fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
138 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
139 action: msgs::ErrorAction::SendErrorMessage {
140 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
142 node_id: node_id.clone(),
146 impl MessageSendEventsProvider for ErroringMessageHandler {
147 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
148 let mut res = Vec::new();
149 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
153 impl ChannelMessageHandler for ErroringMessageHandler {
154 // Any messages which are related to a specific channel generate an error message to let the
155 // peer know we don't care about channels.
156 fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
157 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
159 fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
160 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
162 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
163 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
165 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
166 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
168 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
169 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
171 fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
172 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
174 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
175 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
177 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
178 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
180 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
181 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
183 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
184 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
186 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
187 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
189 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
190 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
192 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
193 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
195 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
196 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
198 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
199 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
201 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
202 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
204 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
205 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
206 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
207 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
208 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
209 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
210 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
211 // Use our known channel feature set as peers may otherwise not be willing to talk to us at
213 InitFeatures::known_channel_features()
216 impl Deref for ErroringMessageHandler {
217 type Target = ErroringMessageHandler;
218 fn deref(&self) -> &Self { self }
221 /// Provides references to trait impls which handle different types of messages.
222 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref> where
223 CM::Target: ChannelMessageHandler,
224 RM::Target: RoutingMessageHandler,
225 OM::Target: OnionMessageHandler,
227 /// A message handler which handles messages specific to channels. Usually this is just a
228 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
230 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
231 pub chan_handler: CM,
232 /// A message handler which handles messages updating our knowledge of the network channel
233 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
235 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
236 pub route_handler: RM,
238 /// A message handler which handles onion messages. For now, this can only be an
239 /// [`IgnoringMessageHandler`].
240 pub onion_message_handler: OM,
243 /// Provides an object which can be used to send data to and which uniquely identifies a connection
244 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
245 /// implement Hash to meet the PeerManager API.
247 /// For efficiency, Clone should be relatively cheap for this type.
249 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
250 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
251 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
252 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
253 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
254 /// to simply use another value which is guaranteed to be globally unique instead.
255 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
256 /// Attempts to send some data from the given slice to the peer.
258 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
259 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
260 /// called and further write attempts may occur until that time.
262 /// If the returned size is smaller than `data.len()`, a
263 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
264 /// written. Additionally, until a `send_data` event completes fully, no further
265 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
266 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
269 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
270 /// (indicating that read events should be paused to prevent DoS in the send buffer),
271 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
272 /// `resume_read` of false carries no meaning, and should not cause any action.
273 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
274 /// Disconnect the socket pointed to by this SocketDescriptor.
276 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
277 /// call (doing so is a noop).
278 fn disconnect_socket(&mut self);
281 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
282 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
285 pub struct PeerHandleError {
286 /// Used to indicate that we probably can't make any future connections to this peer (e.g.
287 /// because we required features that our peer was missing, or vice versa).
289 /// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close
290 /// any channels with this peer or check for new versions of LDK.
292 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
293 pub no_connection_possible: bool,
295 impl fmt::Debug for PeerHandleError {
296 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
297 formatter.write_str("Peer Sent Invalid Data")
300 impl fmt::Display for PeerHandleError {
301 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
302 formatter.write_str("Peer Sent Invalid Data")
306 #[cfg(feature = "std")]
307 impl error::Error for PeerHandleError {
308 fn description(&self) -> &str {
309 "Peer Sent Invalid Data"
313 enum InitSyncTracker{
315 ChannelsSyncing(u64),
316 NodesSyncing(PublicKey),
319 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
320 /// forwarding gossip messages to peers altogether.
321 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
323 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
324 /// we have fewer than this many messages in the outbound buffer again.
325 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
326 /// refilled as we send bytes.
327 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
328 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
330 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
332 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
333 /// the socket receive buffer before receiving the ping.
335 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
336 /// including any network delays, outbound traffic, or the same for messages from other peers.
338 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
339 /// per connected peer to respond to a ping, as long as they send us at least one message during
340 /// each tick, ensuring we aren't actually just disconnected.
341 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
344 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
345 /// two connected peers, assuming most LDK-running systems have at least two cores.
346 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
348 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
349 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
350 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
351 /// process before the next ping.
353 /// Note that we continue responding to other messages even after we've sent this many messages, so
354 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
355 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
356 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
359 channel_encryptor: PeerChannelEncryptor,
360 their_node_id: Option<PublicKey>,
361 their_features: Option<InitFeatures>,
362 their_net_address: Option<NetAddress>,
364 pending_outbound_buffer: LinkedList<Vec<u8>>,
365 pending_outbound_buffer_first_msg_offset: usize,
366 // Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily prioritize
367 // channel messages over them.
368 gossip_broadcast_buffer: LinkedList<Vec<u8>>,
369 awaiting_write_event: bool,
371 pending_read_buffer: Vec<u8>,
372 pending_read_buffer_pos: usize,
373 pending_read_is_header: bool,
375 sync_status: InitSyncTracker,
377 msgs_sent_since_pong: usize,
378 awaiting_pong_timer_tick_intervals: i8,
379 received_message_since_timer_tick: bool,
380 sent_gossip_timestamp_filter: bool,
384 /// Returns true if the channel announcements/updates for the given channel should be
385 /// forwarded to this peer.
386 /// If we are sending our routing table to this peer and we have not yet sent channel
387 /// announcements/updates for the given channel_id then we will send it when we get to that
388 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
389 /// sent the old versions, we should send the update, and so return true here.
390 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
391 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
392 !self.sent_gossip_timestamp_filter {
395 match self.sync_status {
396 InitSyncTracker::NoSyncRequested => true,
397 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
398 InitSyncTracker::NodesSyncing(_) => true,
402 /// Similar to the above, but for node announcements indexed by node_id.
403 fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
404 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
405 !self.sent_gossip_timestamp_filter {
408 match self.sync_status {
409 InitSyncTracker::NoSyncRequested => true,
410 InitSyncTracker::ChannelsSyncing(_) => false,
411 InitSyncTracker::NodesSyncing(pk) => pk < node_id,
415 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
416 /// buffer still has space and we don't need to pause reads to get some writes out.
417 fn should_read(&self) -> bool {
418 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE
421 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
422 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
423 fn should_buffer_gossip_backfill(&self) -> bool {
424 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
425 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
428 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
429 /// every time the peer's buffer may have been drained.
430 fn should_buffer_onion_message(&self) -> bool {
431 self.pending_outbound_buffer.is_empty()
432 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
435 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
436 /// buffer. This is checked every time the peer's buffer may have been drained.
437 fn should_buffer_gossip_broadcast(&self) -> bool {
438 self.pending_outbound_buffer.is_empty()
439 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
442 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
443 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
444 let total_outbound_buffered =
445 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
447 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
448 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
452 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
453 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
454 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
455 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
456 /// issues such as overly long function definitions.
458 /// (C-not exported) as Arcs don't make sense in bindings
459 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, Arc<C>, Arc<L>>>, IgnoringMessageHandler, Arc<L>, Arc<IgnoringMessageHandler>>;
461 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
462 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
463 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
464 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
465 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
466 /// helps with issues such as long function definitions.
468 /// (C-not exported) as Arcs don't make sense in bindings
469 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e P2PGossipSync<&'g NetworkGraph<&'f L>, &'h C, &'f L>, IgnoringMessageHandler, &'f L, IgnoringMessageHandler>;
471 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
472 /// socket events into messages which it passes on to its [`MessageHandler`].
474 /// Locks are taken internally, so you must never assume that reentrancy from a
475 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
477 /// Calls to [`read_event`] will decode relevant messages and pass them to the
478 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
479 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
480 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
481 /// calls only after previous ones have returned.
483 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
484 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
485 /// essentially you should default to using a SimpleRefPeerManager, and use a
486 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
487 /// you're using lightning-net-tokio.
489 /// [`read_event`]: PeerManager::read_event
490 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> where
491 CM::Target: ChannelMessageHandler,
492 RM::Target: RoutingMessageHandler,
493 OM::Target: OnionMessageHandler,
495 CMH::Target: CustomMessageHandler {
496 message_handler: MessageHandler<CM, RM, OM>,
497 /// Connection state for each connected peer - we have an outer read-write lock which is taken
498 /// as read while we're doing processing for a peer and taken write when a peer is being added
501 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
502 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
503 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
504 /// the `MessageHandler`s for a given peer is already guaranteed.
505 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
506 /// Only add to this set when noise completes.
507 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
508 /// lock held. Entries may be added with only the `peers` read lock held (though the
509 /// `Descriptor` value must already exist in `peers`).
510 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
511 /// We can only have one thread processing events at once, but we don't usually need the full
512 /// `peers` write lock to do so, so instead we block on this empty mutex when entering
513 /// `process_events`.
514 event_processing_lock: Mutex<()>,
515 /// Because event processing is global and always does all available work before returning,
516 /// there is no reason for us to have many event processors waiting on the lock at once.
517 /// Instead, we limit the total blocked event processors to always exactly one by setting this
518 /// when an event process call is waiting.
519 blocked_event_processors: AtomicBool,
521 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
522 /// value increases strictly since we don't assume access to a time source.
523 last_node_announcement_serial: AtomicU64,
525 our_node_secret: SecretKey,
526 ephemeral_key_midstate: Sha256Engine,
527 custom_message_handler: CMH,
529 peer_counter: AtomicCounter,
532 secp_ctx: Secp256k1<secp256k1::SignOnly>
535 enum MessageHandlingError {
536 PeerHandleError(PeerHandleError),
537 LightningError(LightningError),
540 impl From<PeerHandleError> for MessageHandlingError {
541 fn from(error: PeerHandleError) -> Self {
542 MessageHandlingError::PeerHandleError(error)
546 impl From<LightningError> for MessageHandlingError {
547 fn from(error: LightningError) -> Self {
548 MessageHandlingError::LightningError(error)
552 macro_rules! encode_msg {
554 let mut buffer = VecWriter(Vec::new());
555 wire::write($msg, &mut buffer).unwrap();
560 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler> where
561 CM::Target: ChannelMessageHandler,
562 OM::Target: OnionMessageHandler,
564 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
565 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
568 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
569 /// cryptographically secure random bytes.
571 /// `current_time` is used as an always-increasing counter that survives across restarts and is
572 /// incremented irregularly internally. In general it is best to simply use the current UNIX
573 /// timestamp, however if it is not available a persistent counter that increases once per
574 /// minute should suffice.
576 /// (C-not exported) as we can't export a PeerManager with a dummy route handler
577 pub fn new_channel_only(channel_message_handler: CM, onion_message_handler: OM, our_node_secret: SecretKey, current_time: u64, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
578 Self::new(MessageHandler {
579 chan_handler: channel_message_handler,
580 route_handler: IgnoringMessageHandler{},
581 onion_message_handler,
582 }, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
586 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
587 RM::Target: RoutingMessageHandler,
589 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
590 /// handler or onion message handler is used and onion and channel messages will be ignored (or
591 /// generate error messages). Note that some other lightning implementations time-out connections
592 /// after some time if no channel is built with the peer.
594 /// `current_time` is used as an always-increasing counter that survives across restarts and is
595 /// incremented irregularly internally. In general it is best to simply use the current UNIX
596 /// timestamp, however if it is not available a persistent counter that increases once per
597 /// minute should suffice.
599 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
600 /// cryptographically secure random bytes.
602 /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
603 pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, current_time: u64, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
604 Self::new(MessageHandler {
605 chan_handler: ErroringMessageHandler::new(),
606 route_handler: routing_message_handler,
607 onion_message_handler: IgnoringMessageHandler{},
608 }, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
612 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
613 /// This works around `format!()` taking a reference to each argument, preventing
614 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
615 /// due to lifetime errors.
616 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
617 impl core::fmt::Display for OptionalFromDebugger<'_> {
618 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
619 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
623 /// A function used to filter out local or private addresses
624 /// https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml
625 /// https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
626 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
628 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
629 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
630 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
631 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
632 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
633 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
634 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
635 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
636 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
637 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
638 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
639 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
640 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
641 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
642 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
643 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
644 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
645 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
646 // For remaining addresses
647 Some(NetAddress::IPv6{addr: _, port: _}) => None,
648 Some(..) => ip_address,
653 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH> where
654 CM::Target: ChannelMessageHandler,
655 RM::Target: RoutingMessageHandler,
656 OM::Target: OnionMessageHandler,
658 CMH::Target: CustomMessageHandler {
659 /// Constructs a new PeerManager with the given message handlers and node_id secret key
660 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
661 /// cryptographically secure random bytes.
663 /// `current_time` is used as an always-increasing counter that survives across restarts and is
664 /// incremented irregularly internally. In general it is best to simply use the current UNIX
665 /// timestamp, however if it is not available a persistent counter that increases once per
666 /// minute should suffice.
667 pub fn new(message_handler: MessageHandler<CM, RM, OM>, our_node_secret: SecretKey, current_time: u64, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
668 let mut ephemeral_key_midstate = Sha256::engine();
669 ephemeral_key_midstate.input(ephemeral_random_data);
671 let mut secp_ctx = Secp256k1::signing_only();
672 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
673 secp_ctx.seeded_randomize(&ephemeral_hash);
677 peers: FairRwLock::new(HashMap::new()),
678 node_id_to_descriptor: Mutex::new(HashMap::new()),
679 event_processing_lock: Mutex::new(()),
680 blocked_event_processors: AtomicBool::new(false),
682 ephemeral_key_midstate,
683 peer_counter: AtomicCounter::new(),
684 last_node_announcement_serial: AtomicU64::new(current_time),
686 custom_message_handler,
691 /// Get the list of node ids for peers which have completed the initial handshake.
693 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
694 /// new_outbound_connection, however entries will only appear once the initial handshake has
695 /// completed and we are sure the remote peer has the private key for the given node_id.
696 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
697 let peers = self.peers.read().unwrap();
698 peers.values().filter_map(|peer_mutex| {
699 let p = peer_mutex.lock().unwrap();
700 if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
707 fn get_ephemeral_key(&self) -> SecretKey {
708 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
709 let counter = self.peer_counter.get_increment();
710 ephemeral_hash.input(&counter.to_le_bytes());
711 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
714 /// Indicates a new outbound connection has been established to a node with the given node_id
715 /// and an optional remote network address.
717 /// The remote network address adds the option to report a remote IP address back to a connecting
718 /// peer using the init message.
719 /// The user should pass the remote network address of the host they are connected to.
721 /// If an `Err` is returned here you must disconnect the connection immediately.
723 /// Returns a small number of bytes to send to the remote node (currently always 50).
725 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
726 /// [`socket_disconnected()`].
728 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
729 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
730 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
731 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
732 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
734 let mut peers = self.peers.write().unwrap();
735 if peers.insert(descriptor, Mutex::new(Peer {
736 channel_encryptor: peer_encryptor,
738 their_features: None,
739 their_net_address: remote_network_address,
741 pending_outbound_buffer: LinkedList::new(),
742 pending_outbound_buffer_first_msg_offset: 0,
743 gossip_broadcast_buffer: LinkedList::new(),
744 awaiting_write_event: false,
747 pending_read_buffer_pos: 0,
748 pending_read_is_header: false,
750 sync_status: InitSyncTracker::NoSyncRequested,
752 msgs_sent_since_pong: 0,
753 awaiting_pong_timer_tick_intervals: 0,
754 received_message_since_timer_tick: false,
755 sent_gossip_timestamp_filter: false,
757 panic!("PeerManager driver duplicated descriptors!");
762 /// Indicates a new inbound connection has been established to a node with an optional remote
765 /// The remote network address adds the option to report a remote IP address back to a connecting
766 /// peer using the init message.
767 /// The user should pass the remote network address of the host they are connected to.
769 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
770 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
771 /// the connection immediately.
773 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
774 /// [`socket_disconnected()`].
776 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
777 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
778 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret, &self.secp_ctx);
779 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
781 let mut peers = self.peers.write().unwrap();
782 if peers.insert(descriptor, Mutex::new(Peer {
783 channel_encryptor: peer_encryptor,
785 their_features: None,
786 their_net_address: remote_network_address,
788 pending_outbound_buffer: LinkedList::new(),
789 pending_outbound_buffer_first_msg_offset: 0,
790 gossip_broadcast_buffer: LinkedList::new(),
791 awaiting_write_event: false,
794 pending_read_buffer_pos: 0,
795 pending_read_is_header: false,
797 sync_status: InitSyncTracker::NoSyncRequested,
799 msgs_sent_since_pong: 0,
800 awaiting_pong_timer_tick_intervals: 0,
801 received_message_since_timer_tick: false,
802 sent_gossip_timestamp_filter: false,
804 panic!("PeerManager driver duplicated descriptors!");
809 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
810 while !peer.awaiting_write_event {
811 if peer.should_buffer_onion_message() {
812 if let Some(peer_node_id) = peer.their_node_id {
813 if let Some(next_onion_message) =
814 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
815 self.enqueue_message(peer, &next_onion_message);
819 if peer.should_buffer_gossip_broadcast() {
820 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
821 peer.pending_outbound_buffer.push_back(msg);
824 if peer.should_buffer_gossip_backfill() {
825 match peer.sync_status {
826 InitSyncTracker::NoSyncRequested => {},
827 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
828 if let Some((announce, update_a_option, update_b_option)) =
829 self.message_handler.route_handler.get_next_channel_announcement(c)
831 self.enqueue_message(peer, &announce);
832 if let Some(update_a) = update_a_option {
833 self.enqueue_message(peer, &update_a);
835 if let Some(update_b) = update_b_option {
836 self.enqueue_message(peer, &update_b);
838 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
840 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
843 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
844 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
845 self.enqueue_message(peer, &msg);
846 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
848 peer.sync_status = InitSyncTracker::NoSyncRequested;
851 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
852 InitSyncTracker::NodesSyncing(key) => {
853 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&key)) {
854 self.enqueue_message(peer, &msg);
855 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
857 peer.sync_status = InitSyncTracker::NoSyncRequested;
862 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
863 self.maybe_send_extra_ping(peer);
866 let next_buff = match peer.pending_outbound_buffer.front() {
871 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
872 let data_sent = descriptor.send_data(pending, peer.should_read());
873 peer.pending_outbound_buffer_first_msg_offset += data_sent;
874 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
875 peer.pending_outbound_buffer_first_msg_offset = 0;
876 peer.pending_outbound_buffer.pop_front();
878 peer.awaiting_write_event = true;
883 /// Indicates that there is room to write data to the given socket descriptor.
885 /// May return an Err to indicate that the connection should be closed.
887 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
888 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
889 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
890 /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
893 /// [`send_data`]: SocketDescriptor::send_data
894 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
895 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
896 let peers = self.peers.read().unwrap();
897 match peers.get(descriptor) {
899 // This is most likely a simple race condition where the user found that the socket
900 // was writeable, then we told the user to `disconnect_socket()`, then they called
901 // this method. Return an error to make sure we get disconnected.
902 return Err(PeerHandleError { no_connection_possible: false });
904 Some(peer_mutex) => {
905 let mut peer = peer_mutex.lock().unwrap();
906 peer.awaiting_write_event = false;
907 self.do_attempt_write_data(descriptor, &mut peer);
913 /// Indicates that data was read from the given socket descriptor.
915 /// May return an Err to indicate that the connection should be closed.
917 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
918 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
919 /// [`send_data`] calls to handle responses.
921 /// If `Ok(true)` is returned, further read_events should not be triggered until a
922 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
925 /// [`send_data`]: SocketDescriptor::send_data
926 /// [`process_events`]: PeerManager::process_events
927 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
928 match self.do_read_event(peer_descriptor, data) {
931 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
932 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
938 /// Append a message to a peer's pending outbound/write buffer
939 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
940 let mut buffer = VecWriter(Vec::with_capacity(2048));
941 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
943 if is_gossip_msg(message.type_id()) {
944 log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
946 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
948 peer.msgs_sent_since_pong += 1;
949 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&buffer.0[..]));
952 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
953 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
954 peer.msgs_sent_since_pong += 1;
955 peer.gossip_broadcast_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
958 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
959 let mut pause_read = false;
960 let peers = self.peers.read().unwrap();
961 let mut msgs_to_forward = Vec::new();
962 let mut peer_node_id = None;
963 match peers.get(peer_descriptor) {
965 // This is most likely a simple race condition where the user read some bytes
966 // from the socket, then we told the user to `disconnect_socket()`, then they
967 // called this method. Return an error to make sure we get disconnected.
968 return Err(PeerHandleError { no_connection_possible: false });
970 Some(peer_mutex) => {
971 let mut read_pos = 0;
972 while read_pos < data.len() {
973 macro_rules! try_potential_handleerror {
974 ($peer: expr, $thing: expr) => {
979 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
980 //TODO: Try to push msg
981 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
982 return Err(PeerHandleError{ no_connection_possible: false });
984 msgs::ErrorAction::IgnoreAndLog(level) => {
985 log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
988 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
989 msgs::ErrorAction::IgnoreError => {
990 log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
993 msgs::ErrorAction::SendErrorMessage { msg } => {
994 log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
995 self.enqueue_message($peer, &msg);
998 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
999 log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
1000 self.enqueue_message($peer, &msg);
1009 let mut peer_lock = peer_mutex.lock().unwrap();
1010 let peer = &mut *peer_lock;
1011 let mut msg_to_handle = None;
1012 if peer_node_id.is_none() {
1013 peer_node_id = peer.their_node_id.clone();
1016 assert!(peer.pending_read_buffer.len() > 0);
1017 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1020 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1021 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]);
1022 read_pos += data_to_copy;
1023 peer.pending_read_buffer_pos += data_to_copy;
1026 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1027 peer.pending_read_buffer_pos = 0;
1029 macro_rules! insert_node_id {
1031 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap()) {
1032 hash_map::Entry::Occupied(_) => {
1033 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
1034 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1035 return Err(PeerHandleError{ no_connection_possible: false })
1037 hash_map::Entry::Vacant(entry) => {
1038 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
1039 entry.insert(peer_descriptor.clone())
1045 let next_step = peer.channel_encryptor.get_noise_step();
1047 NextNoiseStep::ActOne => {
1048 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1049 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1050 &self.our_node_secret, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1051 peer.pending_outbound_buffer.push_back(act_two);
1052 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1054 NextNoiseStep::ActTwo => {
1055 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1056 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1057 &self.our_node_secret, &self.secp_ctx));
1058 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1059 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1060 peer.pending_read_is_header = true;
1062 peer.their_node_id = Some(their_node_id);
1064 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1065 .or(self.message_handler.route_handler.provided_init_features(&their_node_id));
1066 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1067 self.enqueue_message(peer, &resp);
1068 peer.awaiting_pong_timer_tick_intervals = 0;
1070 NextNoiseStep::ActThree => {
1071 let their_node_id = try_potential_handleerror!(peer,
1072 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1073 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1074 peer.pending_read_is_header = true;
1075 peer.their_node_id = Some(their_node_id);
1077 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1078 .or(self.message_handler.route_handler.provided_init_features(&their_node_id));
1079 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1080 self.enqueue_message(peer, &resp);
1081 peer.awaiting_pong_timer_tick_intervals = 0;
1083 NextNoiseStep::NoiseComplete => {
1084 if peer.pending_read_is_header {
1085 let msg_len = try_potential_handleerror!(peer,
1086 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1087 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1088 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1089 if msg_len < 2 { // Need at least the message type tag
1090 return Err(PeerHandleError{ no_connection_possible: false });
1092 peer.pending_read_is_header = false;
1094 let msg_data = try_potential_handleerror!(peer,
1095 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1096 assert!(msg_data.len() >= 2);
1098 // Reset read buffer
1099 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1100 peer.pending_read_buffer.resize(18, 0);
1101 peer.pending_read_is_header = true;
1103 let mut reader = io::Cursor::new(&msg_data[..]);
1104 let message_result = wire::read(&mut reader, &*self.custom_message_handler);
1105 let message = match message_result {
1109 // Note that to avoid recursion we never call
1110 // `do_attempt_write_data` from here, causing
1111 // the messages enqueued here to not actually
1112 // be sent before the peer is disconnected.
1113 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1114 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1117 (msgs::DecodeError::UnsupportedCompression, _) => {
1118 log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1119 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1122 (_, Some(ty)) if is_gossip_msg(ty) => {
1123 log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1124 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unreadable/bogus gossip message".to_owned() });
1127 (msgs::DecodeError::UnknownRequiredFeature, ty) => {
1128 log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1129 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
1130 return Err(PeerHandleError { no_connection_possible: false });
1132 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }),
1133 (msgs::DecodeError::InvalidValue, _) => {
1134 log_debug!(self.logger, "Got an invalid value while deserializing message");
1135 return Err(PeerHandleError { no_connection_possible: false });
1137 (msgs::DecodeError::ShortRead, _) => {
1138 log_debug!(self.logger, "Deserialization failed due to shortness of message");
1139 return Err(PeerHandleError { no_connection_possible: false });
1141 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }),
1142 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }),
1147 msg_to_handle = Some(message);
1152 pause_read = !peer.should_read();
1154 if let Some(message) = msg_to_handle {
1155 match self.handle_message(&peer_mutex, peer_lock, message) {
1156 Err(handling_error) => match handling_error {
1157 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1158 MessageHandlingError::LightningError(e) => {
1159 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1163 msgs_to_forward.push(msg);
1172 for msg in msgs_to_forward.drain(..) {
1173 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref());
1179 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1180 /// Returns the message back if it needs to be broadcasted to all other peers.
1183 peer_mutex: &Mutex<Peer>,
1184 mut peer_lock: MutexGuard<Peer>,
1185 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1186 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1187 let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages");
1188 peer_lock.received_message_since_timer_tick = true;
1190 // Need an Init as first message
1191 if let wire::Message::Init(msg) = message {
1192 if msg.features.requires_unknown_bits() {
1193 log_debug!(self.logger, "Peer features required unknown version bits");
1194 return Err(PeerHandleError{ no_connection_possible: true }.into());
1196 if peer_lock.their_features.is_some() {
1197 return Err(PeerHandleError{ no_connection_possible: false }.into());
1200 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1202 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1203 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1204 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1207 if !msg.features.supports_static_remote_key() {
1208 log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(their_node_id));
1209 return Err(PeerHandleError{ no_connection_possible: true }.into());
1212 self.message_handler.route_handler.peer_connected(&their_node_id, &msg);
1213 self.message_handler.chan_handler.peer_connected(&their_node_id, &msg);
1214 self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg);
1216 peer_lock.their_features = Some(msg.features);
1218 } else if peer_lock.their_features.is_none() {
1219 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1220 return Err(PeerHandleError{ no_connection_possible: false }.into());
1223 if let wire::Message::GossipTimestampFilter(_msg) = message {
1224 // When supporting gossip messages, start inital gossip sync only after we receive
1225 // a GossipTimestampFilter
1226 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1227 !peer_lock.sent_gossip_timestamp_filter {
1228 peer_lock.sent_gossip_timestamp_filter = true;
1229 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1234 let their_features = peer_lock.their_features.clone();
1235 mem::drop(peer_lock);
1237 if is_gossip_msg(message.type_id()) {
1238 log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1240 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1243 let mut should_forward = None;
1246 // Setup and Control messages:
1247 wire::Message::Init(_) => {
1250 wire::Message::GossipTimestampFilter(_) => {
1253 wire::Message::Error(msg) => {
1254 let mut data_is_printable = true;
1255 for b in msg.data.bytes() {
1256 if b < 32 || b > 126 {
1257 data_is_printable = false;
1262 if data_is_printable {
1263 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1265 log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1267 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1268 if msg.channel_id == [0; 32] {
1269 return Err(PeerHandleError{ no_connection_possible: true }.into());
1272 wire::Message::Warning(msg) => {
1273 let mut data_is_printable = true;
1274 for b in msg.data.bytes() {
1275 if b < 32 || b > 126 {
1276 data_is_printable = false;
1281 if data_is_printable {
1282 log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1284 log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1288 wire::Message::Ping(msg) => {
1289 if msg.ponglen < 65532 {
1290 let resp = msgs::Pong { byteslen: msg.ponglen };
1291 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1294 wire::Message::Pong(_msg) => {
1295 let mut peer_lock = peer_mutex.lock().unwrap();
1296 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1297 peer_lock.msgs_sent_since_pong = 0;
1300 // Channel messages:
1301 wire::Message::OpenChannel(msg) => {
1302 self.message_handler.chan_handler.handle_open_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1304 wire::Message::AcceptChannel(msg) => {
1305 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1308 wire::Message::FundingCreated(msg) => {
1309 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1311 wire::Message::FundingSigned(msg) => {
1312 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1314 wire::Message::ChannelReady(msg) => {
1315 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1318 wire::Message::Shutdown(msg) => {
1319 self.message_handler.chan_handler.handle_shutdown(&their_node_id, their_features.as_ref().unwrap(), &msg);
1321 wire::Message::ClosingSigned(msg) => {
1322 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1325 // Commitment messages:
1326 wire::Message::UpdateAddHTLC(msg) => {
1327 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1329 wire::Message::UpdateFulfillHTLC(msg) => {
1330 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1332 wire::Message::UpdateFailHTLC(msg) => {
1333 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1335 wire::Message::UpdateFailMalformedHTLC(msg) => {
1336 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1339 wire::Message::CommitmentSigned(msg) => {
1340 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1342 wire::Message::RevokeAndACK(msg) => {
1343 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1345 wire::Message::UpdateFee(msg) => {
1346 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1348 wire::Message::ChannelReestablish(msg) => {
1349 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1352 // Routing messages:
1353 wire::Message::AnnouncementSignatures(msg) => {
1354 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1356 wire::Message::ChannelAnnouncement(msg) => {
1357 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1358 .map_err(|e| -> MessageHandlingError { e.into() })? {
1359 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1362 wire::Message::NodeAnnouncement(msg) => {
1363 if self.message_handler.route_handler.handle_node_announcement(&msg)
1364 .map_err(|e| -> MessageHandlingError { e.into() })? {
1365 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1368 wire::Message::ChannelUpdate(msg) => {
1369 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1370 if self.message_handler.route_handler.handle_channel_update(&msg)
1371 .map_err(|e| -> MessageHandlingError { e.into() })? {
1372 should_forward = Some(wire::Message::ChannelUpdate(msg));
1375 wire::Message::QueryShortChannelIds(msg) => {
1376 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1378 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1379 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1381 wire::Message::QueryChannelRange(msg) => {
1382 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1384 wire::Message::ReplyChannelRange(msg) => {
1385 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1389 wire::Message::OnionMessage(msg) => {
1390 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1393 // Unknown messages:
1394 wire::Message::Unknown(type_id) if message.is_even() => {
1395 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1396 // Fail the channel if message is an even, unknown type as per BOLT #1.
1397 return Err(PeerHandleError{ no_connection_possible: true }.into());
1399 wire::Message::Unknown(type_id) => {
1400 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1402 wire::Message::Custom(custom) => {
1403 self.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1409 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>) {
1411 wire::Message::ChannelAnnouncement(ref msg) => {
1412 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1413 let encoded_msg = encode_msg!(msg);
1415 for (_, peer_mutex) in peers.iter() {
1416 let mut peer = peer_mutex.lock().unwrap();
1417 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1418 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1421 if peer.buffer_full_drop_gossip_broadcast() {
1422 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1425 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1426 peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1429 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1432 self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1435 wire::Message::NodeAnnouncement(ref msg) => {
1436 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1437 let encoded_msg = encode_msg!(msg);
1439 for (_, peer_mutex) in peers.iter() {
1440 let mut peer = peer_mutex.lock().unwrap();
1441 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1442 !peer.should_forward_node_announcement(msg.contents.node_id) {
1445 if peer.buffer_full_drop_gossip_broadcast() {
1446 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1449 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1452 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1455 self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1458 wire::Message::ChannelUpdate(ref msg) => {
1459 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1460 let encoded_msg = encode_msg!(msg);
1462 for (_, peer_mutex) in peers.iter() {
1463 let mut peer = peer_mutex.lock().unwrap();
1464 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1465 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1468 if peer.buffer_full_drop_gossip_broadcast() {
1469 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1472 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1475 self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1478 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1482 /// Checks for any events generated by our handlers and processes them. Includes sending most
1483 /// response messages as well as messages generated by calls to handler functions directly (eg
1484 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1486 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1489 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1490 /// or one of the other clients provided in our language bindings.
1492 /// Note that if there are any other calls to this function waiting on lock(s) this may return
1493 /// without doing any work. All available events that need handling will be handled before the
1494 /// other calls return.
1496 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1497 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1498 /// [`send_data`]: SocketDescriptor::send_data
1499 pub fn process_events(&self) {
1500 let mut _single_processor_lock = self.event_processing_lock.try_lock();
1501 if _single_processor_lock.is_err() {
1502 // While we could wake the older sleeper here with a CV and make more even waiting
1503 // times, that would be a lot of overengineering for a simple "reduce total waiter
1505 match self.blocked_event_processors.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) {
1507 debug_assert!(val, "compare_exchange failed spuriously?");
1511 debug_assert!(!val, "compare_exchange succeeded spuriously?");
1512 // We're the only waiter, as the running process_events may have emptied the
1513 // pending events "long" ago and there are new events for us to process, wait until
1514 // its done and process any leftover events before returning.
1515 _single_processor_lock = Ok(self.event_processing_lock.lock().unwrap());
1516 self.blocked_event_processors.store(false, Ordering::Release);
1521 let mut peers_to_disconnect = HashMap::new();
1522 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1523 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1526 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1527 // buffer by doing things like announcing channels on another node. We should be willing to
1528 // drop optional-ish messages when send buffers get full!
1530 let peers_lock = self.peers.read().unwrap();
1531 let peers = &*peers_lock;
1532 macro_rules! get_peer_for_forwarding {
1533 ($node_id: expr) => {
1535 if peers_to_disconnect.get($node_id).is_some() {
1536 // If we've "disconnected" this peer, do not send to it.
1539 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1540 match descriptor_opt {
1541 Some(descriptor) => match peers.get(&descriptor) {
1542 Some(peer_mutex) => {
1543 let peer_lock = peer_mutex.lock().unwrap();
1544 if peer_lock.their_features.is_none() {
1550 debug_assert!(false, "Inconsistent peers set state!");
1561 for event in events_generated.drain(..) {
1563 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1564 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1565 log_pubkey!(node_id),
1566 log_bytes!(msg.temporary_channel_id));
1567 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1569 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1570 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1571 log_pubkey!(node_id),
1572 log_bytes!(msg.temporary_channel_id));
1573 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1575 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1576 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1577 log_pubkey!(node_id),
1578 log_bytes!(msg.temporary_channel_id),
1579 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1580 // TODO: If the peer is gone we should generate a DiscardFunding event
1581 // indicating to the wallet that they should just throw away this funding transaction
1582 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1584 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1585 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1586 log_pubkey!(node_id),
1587 log_bytes!(msg.channel_id));
1588 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1590 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1591 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1592 log_pubkey!(node_id),
1593 log_bytes!(msg.channel_id));
1594 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1596 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1597 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1598 log_pubkey!(node_id),
1599 log_bytes!(msg.channel_id));
1600 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1602 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 } } => {
1603 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1604 log_pubkey!(node_id),
1605 update_add_htlcs.len(),
1606 update_fulfill_htlcs.len(),
1607 update_fail_htlcs.len(),
1608 log_bytes!(commitment_signed.channel_id));
1609 let mut peer = get_peer_for_forwarding!(node_id);
1610 for msg in update_add_htlcs {
1611 self.enqueue_message(&mut *peer, msg);
1613 for msg in update_fulfill_htlcs {
1614 self.enqueue_message(&mut *peer, msg);
1616 for msg in update_fail_htlcs {
1617 self.enqueue_message(&mut *peer, msg);
1619 for msg in update_fail_malformed_htlcs {
1620 self.enqueue_message(&mut *peer, msg);
1622 if let &Some(ref msg) = update_fee {
1623 self.enqueue_message(&mut *peer, msg);
1625 self.enqueue_message(&mut *peer, commitment_signed);
1627 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1628 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1629 log_pubkey!(node_id),
1630 log_bytes!(msg.channel_id));
1631 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1633 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1634 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1635 log_pubkey!(node_id),
1636 log_bytes!(msg.channel_id));
1637 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1639 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1640 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1641 log_pubkey!(node_id),
1642 log_bytes!(msg.channel_id));
1643 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1645 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1646 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1647 log_pubkey!(node_id),
1648 log_bytes!(msg.channel_id));
1649 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1651 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
1652 log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
1653 log_pubkey!(node_id),
1654 msg.contents.short_channel_id);
1655 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1656 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
1658 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1659 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1660 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1661 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1662 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1665 match self.message_handler.route_handler.handle_channel_update(&update_msg) {
1666 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1667 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None),
1671 MessageSendEvent::BroadcastChannelUpdate { msg } => {
1672 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1673 match self.message_handler.route_handler.handle_channel_update(&msg) {
1674 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1675 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1679 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1680 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1681 log_pubkey!(node_id), msg.contents.short_channel_id);
1682 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1684 MessageSendEvent::HandleError { ref node_id, ref action } => {
1686 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1687 // We do not have the peers write lock, so we just store that we're
1688 // about to disconenct the peer and do it after we finish
1689 // processing most messages.
1690 peers_to_disconnect.insert(*node_id, msg.clone());
1692 msgs::ErrorAction::IgnoreAndLog(level) => {
1693 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1695 msgs::ErrorAction::IgnoreDuplicateGossip => {},
1696 msgs::ErrorAction::IgnoreError => {
1697 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1699 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1700 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1701 log_pubkey!(node_id),
1703 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1705 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1706 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1707 log_pubkey!(node_id),
1709 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1713 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1714 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1716 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1717 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1719 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1720 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1721 log_pubkey!(node_id),
1722 msg.short_channel_ids.len(),
1724 msg.number_of_blocks,
1726 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1728 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
1729 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1734 for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1735 if peers_to_disconnect.get(&node_id).is_some() { continue; }
1736 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
1739 for (descriptor, peer_mutex) in peers.iter() {
1740 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer_mutex.lock().unwrap());
1743 if !peers_to_disconnect.is_empty() {
1744 let mut peers_lock = self.peers.write().unwrap();
1745 let peers = &mut *peers_lock;
1746 for (node_id, msg) in peers_to_disconnect.drain() {
1747 // Note that since we are holding the peers *write* lock we can
1748 // remove from node_id_to_descriptor immediately (as no other
1749 // thread can be holding the peer lock if we have the global write
1752 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1753 if let Some(peer_mutex) = peers.remove(&descriptor) {
1754 if let Some(msg) = msg {
1755 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1756 log_pubkey!(node_id),
1758 let mut peer = peer_mutex.lock().unwrap();
1759 self.enqueue_message(&mut *peer, &msg);
1760 // This isn't guaranteed to work, but if there is enough free
1761 // room in the send buffer, put the error message there...
1762 self.do_attempt_write_data(&mut descriptor, &mut *peer);
1764 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1767 descriptor.disconnect_socket();
1768 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1769 self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1775 /// Indicates that the given socket descriptor's connection is now closed.
1776 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1777 self.disconnect_event_internal(descriptor, false);
1780 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1781 let mut peers = self.peers.write().unwrap();
1782 let peer_option = peers.remove(descriptor);
1785 // This is most likely a simple race condition where the user found that the socket
1786 // was disconnected, then we told the user to `disconnect_socket()`, then they
1787 // called this method. Either way we're disconnected, return.
1789 Some(peer_lock) => {
1790 let peer = peer_lock.lock().unwrap();
1791 if let Some(node_id) = peer.their_node_id {
1792 log_trace!(self.logger,
1793 "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1794 log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1795 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1796 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1797 self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1803 /// Disconnect a peer given its node id.
1805 /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1806 /// force-closing any channels we have with it.
1808 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1809 /// peer. Thus, be very careful about reentrancy issues.
1811 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1812 pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1813 let mut peers_lock = self.peers.write().unwrap();
1814 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1815 log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1816 peers_lock.remove(&descriptor);
1817 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1818 self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1819 descriptor.disconnect_socket();
1823 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1824 /// an indication that TCP sockets have stalled even if we weren't around to time them out
1825 /// using regular ping/pongs.
1826 pub fn disconnect_all_peers(&self) {
1827 let mut peers_lock = self.peers.write().unwrap();
1828 self.node_id_to_descriptor.lock().unwrap().clear();
1829 let peers = &mut *peers_lock;
1830 for (mut descriptor, peer) in peers.drain() {
1831 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1832 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1833 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1834 self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1836 descriptor.disconnect_socket();
1840 /// This is called when we're blocked on sending additional gossip messages until we receive a
1841 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1842 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1843 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1844 if peer.awaiting_pong_timer_tick_intervals == 0 {
1845 peer.awaiting_pong_timer_tick_intervals = -1;
1846 let ping = msgs::Ping {
1850 self.enqueue_message(peer, &ping);
1854 /// Send pings to each peer and disconnect those which did not respond to the last round of
1857 /// This may be called on any timescale you want, however, roughly once every ten seconds is
1858 /// preferred. The call rate determines both how often we send a ping to our peers and how much
1859 /// time they have to respond before we disconnect them.
1861 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1864 /// [`send_data`]: SocketDescriptor::send_data
1865 pub fn timer_tick_occurred(&self) {
1866 let mut descriptors_needing_disconnect = Vec::new();
1868 let peers_lock = self.peers.read().unwrap();
1870 for (descriptor, peer_mutex) in peers_lock.iter() {
1871 let mut peer = peer_mutex.lock().unwrap();
1872 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1873 // The peer needs to complete its handshake before we can exchange messages. We
1874 // give peers one timer tick to complete handshake, reusing
1875 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1876 // for handshake completion.
1877 if peer.awaiting_pong_timer_tick_intervals != 0 {
1878 descriptors_needing_disconnect.push(descriptor.clone());
1880 peer.awaiting_pong_timer_tick_intervals = 1;
1885 if peer.awaiting_pong_timer_tick_intervals == -1 {
1886 // Magic value set in `maybe_send_extra_ping`.
1887 peer.awaiting_pong_timer_tick_intervals = 1;
1888 peer.received_message_since_timer_tick = false;
1892 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1893 || peer.awaiting_pong_timer_tick_intervals as u64 >
1894 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
1896 descriptors_needing_disconnect.push(descriptor.clone());
1899 peer.received_message_since_timer_tick = false;
1901 if peer.awaiting_pong_timer_tick_intervals > 0 {
1902 peer.awaiting_pong_timer_tick_intervals += 1;
1906 peer.awaiting_pong_timer_tick_intervals = 1;
1907 let ping = msgs::Ping {
1911 self.enqueue_message(&mut *peer, &ping);
1912 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1916 if !descriptors_needing_disconnect.is_empty() {
1918 let mut peers_lock = self.peers.write().unwrap();
1919 for descriptor in descriptors_needing_disconnect.iter() {
1920 if let Some(peer) = peers_lock.remove(descriptor) {
1921 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1922 log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1923 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1924 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1925 self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1931 for mut descriptor in descriptors_needing_disconnect.drain(..) {
1932 descriptor.disconnect_socket();
1938 // Messages of up to 64KB should never end up more than half full with addresses, as that would
1939 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
1940 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1942 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1945 // ...by failing to compile if the number of addresses that would be half of a message is
1946 // smaller than 100:
1947 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
1949 /// Generates a signed node_announcement from the given arguments, sending it to all connected
1950 /// peers. Note that peers will likely ignore this message unless we have at least one public
1951 /// channel which has at least six confirmations on-chain.
1953 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
1954 /// node to humans. They carry no in-protocol meaning.
1956 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
1957 /// accepts incoming connections. These will be included in the node_announcement, publicly
1958 /// tying these addresses together and to this node. If you wish to preserve user privacy,
1959 /// addresses should likely contain only Tor Onion addresses.
1961 /// Panics if `addresses` is absurdly large (more than 100).
1963 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
1964 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
1965 if addresses.len() > 100 {
1966 panic!("More than half the message size was taken up by public addresses!");
1969 // While all existing nodes handle unsorted addresses just fine, the spec requires that
1970 // addresses be sorted for future compatibility.
1971 addresses.sort_by_key(|addr| addr.get_id());
1973 let features = self.message_handler.chan_handler.provided_node_features()
1974 .or(self.message_handler.route_handler.provided_node_features());
1975 let announcement = msgs::UnsignedNodeAnnouncement {
1977 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1978 node_id: PublicKey::from_secret_key(&self.secp_ctx, &self.our_node_secret),
1979 rgb, alias, addresses,
1980 excess_address_data: Vec::new(),
1981 excess_data: Vec::new(),
1983 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1984 let node_announce_sig = sign(&self.secp_ctx, &msghash, &self.our_node_secret);
1986 let msg = msgs::NodeAnnouncement {
1987 signature: node_announce_sig,
1988 contents: announcement
1991 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
1992 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
1993 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
1997 fn is_gossip_msg(type_id: u16) -> bool {
1999 msgs::ChannelAnnouncement::TYPE |
2000 msgs::ChannelUpdate::TYPE |
2001 msgs::NodeAnnouncement::TYPE |
2002 msgs::QueryChannelRange::TYPE |
2003 msgs::ReplyChannelRange::TYPE |
2004 msgs::QueryShortChannelIds::TYPE |
2005 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2012 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2013 use ln::{msgs, wire};
2014 use ln::msgs::NetAddress;
2016 use util::test_utils;
2018 use bitcoin::secp256k1::Secp256k1;
2019 use bitcoin::secp256k1::{SecretKey, PublicKey};
2022 use sync::{Arc, Mutex};
2023 use core::sync::atomic::Ordering;
2026 struct FileDescriptor {
2028 outbound_data: Arc<Mutex<Vec<u8>>>,
2030 impl PartialEq for FileDescriptor {
2031 fn eq(&self, other: &Self) -> bool {
2035 impl Eq for FileDescriptor { }
2036 impl core::hash::Hash for FileDescriptor {
2037 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2038 self.fd.hash(hasher)
2042 impl SocketDescriptor for FileDescriptor {
2043 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2044 self.outbound_data.lock().unwrap().extend_from_slice(data);
2048 fn disconnect_socket(&mut self) {}
2051 struct PeerManagerCfg {
2052 chan_handler: test_utils::TestChannelMessageHandler,
2053 routing_handler: test_utils::TestRoutingMessageHandler,
2054 logger: test_utils::TestLogger,
2057 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2058 let mut cfgs = Vec::new();
2059 for _ in 0..peer_count {
2062 chan_handler: test_utils::TestChannelMessageHandler::new(),
2063 logger: test_utils::TestLogger::new(),
2064 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2072 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, IgnoringMessageHandler>> {
2073 let mut peers = Vec::new();
2074 for i in 0..peer_count {
2075 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2076 let ephemeral_bytes = [i as u8; 32];
2077 let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler, onion_message_handler: IgnoringMessageHandler {} };
2078 let peer = PeerManager::new(msg_handler, node_secret, 0, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
2085 fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>) -> (FileDescriptor, FileDescriptor) {
2086 let secp_ctx = Secp256k1::new();
2087 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
2088 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2089 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2090 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2091 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
2092 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2093 peer_a.process_events();
2095 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2096 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2098 peer_b.process_events();
2099 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2100 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2102 peer_a.process_events();
2103 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2104 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2106 (fd_a.clone(), fd_b.clone())
2110 fn test_disconnect_peer() {
2111 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2112 // push a DisconnectPeer event to remove the node flagged by id
2113 let cfgs = create_peermgr_cfgs(2);
2114 let chan_handler = test_utils::TestChannelMessageHandler::new();
2115 let mut peers = create_network(2, &cfgs);
2116 establish_connection(&peers[0], &peers[1]);
2117 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2119 let secp_ctx = Secp256k1::new();
2120 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2122 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2124 action: msgs::ErrorAction::DisconnectPeer { msg: None },
2126 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
2127 peers[0].message_handler.chan_handler = &chan_handler;
2129 peers[0].process_events();
2130 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2134 fn test_send_simple_msg() {
2135 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2136 // push a message from one peer to another.
2137 let cfgs = create_peermgr_cfgs(2);
2138 let a_chan_handler = test_utils::TestChannelMessageHandler::new();
2139 let b_chan_handler = test_utils::TestChannelMessageHandler::new();
2140 let mut peers = create_network(2, &cfgs);
2141 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2142 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2144 let secp_ctx = Secp256k1::new();
2145 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2147 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2148 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2149 node_id: their_id, msg: msg.clone()
2151 peers[0].message_handler.chan_handler = &a_chan_handler;
2153 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2154 peers[1].message_handler.chan_handler = &b_chan_handler;
2156 peers[0].process_events();
2158 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2159 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2163 fn test_disconnect_all_peer() {
2164 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2165 // then calls disconnect_all_peers
2166 let cfgs = create_peermgr_cfgs(2);
2167 let peers = create_network(2, &cfgs);
2168 establish_connection(&peers[0], &peers[1]);
2169 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2171 peers[0].disconnect_all_peers();
2172 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2176 fn test_timer_tick_occurred() {
2177 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2178 let cfgs = create_peermgr_cfgs(2);
2179 let peers = create_network(2, &cfgs);
2180 establish_connection(&peers[0], &peers[1]);
2181 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2183 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2184 peers[0].timer_tick_occurred();
2185 peers[0].process_events();
2186 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2188 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2189 peers[0].timer_tick_occurred();
2190 peers[0].process_events();
2191 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2195 fn test_do_attempt_write_data() {
2196 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2197 let cfgs = create_peermgr_cfgs(2);
2198 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2199 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2200 let peers = create_network(2, &cfgs);
2202 // By calling establish_connect, we trigger do_attempt_write_data between
2203 // the peers. Previously this function would mistakenly enter an infinite loop
2204 // when there were more channel messages available than could fit into a peer's
2205 // buffer. This issue would now be detected by this test (because we use custom
2206 // RoutingMessageHandlers that intentionally return more channel messages
2207 // than can fit into a peer's buffer).
2208 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2210 // Make each peer to read the messages that the other peer just wrote to them. Note that
2211 // due to the max-message-before-ping limits this may take a few iterations to complete.
2212 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2213 peers[1].process_events();
2214 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2215 assert!(!a_read_data.is_empty());
2217 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2218 peers[0].process_events();
2220 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2221 assert!(!b_read_data.is_empty());
2222 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2224 peers[0].process_events();
2225 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2228 // Check that each peer has received the expected number of channel updates and channel
2230 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2231 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2232 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2233 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2237 fn test_handshake_timeout() {
2238 // Tests that we time out a peer still waiting on handshake completion after a full timer
2240 let cfgs = create_peermgr_cfgs(2);
2241 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2242 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2243 let peers = create_network(2, &cfgs);
2245 let secp_ctx = Secp256k1::new();
2246 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
2247 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2248 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2249 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2250 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
2252 // If we get a single timer tick before completion, that's fine
2253 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2254 peers[0].timer_tick_occurred();
2255 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2257 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
2258 peers[0].process_events();
2259 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2260 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2261 peers[1].process_events();
2263 // ...but if we get a second timer tick, we should disconnect the peer
2264 peers[0].timer_tick_occurred();
2265 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2267 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2268 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
2272 fn test_filter_addresses(){
2273 // Tests the filter_addresses function.
2276 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
2277 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2278 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
2279 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2280 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
2281 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2284 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
2285 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2286 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
2287 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2288 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
2289 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2292 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
2293 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2294 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
2295 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2296 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
2297 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2300 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
2301 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2302 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
2303 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2304 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
2305 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2308 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
2309 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2310 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2311 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2312 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2313 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2316 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2317 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2318 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2319 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2320 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2321 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2324 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2325 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2326 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2327 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2328 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2329 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2331 // For (192.88.99/24)
2332 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2333 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2334 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2335 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2336 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2337 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2339 // For other IPv4 addresses
2340 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2341 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2342 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2343 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2344 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2345 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2348 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2349 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2350 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2351 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2352 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2353 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2355 // For other IPv6 addresses
2356 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2357 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2358 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2359 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2360 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2361 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2364 assert_eq!(filter_addresses(None), None);