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_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures {
84 impl OnionMessageProvider for IgnoringMessageHandler {
85 fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
87 impl OnionMessageHandler for IgnoringMessageHandler {
88 fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
89 fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
90 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
92 impl Deref for IgnoringMessageHandler {
93 type Target = IgnoringMessageHandler;
94 fn deref(&self) -> &Self { self }
97 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
98 // method that takes self for it.
99 impl wire::Type for Infallible {
100 fn type_id(&self) -> u16 {
104 impl Writeable for Infallible {
105 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
110 impl wire::CustomMessageReader for IgnoringMessageHandler {
111 type CustomMessage = Infallible;
112 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
117 impl CustomMessageHandler for IgnoringMessageHandler {
118 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
119 // Since we always return `None` in the read the handle method should never be called.
123 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
126 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
127 /// You can provide one of these as the route_handler in a MessageHandler.
128 pub struct ErroringMessageHandler {
129 message_queue: Mutex<Vec<MessageSendEvent>>
131 impl ErroringMessageHandler {
132 /// Constructs a new ErroringMessageHandler
133 pub fn new() -> Self {
134 Self { message_queue: Mutex::new(Vec::new()) }
136 fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
137 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
138 action: msgs::ErrorAction::SendErrorMessage {
139 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
141 node_id: node_id.clone(),
145 impl MessageSendEventsProvider for ErroringMessageHandler {
146 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
147 let mut res = Vec::new();
148 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
152 impl ChannelMessageHandler for ErroringMessageHandler {
153 // Any messages which are related to a specific channel generate an error message to let the
154 // peer know we don't care about channels.
155 fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
156 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
158 fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
159 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
161 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
162 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
164 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
165 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
167 fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
168 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
170 fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
171 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
173 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
174 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
176 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
177 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
179 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
180 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
182 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
183 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
185 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
186 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
188 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
189 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
191 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
192 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
194 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
195 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
197 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
198 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
200 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
201 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
203 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
204 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
205 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
206 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
207 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
208 fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
209 fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures { InitFeatures::known() }
211 impl Deref for ErroringMessageHandler {
212 type Target = ErroringMessageHandler;
213 fn deref(&self) -> &Self { self }
216 /// Provides references to trait impls which handle different types of messages.
217 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref> where
218 CM::Target: ChannelMessageHandler,
219 RM::Target: RoutingMessageHandler,
220 OM::Target: OnionMessageHandler,
222 /// A message handler which handles messages specific to channels. Usually this is just a
223 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
225 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
226 pub chan_handler: CM,
227 /// A message handler which handles messages updating our knowledge of the network channel
228 /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
230 /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
231 pub route_handler: RM,
233 /// A message handler which handles onion messages. For now, this can only be an
234 /// [`IgnoringMessageHandler`].
235 pub onion_message_handler: OM,
238 /// Provides an object which can be used to send data to and which uniquely identifies a connection
239 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
240 /// implement Hash to meet the PeerManager API.
242 /// For efficiency, Clone should be relatively cheap for this type.
244 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
245 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
246 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
247 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
248 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
249 /// to simply use another value which is guaranteed to be globally unique instead.
250 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
251 /// Attempts to send some data from the given slice to the peer.
253 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
254 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
255 /// called and further write attempts may occur until that time.
257 /// If the returned size is smaller than `data.len()`, a
258 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
259 /// written. Additionally, until a `send_data` event completes fully, no further
260 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
261 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
264 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
265 /// (indicating that read events should be paused to prevent DoS in the send buffer),
266 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
267 /// `resume_read` of false carries no meaning, and should not cause any action.
268 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
269 /// Disconnect the socket pointed to by this SocketDescriptor.
271 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
272 /// call (doing so is a noop).
273 fn disconnect_socket(&mut self);
276 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
277 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
280 pub struct PeerHandleError {
281 /// Used to indicate that we probably can't make any future connections to this peer (e.g.
282 /// because we required features that our peer was missing, or vice versa).
284 /// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close
285 /// any channels with this peer or check for new versions of LDK.
287 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
288 pub no_connection_possible: bool,
290 impl fmt::Debug for PeerHandleError {
291 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
292 formatter.write_str("Peer Sent Invalid Data")
295 impl fmt::Display for PeerHandleError {
296 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
297 formatter.write_str("Peer Sent Invalid Data")
301 #[cfg(feature = "std")]
302 impl error::Error for PeerHandleError {
303 fn description(&self) -> &str {
304 "Peer Sent Invalid Data"
308 enum InitSyncTracker{
310 ChannelsSyncing(u64),
311 NodesSyncing(PublicKey),
314 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
315 /// forwarding gossip messages to peers altogether.
316 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
318 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
319 /// we have fewer than this many messages in the outbound buffer again.
320 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
321 /// refilled as we send bytes.
322 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
323 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
325 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
327 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
328 /// the socket receive buffer before receiving the ping.
330 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
331 /// including any network delays, outbound traffic, or the same for messages from other peers.
333 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
334 /// per connected peer to respond to a ping, as long as they send us at least one message during
335 /// each tick, ensuring we aren't actually just disconnected.
336 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
339 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
340 /// two connected peers, assuming most LDK-running systems have at least two cores.
341 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
343 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
344 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
345 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
346 /// process before the next ping.
348 /// Note that we continue responding to other messages even after we've sent this many messages, so
349 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
350 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
351 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
354 channel_encryptor: PeerChannelEncryptor,
355 their_node_id: Option<PublicKey>,
356 their_features: Option<InitFeatures>,
357 their_net_address: Option<NetAddress>,
359 pending_outbound_buffer: LinkedList<Vec<u8>>,
360 pending_outbound_buffer_first_msg_offset: usize,
361 // Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily prioritize
362 // channel messages over them.
363 gossip_broadcast_buffer: LinkedList<Vec<u8>>,
364 awaiting_write_event: bool,
366 pending_read_buffer: Vec<u8>,
367 pending_read_buffer_pos: usize,
368 pending_read_is_header: bool,
370 sync_status: InitSyncTracker,
372 msgs_sent_since_pong: usize,
373 awaiting_pong_timer_tick_intervals: i8,
374 received_message_since_timer_tick: bool,
375 sent_gossip_timestamp_filter: bool,
379 /// Returns true if the channel announcements/updates for the given channel should be
380 /// forwarded to this peer.
381 /// If we are sending our routing table to this peer and we have not yet sent channel
382 /// announcements/updates for the given channel_id then we will send it when we get to that
383 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
384 /// sent the old versions, we should send the update, and so return true here.
385 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
386 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
387 !self.sent_gossip_timestamp_filter {
390 match self.sync_status {
391 InitSyncTracker::NoSyncRequested => true,
392 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
393 InitSyncTracker::NodesSyncing(_) => true,
397 /// Similar to the above, but for node announcements indexed by node_id.
398 fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
399 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
400 !self.sent_gossip_timestamp_filter {
403 match self.sync_status {
404 InitSyncTracker::NoSyncRequested => true,
405 InitSyncTracker::ChannelsSyncing(_) => false,
406 InitSyncTracker::NodesSyncing(pk) => pk < node_id,
410 /// Returns whether we should be reading bytes from this peer, based on whether its outbound
411 /// buffer still has space and we don't need to pause reads to get some writes out.
412 fn should_read(&self) -> bool {
413 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE
416 /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
417 /// outbound buffer. This is checked every time the peer's buffer may have been drained.
418 fn should_buffer_gossip_backfill(&self) -> bool {
419 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
420 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
423 /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
424 /// every time the peer's buffer may have been drained.
425 fn should_buffer_onion_message(&self) -> bool {
426 self.pending_outbound_buffer.is_empty()
427 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
430 /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
431 /// buffer. This is checked every time the peer's buffer may have been drained.
432 fn should_buffer_gossip_broadcast(&self) -> bool {
433 self.pending_outbound_buffer.is_empty()
434 && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
437 /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
438 fn buffer_full_drop_gossip_broadcast(&self) -> bool {
439 let total_outbound_buffered =
440 self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
442 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
443 self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
447 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
448 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
449 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
450 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
451 /// issues such as overly long function definitions.
453 /// (C-not exported) as Arcs don't make sense in bindings
454 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>>;
456 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
457 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
458 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
459 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
460 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
461 /// helps with issues such as long function definitions.
463 /// (C-not exported) as Arcs don't make sense in bindings
464 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>;
466 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
467 /// socket events into messages which it passes on to its [`MessageHandler`].
469 /// Locks are taken internally, so you must never assume that reentrancy from a
470 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
472 /// Calls to [`read_event`] will decode relevant messages and pass them to the
473 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
474 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
475 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
476 /// calls only after previous ones have returned.
478 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
479 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
480 /// essentially you should default to using a SimpleRefPeerManager, and use a
481 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
482 /// you're using lightning-net-tokio.
484 /// [`read_event`]: PeerManager::read_event
485 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> where
486 CM::Target: ChannelMessageHandler,
487 RM::Target: RoutingMessageHandler,
488 OM::Target: OnionMessageHandler,
490 CMH::Target: CustomMessageHandler {
491 message_handler: MessageHandler<CM, RM, OM>,
492 /// Connection state for each connected peer - we have an outer read-write lock which is taken
493 /// as read while we're doing processing for a peer and taken write when a peer is being added
496 /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
497 /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
498 /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
499 /// the `MessageHandler`s for a given peer is already guaranteed.
500 peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
501 /// Only add to this set when noise completes.
502 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
503 /// lock held. Entries may be added with only the `peers` read lock held (though the
504 /// `Descriptor` value must already exist in `peers`).
505 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
506 /// We can only have one thread processing events at once, but we don't usually need the full
507 /// `peers` write lock to do so, so instead we block on this empty mutex when entering
508 /// `process_events`.
509 event_processing_lock: Mutex<()>,
510 /// Because event processing is global and always does all available work before returning,
511 /// there is no reason for us to have many event processors waiting on the lock at once.
512 /// Instead, we limit the total blocked event processors to always exactly one by setting this
513 /// when an event process call is waiting.
514 blocked_event_processors: AtomicBool,
516 /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
517 /// value increases strictly since we don't assume access to a time source.
518 last_node_announcement_serial: AtomicU64,
520 our_node_secret: SecretKey,
521 ephemeral_key_midstate: Sha256Engine,
522 custom_message_handler: CMH,
524 peer_counter: AtomicCounter,
527 secp_ctx: Secp256k1<secp256k1::SignOnly>
530 enum MessageHandlingError {
531 PeerHandleError(PeerHandleError),
532 LightningError(LightningError),
535 impl From<PeerHandleError> for MessageHandlingError {
536 fn from(error: PeerHandleError) -> Self {
537 MessageHandlingError::PeerHandleError(error)
541 impl From<LightningError> for MessageHandlingError {
542 fn from(error: LightningError) -> Self {
543 MessageHandlingError::LightningError(error)
547 macro_rules! encode_msg {
549 let mut buffer = VecWriter(Vec::new());
550 wire::write($msg, &mut buffer).unwrap();
555 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler> where
556 CM::Target: ChannelMessageHandler,
557 OM::Target: OnionMessageHandler,
559 /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
560 /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
563 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
564 /// cryptographically secure random bytes.
566 /// `current_time` is used as an always-increasing counter that survives across restarts and is
567 /// incremented irregularly internally. In general it is best to simply use the current UNIX
568 /// timestamp, however if it is not available a persistent counter that increases once per
569 /// minute should suffice.
571 /// (C-not exported) as we can't export a PeerManager with a dummy route handler
572 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 {
573 Self::new(MessageHandler {
574 chan_handler: channel_message_handler,
575 route_handler: IgnoringMessageHandler{},
576 onion_message_handler,
577 }, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
581 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
582 RM::Target: RoutingMessageHandler,
584 /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
585 /// handler or onion message handler is used and onion and channel messages will be ignored (or
586 /// generate error messages). Note that some other lightning implementations time-out connections
587 /// after some time if no channel is built with the peer.
589 /// `current_time` is used as an always-increasing counter that survives across restarts and is
590 /// incremented irregularly internally. In general it is best to simply use the current UNIX
591 /// timestamp, however if it is not available a persistent counter that increases once per
592 /// minute should suffice.
594 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
595 /// cryptographically secure random bytes.
597 /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
598 pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, current_time: u64, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
599 Self::new(MessageHandler {
600 chan_handler: ErroringMessageHandler::new(),
601 route_handler: routing_message_handler,
602 onion_message_handler: IgnoringMessageHandler{},
603 }, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
607 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
608 /// This works around `format!()` taking a reference to each argument, preventing
609 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
610 /// due to lifetime errors.
611 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
612 impl core::fmt::Display for OptionalFromDebugger<'_> {
613 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
614 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
618 /// A function used to filter out local or private addresses
619 /// https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml
620 /// https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
621 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
623 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
624 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
625 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
626 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
627 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
628 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
629 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
630 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
631 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
632 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
633 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
634 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
635 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
636 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
637 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
638 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
639 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
640 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
641 // For remaining addresses
642 Some(NetAddress::IPv6{addr: _, port: _}) => None,
643 Some(..) => ip_address,
648 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH> where
649 CM::Target: ChannelMessageHandler,
650 RM::Target: RoutingMessageHandler,
651 OM::Target: OnionMessageHandler,
653 CMH::Target: CustomMessageHandler {
654 /// Constructs a new PeerManager with the given message handlers and node_id secret key
655 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
656 /// cryptographically secure random bytes.
658 /// `current_time` is used as an always-increasing counter that survives across restarts and is
659 /// incremented irregularly internally. In general it is best to simply use the current UNIX
660 /// timestamp, however if it is not available a persistent counter that increases once per
661 /// minute should suffice.
662 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 {
663 let mut ephemeral_key_midstate = Sha256::engine();
664 ephemeral_key_midstate.input(ephemeral_random_data);
666 let mut secp_ctx = Secp256k1::signing_only();
667 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
668 secp_ctx.seeded_randomize(&ephemeral_hash);
672 peers: FairRwLock::new(HashMap::new()),
673 node_id_to_descriptor: Mutex::new(HashMap::new()),
674 event_processing_lock: Mutex::new(()),
675 blocked_event_processors: AtomicBool::new(false),
677 ephemeral_key_midstate,
678 peer_counter: AtomicCounter::new(),
679 last_node_announcement_serial: AtomicU64::new(current_time),
681 custom_message_handler,
686 /// Get the list of node ids for peers which have completed the initial handshake.
688 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
689 /// new_outbound_connection, however entries will only appear once the initial handshake has
690 /// completed and we are sure the remote peer has the private key for the given node_id.
691 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
692 let peers = self.peers.read().unwrap();
693 peers.values().filter_map(|peer_mutex| {
694 let p = peer_mutex.lock().unwrap();
695 if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
702 fn get_ephemeral_key(&self) -> SecretKey {
703 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
704 let counter = self.peer_counter.get_increment();
705 ephemeral_hash.input(&counter.to_le_bytes());
706 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
709 /// Indicates a new outbound connection has been established to a node with the given node_id
710 /// and an optional remote network address.
712 /// The remote network address adds the option to report a remote IP address back to a connecting
713 /// peer using the init message.
714 /// The user should pass the remote network address of the host they are connected to.
716 /// If an `Err` is returned here you must disconnect the connection immediately.
718 /// Returns a small number of bytes to send to the remote node (currently always 50).
720 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
721 /// [`socket_disconnected()`].
723 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
724 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
725 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
726 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
727 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
729 let mut peers = self.peers.write().unwrap();
730 if peers.insert(descriptor, Mutex::new(Peer {
731 channel_encryptor: peer_encryptor,
733 their_features: None,
734 their_net_address: remote_network_address,
736 pending_outbound_buffer: LinkedList::new(),
737 pending_outbound_buffer_first_msg_offset: 0,
738 gossip_broadcast_buffer: LinkedList::new(),
739 awaiting_write_event: false,
742 pending_read_buffer_pos: 0,
743 pending_read_is_header: false,
745 sync_status: InitSyncTracker::NoSyncRequested,
747 msgs_sent_since_pong: 0,
748 awaiting_pong_timer_tick_intervals: 0,
749 received_message_since_timer_tick: false,
750 sent_gossip_timestamp_filter: false,
752 panic!("PeerManager driver duplicated descriptors!");
757 /// Indicates a new inbound connection has been established to a node with an optional remote
760 /// The remote network address adds the option to report a remote IP address back to a connecting
761 /// peer using the init message.
762 /// The user should pass the remote network address of the host they are connected to.
764 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
765 /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
766 /// the connection immediately.
768 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
769 /// [`socket_disconnected()`].
771 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
772 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
773 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret, &self.secp_ctx);
774 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
776 let mut peers = self.peers.write().unwrap();
777 if peers.insert(descriptor, Mutex::new(Peer {
778 channel_encryptor: peer_encryptor,
780 their_features: None,
781 their_net_address: remote_network_address,
783 pending_outbound_buffer: LinkedList::new(),
784 pending_outbound_buffer_first_msg_offset: 0,
785 gossip_broadcast_buffer: LinkedList::new(),
786 awaiting_write_event: false,
789 pending_read_buffer_pos: 0,
790 pending_read_is_header: false,
792 sync_status: InitSyncTracker::NoSyncRequested,
794 msgs_sent_since_pong: 0,
795 awaiting_pong_timer_tick_intervals: 0,
796 received_message_since_timer_tick: false,
797 sent_gossip_timestamp_filter: false,
799 panic!("PeerManager driver duplicated descriptors!");
804 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
805 while !peer.awaiting_write_event {
806 if peer.should_buffer_onion_message() {
807 if let Some(peer_node_id) = peer.their_node_id {
808 if let Some(next_onion_message) =
809 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
810 self.enqueue_message(peer, &next_onion_message);
814 if peer.should_buffer_gossip_broadcast() {
815 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
816 peer.pending_outbound_buffer.push_back(msg);
819 if peer.should_buffer_gossip_backfill() {
820 match peer.sync_status {
821 InitSyncTracker::NoSyncRequested => {},
822 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
823 if let Some((announce, update_a_option, update_b_option)) =
824 self.message_handler.route_handler.get_next_channel_announcement(c)
826 self.enqueue_message(peer, &announce);
827 if let Some(update_a) = update_a_option {
828 self.enqueue_message(peer, &update_a);
830 if let Some(update_b) = update_b_option {
831 self.enqueue_message(peer, &update_b);
833 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
835 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
838 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
839 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
840 self.enqueue_message(peer, &msg);
841 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
843 peer.sync_status = InitSyncTracker::NoSyncRequested;
846 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
847 InitSyncTracker::NodesSyncing(key) => {
848 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&key)) {
849 self.enqueue_message(peer, &msg);
850 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
852 peer.sync_status = InitSyncTracker::NoSyncRequested;
857 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
858 self.maybe_send_extra_ping(peer);
861 let next_buff = match peer.pending_outbound_buffer.front() {
866 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
867 let data_sent = descriptor.send_data(pending, peer.should_read());
868 peer.pending_outbound_buffer_first_msg_offset += data_sent;
869 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
870 peer.pending_outbound_buffer_first_msg_offset = 0;
871 peer.pending_outbound_buffer.pop_front();
873 peer.awaiting_write_event = true;
878 /// Indicates that there is room to write data to the given socket descriptor.
880 /// May return an Err to indicate that the connection should be closed.
882 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
883 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
884 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
885 /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
888 /// [`send_data`]: SocketDescriptor::send_data
889 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
890 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
891 let peers = self.peers.read().unwrap();
892 match peers.get(descriptor) {
894 // This is most likely a simple race condition where the user found that the socket
895 // was writeable, then we told the user to `disconnect_socket()`, then they called
896 // this method. Return an error to make sure we get disconnected.
897 return Err(PeerHandleError { no_connection_possible: false });
899 Some(peer_mutex) => {
900 let mut peer = peer_mutex.lock().unwrap();
901 peer.awaiting_write_event = false;
902 self.do_attempt_write_data(descriptor, &mut peer);
908 /// Indicates that data was read from the given socket descriptor.
910 /// May return an Err to indicate that the connection should be closed.
912 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
913 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
914 /// [`send_data`] calls to handle responses.
916 /// If `Ok(true)` is returned, further read_events should not be triggered until a
917 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
920 /// [`send_data`]: SocketDescriptor::send_data
921 /// [`process_events`]: PeerManager::process_events
922 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
923 match self.do_read_event(peer_descriptor, data) {
926 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
927 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
933 /// Append a message to a peer's pending outbound/write buffer
934 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
935 let mut buffer = VecWriter(Vec::with_capacity(2048));
936 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
938 if is_gossip_msg(message.type_id()) {
939 log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
941 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
943 peer.msgs_sent_since_pong += 1;
944 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&buffer.0[..]));
947 /// Append a message to a peer's pending outbound/write gossip broadcast buffer
948 fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
949 peer.msgs_sent_since_pong += 1;
950 peer.gossip_broadcast_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
953 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
954 let mut pause_read = false;
955 let peers = self.peers.read().unwrap();
956 let mut msgs_to_forward = Vec::new();
957 let mut peer_node_id = None;
958 match peers.get(peer_descriptor) {
960 // This is most likely a simple race condition where the user read some bytes
961 // from the socket, then we told the user to `disconnect_socket()`, then they
962 // called this method. Return an error to make sure we get disconnected.
963 return Err(PeerHandleError { no_connection_possible: false });
965 Some(peer_mutex) => {
966 let mut read_pos = 0;
967 while read_pos < data.len() {
968 macro_rules! try_potential_handleerror {
969 ($peer: expr, $thing: expr) => {
974 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
975 //TODO: Try to push msg
976 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
977 return Err(PeerHandleError{ no_connection_possible: false });
979 msgs::ErrorAction::IgnoreAndLog(level) => {
980 log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
983 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
984 msgs::ErrorAction::IgnoreError => {
985 log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
988 msgs::ErrorAction::SendErrorMessage { msg } => {
989 log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
990 self.enqueue_message($peer, &msg);
993 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
994 log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
995 self.enqueue_message($peer, &msg);
1004 let mut peer_lock = peer_mutex.lock().unwrap();
1005 let peer = &mut *peer_lock;
1006 let mut msg_to_handle = None;
1007 if peer_node_id.is_none() {
1008 peer_node_id = peer.their_node_id.clone();
1011 assert!(peer.pending_read_buffer.len() > 0);
1012 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1015 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1016 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]);
1017 read_pos += data_to_copy;
1018 peer.pending_read_buffer_pos += data_to_copy;
1021 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1022 peer.pending_read_buffer_pos = 0;
1024 macro_rules! insert_node_id {
1026 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap()) {
1027 hash_map::Entry::Occupied(_) => {
1028 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
1029 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1030 return Err(PeerHandleError{ no_connection_possible: false })
1032 hash_map::Entry::Vacant(entry) => {
1033 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
1034 entry.insert(peer_descriptor.clone())
1040 let next_step = peer.channel_encryptor.get_noise_step();
1042 NextNoiseStep::ActOne => {
1043 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1044 .process_act_one_with_keys(&peer.pending_read_buffer[..],
1045 &self.our_node_secret, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1046 peer.pending_outbound_buffer.push_back(act_two);
1047 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1049 NextNoiseStep::ActTwo => {
1050 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1051 peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1052 &self.our_node_secret, &self.secp_ctx));
1053 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1054 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1055 peer.pending_read_is_header = true;
1057 peer.their_node_id = Some(their_node_id);
1059 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1060 .or(self.message_handler.route_handler.provided_init_features(&their_node_id));
1061 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1062 self.enqueue_message(peer, &resp);
1063 peer.awaiting_pong_timer_tick_intervals = 0;
1065 NextNoiseStep::ActThree => {
1066 let their_node_id = try_potential_handleerror!(peer,
1067 peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1068 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1069 peer.pending_read_is_header = true;
1070 peer.their_node_id = Some(their_node_id);
1072 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id)
1073 .or(self.message_handler.route_handler.provided_init_features(&their_node_id));
1074 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1075 self.enqueue_message(peer, &resp);
1076 peer.awaiting_pong_timer_tick_intervals = 0;
1078 NextNoiseStep::NoiseComplete => {
1079 if peer.pending_read_is_header {
1080 let msg_len = try_potential_handleerror!(peer,
1081 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1082 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1083 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1084 if msg_len < 2 { // Need at least the message type tag
1085 return Err(PeerHandleError{ no_connection_possible: false });
1087 peer.pending_read_is_header = false;
1089 let msg_data = try_potential_handleerror!(peer,
1090 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1091 assert!(msg_data.len() >= 2);
1093 // Reset read buffer
1094 if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1095 peer.pending_read_buffer.resize(18, 0);
1096 peer.pending_read_is_header = true;
1098 let mut reader = io::Cursor::new(&msg_data[..]);
1099 let message_result = wire::read(&mut reader, &*self.custom_message_handler);
1100 let message = match message_result {
1104 // Note that to avoid recursion we never call
1105 // `do_attempt_write_data` from here, causing
1106 // the messages enqueued here to not actually
1107 // be sent before the peer is disconnected.
1108 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1109 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1112 (msgs::DecodeError::UnsupportedCompression, _) => {
1113 log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1114 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1117 (_, Some(ty)) if is_gossip_msg(ty) => {
1118 log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1119 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unreadable/bogus gossip message".to_owned() });
1122 (msgs::DecodeError::UnknownRequiredFeature, ty) => {
1123 log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1124 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
1125 return Err(PeerHandleError { no_connection_possible: false });
1127 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }),
1128 (msgs::DecodeError::InvalidValue, _) => {
1129 log_debug!(self.logger, "Got an invalid value while deserializing message");
1130 return Err(PeerHandleError { no_connection_possible: false });
1132 (msgs::DecodeError::ShortRead, _) => {
1133 log_debug!(self.logger, "Deserialization failed due to shortness of message");
1134 return Err(PeerHandleError { no_connection_possible: false });
1136 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }),
1137 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }),
1142 msg_to_handle = Some(message);
1147 pause_read = !peer.should_read();
1149 if let Some(message) = msg_to_handle {
1150 match self.handle_message(&peer_mutex, peer_lock, message) {
1151 Err(handling_error) => match handling_error {
1152 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1153 MessageHandlingError::LightningError(e) => {
1154 try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1158 msgs_to_forward.push(msg);
1167 for msg in msgs_to_forward.drain(..) {
1168 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref());
1174 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1175 /// Returns the message back if it needs to be broadcasted to all other peers.
1178 peer_mutex: &Mutex<Peer>,
1179 mut peer_lock: MutexGuard<Peer>,
1180 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1181 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1182 let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages");
1183 peer_lock.received_message_since_timer_tick = true;
1185 // Need an Init as first message
1186 if let wire::Message::Init(msg) = message {
1187 if msg.features.requires_unknown_bits() {
1188 log_debug!(self.logger, "Peer features required unknown version bits");
1189 return Err(PeerHandleError{ no_connection_possible: true }.into());
1191 if peer_lock.their_features.is_some() {
1192 return Err(PeerHandleError{ no_connection_possible: false }.into());
1195 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1197 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1198 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1199 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1202 if !msg.features.supports_static_remote_key() {
1203 log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(their_node_id));
1204 return Err(PeerHandleError{ no_connection_possible: true }.into());
1207 self.message_handler.route_handler.peer_connected(&their_node_id, &msg);
1208 self.message_handler.chan_handler.peer_connected(&their_node_id, &msg);
1209 self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg);
1211 peer_lock.their_features = Some(msg.features);
1213 } else if peer_lock.their_features.is_none() {
1214 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1215 return Err(PeerHandleError{ no_connection_possible: false }.into());
1218 if let wire::Message::GossipTimestampFilter(_msg) = message {
1219 // When supporting gossip messages, start inital gossip sync only after we receive
1220 // a GossipTimestampFilter
1221 if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1222 !peer_lock.sent_gossip_timestamp_filter {
1223 peer_lock.sent_gossip_timestamp_filter = true;
1224 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1229 let their_features = peer_lock.their_features.clone();
1230 mem::drop(peer_lock);
1232 if is_gossip_msg(message.type_id()) {
1233 log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1235 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1238 let mut should_forward = None;
1241 // Setup and Control messages:
1242 wire::Message::Init(_) => {
1245 wire::Message::GossipTimestampFilter(_) => {
1248 wire::Message::Error(msg) => {
1249 let mut data_is_printable = true;
1250 for b in msg.data.bytes() {
1251 if b < 32 || b > 126 {
1252 data_is_printable = false;
1257 if data_is_printable {
1258 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1260 log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1262 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1263 if msg.channel_id == [0; 32] {
1264 return Err(PeerHandleError{ no_connection_possible: true }.into());
1267 wire::Message::Warning(msg) => {
1268 let mut data_is_printable = true;
1269 for b in msg.data.bytes() {
1270 if b < 32 || b > 126 {
1271 data_is_printable = false;
1276 if data_is_printable {
1277 log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1279 log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1283 wire::Message::Ping(msg) => {
1284 if msg.ponglen < 65532 {
1285 let resp = msgs::Pong { byteslen: msg.ponglen };
1286 self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1289 wire::Message::Pong(_msg) => {
1290 let mut peer_lock = peer_mutex.lock().unwrap();
1291 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1292 peer_lock.msgs_sent_since_pong = 0;
1295 // Channel messages:
1296 wire::Message::OpenChannel(msg) => {
1297 self.message_handler.chan_handler.handle_open_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1299 wire::Message::AcceptChannel(msg) => {
1300 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1303 wire::Message::FundingCreated(msg) => {
1304 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1306 wire::Message::FundingSigned(msg) => {
1307 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1309 wire::Message::ChannelReady(msg) => {
1310 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1313 wire::Message::Shutdown(msg) => {
1314 self.message_handler.chan_handler.handle_shutdown(&their_node_id, their_features.as_ref().unwrap(), &msg);
1316 wire::Message::ClosingSigned(msg) => {
1317 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1320 // Commitment messages:
1321 wire::Message::UpdateAddHTLC(msg) => {
1322 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1324 wire::Message::UpdateFulfillHTLC(msg) => {
1325 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1327 wire::Message::UpdateFailHTLC(msg) => {
1328 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1330 wire::Message::UpdateFailMalformedHTLC(msg) => {
1331 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1334 wire::Message::CommitmentSigned(msg) => {
1335 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1337 wire::Message::RevokeAndACK(msg) => {
1338 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1340 wire::Message::UpdateFee(msg) => {
1341 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1343 wire::Message::ChannelReestablish(msg) => {
1344 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1347 // Routing messages:
1348 wire::Message::AnnouncementSignatures(msg) => {
1349 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1351 wire::Message::ChannelAnnouncement(msg) => {
1352 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1353 .map_err(|e| -> MessageHandlingError { e.into() })? {
1354 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1357 wire::Message::NodeAnnouncement(msg) => {
1358 if self.message_handler.route_handler.handle_node_announcement(&msg)
1359 .map_err(|e| -> MessageHandlingError { e.into() })? {
1360 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1363 wire::Message::ChannelUpdate(msg) => {
1364 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1365 if self.message_handler.route_handler.handle_channel_update(&msg)
1366 .map_err(|e| -> MessageHandlingError { e.into() })? {
1367 should_forward = Some(wire::Message::ChannelUpdate(msg));
1370 wire::Message::QueryShortChannelIds(msg) => {
1371 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1373 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1374 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1376 wire::Message::QueryChannelRange(msg) => {
1377 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1379 wire::Message::ReplyChannelRange(msg) => {
1380 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1384 wire::Message::OnionMessage(msg) => {
1385 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1388 // Unknown messages:
1389 wire::Message::Unknown(type_id) if message.is_even() => {
1390 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1391 // Fail the channel if message is an even, unknown type as per BOLT #1.
1392 return Err(PeerHandleError{ no_connection_possible: true }.into());
1394 wire::Message::Unknown(type_id) => {
1395 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1397 wire::Message::Custom(custom) => {
1398 self.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1404 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>) {
1406 wire::Message::ChannelAnnouncement(ref msg) => {
1407 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1408 let encoded_msg = encode_msg!(msg);
1410 for (_, peer_mutex) in peers.iter() {
1411 let mut peer = peer_mutex.lock().unwrap();
1412 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1413 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1416 if peer.buffer_full_drop_gossip_broadcast() {
1417 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1420 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1421 peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1424 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1427 self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1430 wire::Message::NodeAnnouncement(ref msg) => {
1431 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1432 let encoded_msg = encode_msg!(msg);
1434 for (_, peer_mutex) in peers.iter() {
1435 let mut peer = peer_mutex.lock().unwrap();
1436 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1437 !peer.should_forward_node_announcement(msg.contents.node_id) {
1440 if peer.buffer_full_drop_gossip_broadcast() {
1441 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1444 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1447 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1450 self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1453 wire::Message::ChannelUpdate(ref msg) => {
1454 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1455 let encoded_msg = encode_msg!(msg);
1457 for (_, peer_mutex) in peers.iter() {
1458 let mut peer = peer_mutex.lock().unwrap();
1459 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1460 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1463 if peer.buffer_full_drop_gossip_broadcast() {
1464 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1467 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1470 self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1473 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1477 /// Checks for any events generated by our handlers and processes them. Includes sending most
1478 /// response messages as well as messages generated by calls to handler functions directly (eg
1479 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1481 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1484 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1485 /// or one of the other clients provided in our language bindings.
1487 /// Note that if there are any other calls to this function waiting on lock(s) this may return
1488 /// without doing any work. All available events that need handling will be handled before the
1489 /// other calls return.
1491 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1492 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1493 /// [`send_data`]: SocketDescriptor::send_data
1494 pub fn process_events(&self) {
1495 let mut _single_processor_lock = self.event_processing_lock.try_lock();
1496 if _single_processor_lock.is_err() {
1497 // While we could wake the older sleeper here with a CV and make more even waiting
1498 // times, that would be a lot of overengineering for a simple "reduce total waiter
1500 match self.blocked_event_processors.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) {
1502 debug_assert!(val, "compare_exchange failed spuriously?");
1506 debug_assert!(!val, "compare_exchange succeeded spuriously?");
1507 // We're the only waiter, as the running process_events may have emptied the
1508 // pending events "long" ago and there are new events for us to process, wait until
1509 // its done and process any leftover events before returning.
1510 _single_processor_lock = Ok(self.event_processing_lock.lock().unwrap());
1511 self.blocked_event_processors.store(false, Ordering::Release);
1516 let mut peers_to_disconnect = HashMap::new();
1517 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1518 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1521 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1522 // buffer by doing things like announcing channels on another node. We should be willing to
1523 // drop optional-ish messages when send buffers get full!
1525 let peers_lock = self.peers.read().unwrap();
1526 let peers = &*peers_lock;
1527 macro_rules! get_peer_for_forwarding {
1528 ($node_id: expr) => {
1530 if peers_to_disconnect.get($node_id).is_some() {
1531 // If we've "disconnected" this peer, do not send to it.
1534 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1535 match descriptor_opt {
1536 Some(descriptor) => match peers.get(&descriptor) {
1537 Some(peer_mutex) => {
1538 let peer_lock = peer_mutex.lock().unwrap();
1539 if peer_lock.their_features.is_none() {
1545 debug_assert!(false, "Inconsistent peers set state!");
1556 for event in events_generated.drain(..) {
1558 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1559 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1560 log_pubkey!(node_id),
1561 log_bytes!(msg.temporary_channel_id));
1562 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1564 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1565 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1566 log_pubkey!(node_id),
1567 log_bytes!(msg.temporary_channel_id));
1568 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1570 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1571 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1572 log_pubkey!(node_id),
1573 log_bytes!(msg.temporary_channel_id),
1574 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1575 // TODO: If the peer is gone we should generate a DiscardFunding event
1576 // indicating to the wallet that they should just throw away this funding transaction
1577 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1579 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1580 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1581 log_pubkey!(node_id),
1582 log_bytes!(msg.channel_id));
1583 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1585 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1586 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1587 log_pubkey!(node_id),
1588 log_bytes!(msg.channel_id));
1589 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1591 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1592 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1593 log_pubkey!(node_id),
1594 log_bytes!(msg.channel_id));
1595 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1597 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 } } => {
1598 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1599 log_pubkey!(node_id),
1600 update_add_htlcs.len(),
1601 update_fulfill_htlcs.len(),
1602 update_fail_htlcs.len(),
1603 log_bytes!(commitment_signed.channel_id));
1604 let mut peer = get_peer_for_forwarding!(node_id);
1605 for msg in update_add_htlcs {
1606 self.enqueue_message(&mut *peer, msg);
1608 for msg in update_fulfill_htlcs {
1609 self.enqueue_message(&mut *peer, msg);
1611 for msg in update_fail_htlcs {
1612 self.enqueue_message(&mut *peer, msg);
1614 for msg in update_fail_malformed_htlcs {
1615 self.enqueue_message(&mut *peer, msg);
1617 if let &Some(ref msg) = update_fee {
1618 self.enqueue_message(&mut *peer, msg);
1620 self.enqueue_message(&mut *peer, commitment_signed);
1622 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1623 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1624 log_pubkey!(node_id),
1625 log_bytes!(msg.channel_id));
1626 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1628 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1629 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1630 log_pubkey!(node_id),
1631 log_bytes!(msg.channel_id));
1632 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1634 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1635 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1636 log_pubkey!(node_id),
1637 log_bytes!(msg.channel_id));
1638 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1640 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1641 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1642 log_pubkey!(node_id),
1643 log_bytes!(msg.channel_id));
1644 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1646 MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
1647 log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
1648 log_pubkey!(node_id),
1649 msg.contents.short_channel_id);
1650 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1651 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
1653 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1654 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1655 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1656 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1657 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1660 match self.message_handler.route_handler.handle_channel_update(&update_msg) {
1661 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1662 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None),
1666 MessageSendEvent::BroadcastChannelUpdate { msg } => {
1667 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1668 match self.message_handler.route_handler.handle_channel_update(&msg) {
1669 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1670 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1674 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1675 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1676 log_pubkey!(node_id), msg.contents.short_channel_id);
1677 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1679 MessageSendEvent::HandleError { ref node_id, ref action } => {
1681 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1682 // We do not have the peers write lock, so we just store that we're
1683 // about to disconenct the peer and do it after we finish
1684 // processing most messages.
1685 peers_to_disconnect.insert(*node_id, msg.clone());
1687 msgs::ErrorAction::IgnoreAndLog(level) => {
1688 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1690 msgs::ErrorAction::IgnoreDuplicateGossip => {},
1691 msgs::ErrorAction::IgnoreError => {
1692 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1694 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1695 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1696 log_pubkey!(node_id),
1698 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1700 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1701 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1702 log_pubkey!(node_id),
1704 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1708 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1709 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1711 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1712 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1714 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1715 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1716 log_pubkey!(node_id),
1717 msg.short_channel_ids.len(),
1719 msg.number_of_blocks,
1721 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1723 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
1724 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1729 for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1730 if peers_to_disconnect.get(&node_id).is_some() { continue; }
1731 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
1734 for (descriptor, peer_mutex) in peers.iter() {
1735 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer_mutex.lock().unwrap());
1738 if !peers_to_disconnect.is_empty() {
1739 let mut peers_lock = self.peers.write().unwrap();
1740 let peers = &mut *peers_lock;
1741 for (node_id, msg) in peers_to_disconnect.drain() {
1742 // Note that since we are holding the peers *write* lock we can
1743 // remove from node_id_to_descriptor immediately (as no other
1744 // thread can be holding the peer lock if we have the global write
1747 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1748 if let Some(peer_mutex) = peers.remove(&descriptor) {
1749 if let Some(msg) = msg {
1750 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1751 log_pubkey!(node_id),
1753 let mut peer = peer_mutex.lock().unwrap();
1754 self.enqueue_message(&mut *peer, &msg);
1755 // This isn't guaranteed to work, but if there is enough free
1756 // room in the send buffer, put the error message there...
1757 self.do_attempt_write_data(&mut descriptor, &mut *peer);
1759 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1762 descriptor.disconnect_socket();
1763 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1764 self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1770 /// Indicates that the given socket descriptor's connection is now closed.
1771 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1772 self.disconnect_event_internal(descriptor, false);
1775 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1776 let mut peers = self.peers.write().unwrap();
1777 let peer_option = peers.remove(descriptor);
1780 // This is most likely a simple race condition where the user found that the socket
1781 // was disconnected, then we told the user to `disconnect_socket()`, then they
1782 // called this method. Either way we're disconnected, return.
1784 Some(peer_lock) => {
1785 let peer = peer_lock.lock().unwrap();
1786 if let Some(node_id) = peer.their_node_id {
1787 log_trace!(self.logger,
1788 "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1789 log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1790 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1791 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1792 self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1798 /// Disconnect a peer given its node id.
1800 /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1801 /// force-closing any channels we have with it.
1803 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1804 /// peer. Thus, be very careful about reentrancy issues.
1806 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1807 pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1808 let mut peers_lock = self.peers.write().unwrap();
1809 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1810 log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1811 peers_lock.remove(&descriptor);
1812 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1813 self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1814 descriptor.disconnect_socket();
1818 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1819 /// an indication that TCP sockets have stalled even if we weren't around to time them out
1820 /// using regular ping/pongs.
1821 pub fn disconnect_all_peers(&self) {
1822 let mut peers_lock = self.peers.write().unwrap();
1823 self.node_id_to_descriptor.lock().unwrap().clear();
1824 let peers = &mut *peers_lock;
1825 for (mut descriptor, peer) in peers.drain() {
1826 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1827 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1828 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1829 self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1831 descriptor.disconnect_socket();
1835 /// This is called when we're blocked on sending additional gossip messages until we receive a
1836 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1837 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1838 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1839 if peer.awaiting_pong_timer_tick_intervals == 0 {
1840 peer.awaiting_pong_timer_tick_intervals = -1;
1841 let ping = msgs::Ping {
1845 self.enqueue_message(peer, &ping);
1849 /// Send pings to each peer and disconnect those which did not respond to the last round of
1852 /// This may be called on any timescale you want, however, roughly once every ten seconds is
1853 /// preferred. The call rate determines both how often we send a ping to our peers and how much
1854 /// time they have to respond before we disconnect them.
1856 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1859 /// [`send_data`]: SocketDescriptor::send_data
1860 pub fn timer_tick_occurred(&self) {
1861 let mut descriptors_needing_disconnect = Vec::new();
1863 let peers_lock = self.peers.read().unwrap();
1865 for (descriptor, peer_mutex) in peers_lock.iter() {
1866 let mut peer = peer_mutex.lock().unwrap();
1867 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1868 // The peer needs to complete its handshake before we can exchange messages. We
1869 // give peers one timer tick to complete handshake, reusing
1870 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1871 // for handshake completion.
1872 if peer.awaiting_pong_timer_tick_intervals != 0 {
1873 descriptors_needing_disconnect.push(descriptor.clone());
1875 peer.awaiting_pong_timer_tick_intervals = 1;
1880 if peer.awaiting_pong_timer_tick_intervals == -1 {
1881 // Magic value set in `maybe_send_extra_ping`.
1882 peer.awaiting_pong_timer_tick_intervals = 1;
1883 peer.received_message_since_timer_tick = false;
1887 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1888 || peer.awaiting_pong_timer_tick_intervals as u64 >
1889 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
1891 descriptors_needing_disconnect.push(descriptor.clone());
1894 peer.received_message_since_timer_tick = false;
1896 if peer.awaiting_pong_timer_tick_intervals > 0 {
1897 peer.awaiting_pong_timer_tick_intervals += 1;
1901 peer.awaiting_pong_timer_tick_intervals = 1;
1902 let ping = msgs::Ping {
1906 self.enqueue_message(&mut *peer, &ping);
1907 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1911 if !descriptors_needing_disconnect.is_empty() {
1913 let mut peers_lock = self.peers.write().unwrap();
1914 for descriptor in descriptors_needing_disconnect.iter() {
1915 if let Some(peer) = peers_lock.remove(descriptor) {
1916 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1917 log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1918 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1919 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1920 self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1926 for mut descriptor in descriptors_needing_disconnect.drain(..) {
1927 descriptor.disconnect_socket();
1933 // Messages of up to 64KB should never end up more than half full with addresses, as that would
1934 // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
1935 // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1937 const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1940 // ...by failing to compile if the number of addresses that would be half of a message is
1941 // smaller than 100:
1942 const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
1944 /// Generates a signed node_announcement from the given arguments, sending it to all connected
1945 /// peers. Note that peers will likely ignore this message unless we have at least one public
1946 /// channel which has at least six confirmations on-chain.
1948 /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
1949 /// node to humans. They carry no in-protocol meaning.
1951 /// `addresses` represent the set (possibly empty) of socket addresses on which this node
1952 /// accepts incoming connections. These will be included in the node_announcement, publicly
1953 /// tying these addresses together and to this node. If you wish to preserve user privacy,
1954 /// addresses should likely contain only Tor Onion addresses.
1956 /// Panics if `addresses` is absurdly large (more than 100).
1958 /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
1959 pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
1960 if addresses.len() > 100 {
1961 panic!("More than half the message size was taken up by public addresses!");
1964 // While all existing nodes handle unsorted addresses just fine, the spec requires that
1965 // addresses be sorted for future compatibility.
1966 addresses.sort_by_key(|addr| addr.get_id());
1968 let announcement = msgs::UnsignedNodeAnnouncement {
1969 features: self.message_handler.chan_handler.provided_node_features(),
1970 timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1971 node_id: PublicKey::from_secret_key(&self.secp_ctx, &self.our_node_secret),
1972 rgb, alias, addresses,
1973 excess_address_data: Vec::new(),
1974 excess_data: Vec::new(),
1976 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1977 let node_announce_sig = sign(&self.secp_ctx, &msghash, &self.our_node_secret);
1979 let msg = msgs::NodeAnnouncement {
1980 signature: node_announce_sig,
1981 contents: announcement
1984 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
1985 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
1986 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
1990 fn is_gossip_msg(type_id: u16) -> bool {
1992 msgs::ChannelAnnouncement::TYPE |
1993 msgs::ChannelUpdate::TYPE |
1994 msgs::NodeAnnouncement::TYPE |
1995 msgs::QueryChannelRange::TYPE |
1996 msgs::ReplyChannelRange::TYPE |
1997 msgs::QueryShortChannelIds::TYPE |
1998 msgs::ReplyShortChannelIdsEnd::TYPE => true,
2005 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2006 use ln::{msgs, wire};
2007 use ln::msgs::NetAddress;
2009 use util::test_utils;
2011 use bitcoin::secp256k1::Secp256k1;
2012 use bitcoin::secp256k1::{SecretKey, PublicKey};
2015 use sync::{Arc, Mutex};
2016 use core::sync::atomic::Ordering;
2019 struct FileDescriptor {
2021 outbound_data: Arc<Mutex<Vec<u8>>>,
2023 impl PartialEq for FileDescriptor {
2024 fn eq(&self, other: &Self) -> bool {
2028 impl Eq for FileDescriptor { }
2029 impl core::hash::Hash for FileDescriptor {
2030 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2031 self.fd.hash(hasher)
2035 impl SocketDescriptor for FileDescriptor {
2036 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2037 self.outbound_data.lock().unwrap().extend_from_slice(data);
2041 fn disconnect_socket(&mut self) {}
2044 struct PeerManagerCfg {
2045 chan_handler: test_utils::TestChannelMessageHandler,
2046 routing_handler: test_utils::TestRoutingMessageHandler,
2047 logger: test_utils::TestLogger,
2050 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2051 let mut cfgs = Vec::new();
2052 for _ in 0..peer_count {
2055 chan_handler: test_utils::TestChannelMessageHandler::new(),
2056 logger: test_utils::TestLogger::new(),
2057 routing_handler: test_utils::TestRoutingMessageHandler::new(),
2065 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>> {
2066 let mut peers = Vec::new();
2067 for i in 0..peer_count {
2068 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2069 let ephemeral_bytes = [i as u8; 32];
2070 let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler, onion_message_handler: IgnoringMessageHandler {} };
2071 let peer = PeerManager::new(msg_handler, node_secret, 0, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
2078 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) {
2079 let secp_ctx = Secp256k1::new();
2080 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
2081 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2082 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2083 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2084 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
2085 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2086 peer_a.process_events();
2088 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2089 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2091 peer_b.process_events();
2092 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2093 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2095 peer_a.process_events();
2096 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2097 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2099 (fd_a.clone(), fd_b.clone())
2103 fn test_disconnect_peer() {
2104 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2105 // push a DisconnectPeer event to remove the node flagged by id
2106 let cfgs = create_peermgr_cfgs(2);
2107 let chan_handler = test_utils::TestChannelMessageHandler::new();
2108 let mut peers = create_network(2, &cfgs);
2109 establish_connection(&peers[0], &peers[1]);
2110 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2112 let secp_ctx = Secp256k1::new();
2113 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2115 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2117 action: msgs::ErrorAction::DisconnectPeer { msg: None },
2119 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
2120 peers[0].message_handler.chan_handler = &chan_handler;
2122 peers[0].process_events();
2123 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2127 fn test_send_simple_msg() {
2128 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2129 // push a message from one peer to another.
2130 let cfgs = create_peermgr_cfgs(2);
2131 let a_chan_handler = test_utils::TestChannelMessageHandler::new();
2132 let b_chan_handler = test_utils::TestChannelMessageHandler::new();
2133 let mut peers = create_network(2, &cfgs);
2134 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2135 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2137 let secp_ctx = Secp256k1::new();
2138 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2140 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2141 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2142 node_id: their_id, msg: msg.clone()
2144 peers[0].message_handler.chan_handler = &a_chan_handler;
2146 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2147 peers[1].message_handler.chan_handler = &b_chan_handler;
2149 peers[0].process_events();
2151 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2152 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2156 fn test_disconnect_all_peer() {
2157 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2158 // then calls disconnect_all_peers
2159 let cfgs = create_peermgr_cfgs(2);
2160 let peers = create_network(2, &cfgs);
2161 establish_connection(&peers[0], &peers[1]);
2162 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2164 peers[0].disconnect_all_peers();
2165 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2169 fn test_timer_tick_occurred() {
2170 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2171 let cfgs = create_peermgr_cfgs(2);
2172 let peers = create_network(2, &cfgs);
2173 establish_connection(&peers[0], &peers[1]);
2174 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2176 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2177 peers[0].timer_tick_occurred();
2178 peers[0].process_events();
2179 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2181 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2182 peers[0].timer_tick_occurred();
2183 peers[0].process_events();
2184 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2188 fn test_do_attempt_write_data() {
2189 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2190 let cfgs = create_peermgr_cfgs(2);
2191 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2192 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2193 let peers = create_network(2, &cfgs);
2195 // By calling establish_connect, we trigger do_attempt_write_data between
2196 // the peers. Previously this function would mistakenly enter an infinite loop
2197 // when there were more channel messages available than could fit into a peer's
2198 // buffer. This issue would now be detected by this test (because we use custom
2199 // RoutingMessageHandlers that intentionally return more channel messages
2200 // than can fit into a peer's buffer).
2201 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2203 // Make each peer to read the messages that the other peer just wrote to them. Note that
2204 // due to the max-message-before-ping limits this may take a few iterations to complete.
2205 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2206 peers[1].process_events();
2207 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2208 assert!(!a_read_data.is_empty());
2210 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2211 peers[0].process_events();
2213 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2214 assert!(!b_read_data.is_empty());
2215 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2217 peers[0].process_events();
2218 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2221 // Check that each peer has received the expected number of channel updates and channel
2223 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2224 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2225 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2226 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2230 fn test_handshake_timeout() {
2231 // Tests that we time out a peer still waiting on handshake completion after a full timer
2233 let cfgs = create_peermgr_cfgs(2);
2234 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2235 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2236 let peers = create_network(2, &cfgs);
2238 let secp_ctx = Secp256k1::new();
2239 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
2240 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2241 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2242 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2243 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
2245 // If we get a single timer tick before completion, that's fine
2246 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2247 peers[0].timer_tick_occurred();
2248 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2250 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
2251 peers[0].process_events();
2252 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2253 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2254 peers[1].process_events();
2256 // ...but if we get a second timer tick, we should disconnect the peer
2257 peers[0].timer_tick_occurred();
2258 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2260 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2261 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
2265 fn test_filter_addresses(){
2266 // Tests the filter_addresses function.
2269 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
2270 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2271 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
2272 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2273 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
2274 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2277 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
2278 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2279 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
2280 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2281 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
2282 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2285 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
2286 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2287 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
2288 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2289 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
2290 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2293 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
2294 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2295 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
2296 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2297 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
2298 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2301 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
2302 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2303 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2304 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2305 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2306 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2309 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2310 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2311 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2312 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2313 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2314 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2317 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2318 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2319 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2320 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2321 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2322 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2324 // For (192.88.99/24)
2325 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2326 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2327 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2328 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2329 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2330 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2332 // For other IPv4 addresses
2333 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2334 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2335 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2336 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2337 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2338 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2341 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2342 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2343 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2344 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2345 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2346 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2348 // For other IPv6 addresses
2349 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2350 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2351 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2352 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2353 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2354 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2357 assert_eq!(filter_addresses(None), None);